cozyclay 3.1.5 → 3.2.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.
- package/CHANGELOG.md +76 -0
- package/bin/agent/agent-runner.mjs +9 -4
- package/bin/agent/openai-compatible-provider.mjs +24 -1
- package/dist/app/index.html +5 -5
- package/dist/assets/TaskBoard-BUjjuvm5.js +1 -0
- package/dist/assets/{app-CEP7jzXB.css → app-Dige7q3X.css} +1 -1
- package/dist/assets/app-DxoI941o.js +5144 -0
- package/dist/assets/compile-worker-DRWRa9pr.js +6 -0
- package/dist/assets/{motion3-compile-Du7UXrWn.js → motion3-compile-B4SX4TGx.js} +1 -1
- package/dist/assets/scene-asset-sync-LeI3eSnO.js +13 -0
- package/dist/assets/task-board-5PKn7ZaA.js +15 -0
- package/dist/assets/{workflow-DJwOUzqJ.js → workflow-Dg9jCKOq.js} +3 -3
- package/dist/cozyclay-package.json +1 -1
- package/dist/index.html +1 -1
- package/dist/workflow/index.html +3 -3
- package/mcp/project-camera.mjs +43 -0
- package/package.json +3 -1
- package/src/App.jsx +5 -5
- package/src/commands/index.js +2 -1
- package/src/commands/physics.js +21 -0
- package/src/domains/motion.js +7 -9
- package/src/motion/center-of-mass.js +5 -23
- package/src/motion/contact-project.js +143 -0
- package/src/motion/fix-collisions.js +1 -1
- package/src/motion/ik-drag.js +93 -1
- package/src/motion/timeline.css +12 -0
- package/src/motion/timeline.jsx +2 -2
- package/src/motion3/compile-job.js +3 -2
- package/src/motion3/compiler/compile.js +3 -3
- package/src/motion3/compiler/spring.js +95 -0
- package/src/motion3/compiler/validate-objects.js +18 -2
- package/src/motion3/compiler/validate-parts.js +1 -0
- package/src/motion3/compiler/vocab.js +1 -1
- package/src/motion3/fix/index.js +8 -4
- package/src/motion3/fix/person.js +110 -0
- package/src/motion3/free-motion.js +49 -11
- package/src/motion3/object-pose.js +44 -2
- package/src/motion3/people.js +16 -1
- package/src/motion3/physics-frames.js +72 -0
- package/src/motion3/physics-trail.js +45 -0
- package/src/motion3/physics-view.js +79 -0
- package/src/motion3/pipeline.js +5 -1
- package/src/motion3/qa/ballistic.js +67 -0
- package/src/motion3/qa/com.js +140 -0
- package/src/motion3/qa/ground.js +10 -3
- package/src/motion3/qa/hints-contact.js +9 -7
- package/src/motion3/qa/hints-motion.js +38 -1
- package/src/motion3/qa/key-checks.js +5 -4
- package/src/motion3/qa/patch.js +28 -3
- package/src/motion3/qa/people-checks.js +1 -1
- package/src/motion3/qa/spring-pivot.js +23 -0
- package/src/motion3/qa/style.js +13 -30
- package/src/motion3/schema/fields.js +4 -2
- package/src/motion3/schema/topics.js +15 -11
- package/src/motion3/schema/types.js +13 -9
- package/src/physics-overlay-settings.js +41 -0
- package/src/physics-overlay.js +152 -0
- package/src/physics-overlay.jsx +54 -0
- package/src/physics-toggle.jsx +20 -0
- package/src/posestudio.jsx +1 -1
- package/tools/run-tests.mjs +9 -16
- package/tools/verify-package-tarball.mjs +29 -1
- package/dist/assets/TaskBoard-DwXhsJXz.js +0 -1
- package/dist/assets/app-CTKcyPM-.js +0 -5144
- package/dist/assets/compile-worker-or7djI2v.js +0 -6
- package/dist/assets/scene-asset-sync-t45pWCyq.js +0 -13
- package/dist/assets/task-board-CkLZGPkv.js +0 -15
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-hePW80VL.js";var t=e((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var ee=/\/+/g;function A(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function te(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function ne(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,ne(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+A(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(ee,`$&/`)+`/`),ne(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(ee,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u<e.length;u++)a=e[u],s=l+A(a,u),c+=ne(a,r,i,s,o);else if(u=m(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+A(a,u++),c+=ne(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return ne(te(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function re(e,t,n){if(e==null)return e;var r=[],i=0;return ne(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function ie(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var ae=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},oe={map:re,forEach:function(e,t,n){re(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return re(e,function(){t++}),t},toArray:function(e){return re(e,function(e){return e})||[]},only:function(e){if(!O(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=oe,e.Component=v,e.Fragment=r,e.Profiler=a,e.PureComponent=b,e.StrictMode=i,e.Suspense=l,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return w.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=g({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!T.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return E(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)T.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return E(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=O,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:ie}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=w.T,n={};w.T=n;try{var r=e(),i=w.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(C,ae)}catch(e){ae(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),w.T=t}},e.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()},e.use=function(e){return w.H.use(e)},e.useActionState=function(e,t,n){return w.H.useActionState(e,t,n)},e.useCallback=function(e,t){return w.H.useCallback(e,t)},e.useContext=function(e){return w.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return w.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return w.H.useEffect(e,t)},e.useEffectEvent=function(e){return w.H.useEffectEvent(e)},e.useId=function(){return w.H.useId()},e.useImperativeHandle=function(e,t,n){return w.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return w.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return w.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return w.H.useMemo(e,t)},e.useOptimistic=function(e,t){return w.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return w.H.useReducer(e,t,n)},e.useRef=function(e){return w.H.useRef(e)},e.useState=function(e){return w.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return w.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return w.H.useTransition()},e.version=`19.2.8`})),n=e(((e,n)=>{n.exports=t()})),r=e=>e&&typeof e==`object`?Object.freeze({...e}):e,i=Object.freeze([{path:`character.position`,type:`vec3`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,min:{x:-240,y:0,z:-240},max:{x:240,y:240,z:240},gizmo:{min:{x:-4,y:0,z:-4},max:{x:4,y:240,z:4}},note:`y is the feet`},{path:`character.rot`,type:`number`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,min:-180,max:180,angle:!0,note:`yaw degrees, wrapped at the upper bound`},{path:`character.scale`,type:`number`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,min:.2,max:3},{path:`character.subject`,type:`string`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.hidden`,type:`boolean`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.parent`,type:`id`,nullable:!0,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,note:`scene object id the character is grouped under and rides; null stands in the world`},{path:`character.model`,type:`enum`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,enum:[`y-bot-tpose`,`x-bot-tpose`,`proxy-figure`]},{path:`character.posture`,type:`enum`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,enum:[`stand`,`sit`,`lie`]},{path:`character.tint`,type:`color`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.identityImage`,type:`image`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,note:`data:image only`},{path:`character.pose`,type:`id`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`},{path:`character.waypoints`,type:`array`,persisted:!0,undoDomain:`cast`,normalizer:`createCharacterEntry`,actions:[`character.addWaypoint`,`character.moveWaypoint`,`character.removeWaypoint`,`character.clearWaypoints`],note:`root path pins, addressed by frame`},{path:`character.sessionMotion`,type:`array`,persisted:!1,undoDomain:`cast`,normalizer:`createCharacterEntry`,note:`dropped by createCharacterEntry`},{path:`character.ikKeys`,type:`array`,persisted:!1,undoDomain:`cast`,normalizer:`createCharacterEntry`,actions:[`character.setIkKey`,`character.removeIkKey`,`character.clearIkKeys`],note:`dropped by createCharacterEntry; keys travel as JSON quaternions/positions`},{path:`object.renderer`,type:`enum`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,enum:[`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`,`empty`,`light`,`effect`,`text`],note:`light is made from catalogue kind point-light or spot-light; effect (smoke, fire, rain, trail...) from kind effect; text (words, a sign, a logo) from kind text`},{path:`object.position`,type:`vec3`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:{x:-240,y:0,z:-240},max:{x:240,y:240,z:240},note:`y is the object's base: y=0 rests on the floor; height/supportY rise from it`},{path:`object.rotation`,type:`vec3`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:{x:-180,y:-180,z:-180},max:{x:180,y:180,z:180},angle:!0,note:`rot/rotX/rotZ degrees, wrapped at the upper bound`},{path:`object.scale`,type:`vec3`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:{x:.01,y:.01,z:.01},max:{x:100,y:100,z:100}},{path:`object.name`,type:`string`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.color`,type:`color`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.opacity`,type:`number`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,min:.05,max:1,note:`1 is solid; lower is see-through, e.g. 0.4 for a ghost or water; for a glass object use object.material glass`},{path:`object.material`,type:`enum`,sparse:!0,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,enum:[`clay`,`wood`,`straw`,`stone`,`brick`,`concrete`,`metal`,`glass`,`ceramic`,`plastic`,`rubber`,`fabric`,`paper`,`foliage`],note:`cube/sphere/capsule/cylinder/cone/plane only: surface preset with real texture and shine; color stays the tint and a grey (#c2c6c8) object takes the preset's own colour. clay is the default matte look; wood (planks, furniture), straw (thatch, hay, wicker), stone, brick (walls, chimneys), concrete (plaster, pavement), metal (reflects the stage), glass (clear, see-through; tint with color), ceramic (glazed), plastic, rubber (tyres), fabric (cloth, upholstery), paper, foliage (leaves, hedges)`},{path:`object.finish`,type:`enum`,sparse:!0,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,enum:[`matte`,`satin`,`gloss`],note:`with object.material: overrides the preset's shine, e.g. metal + gloss = chrome, glass + matte = frosted, wood + gloss = varnished`},{path:`object.parent`,type:`id`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.attach`,type:`id`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,actions:[`object.attach`,`object.detach`],note:`carried by a character's root or bone; channels convert so the prop stays put`},{path:`object.path`,type:`array`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`},{path:`object.remove`,type:`boolean`,persisted:!0,undoDomain:`objects`,normalizer:null,note:`lifecycle operation, not a document field`},{path:`object.cutout`,type:`image`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,actions:[`asset.import`],note:`assetId-backed cutout record; imported pictures and models are placed by asset.import`},{path:`object.light`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`renderer light only. { type point|spot, color, intensity 0..1000 candela (lighter 0.45, candle 0.3, desk lamp 5, street lamp 40), range m (0 none), angle 1..89 deg spot half-angle, softness 0..1, shadow (first 2 lights only; inside a solid record it is blocked: receipt LIGHT_BLOCKED), flicker 0..1 (lighter 0.6), aim {x,y,z} world point or null = local -Y }, e.g. { intensity: 40, aim: { x: 0, y: 0, z: 1 } }; a take level track scales it`},{path:`object.glow`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`any record: self-lit colour plus additive halo, same under any stage light; casts no shadow, so a light inside a glowing bulb shines out. { color, intensity 0..20, halo 0..4 x the record's radius }, e.g. ember { color: "#ff5a1f", intensity: 6, halo: 2 }; null removes; a take level track scales it`},{path:`object.text`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`renderer text only: words in one record, e.g. object.add { kind: "text", text: { value: "CozyClay", size: 0.4 }, placement: { x, y, z, rot } }. { value: the words (up to 200 characters, \\n starts a line), size m height of a capital letter (default 0.3), depth m (0 = flat lettering in any script, default; above 0 = solid letters for Latin, digits and punctuation, and words with other characters stay flat), align left|center|right for several lines }. The record's footprint and height are measured from the words: x is the centre, y the bottom of the lowest line, and the letters face local +z and read toward local +x, so on a side facing +x set rot 90. Flat lettering on a surface: keep it 3 mm or more off the face. color is the letters' colour`},{path:`object.grasp`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`grasp sockets: where a hand takes hold of the record, in its own axes (m from the base pivot), moving and saving with it. { <name>: { at: [x,y,z], axis?: [x,y,z] the line across the palm (a bar, a handle), from?: [x,y,z] the side the hand comes from (the palm faces against it), thumb?: [x,y,z] the axis end the thumb takes } }, at most 8; null removes. A motion spec anchor { kind: "object", object, socket: <name>, grasp } takes a hand by one; a thin body (a bar, a can, a handle) is a socket of its own, named by its id`},{path:`object.effect`,type:`object`,persisted:!0,undoDomain:`objects`,normalizer:`normalizeSceneObject`,note:`renderer effect only (object.add kind "effect"). { preset: smoke|exhale|steam|fire|sparks|dust|rain|snow|trail, rate particles/s, life s, size m start diameter, grow end/start size, speed m/s along the record's local +Y (rotX 90 aims +Z), spread 0..1 cone, gravity m/s2 (+ falls, - rises), wind {x,y,z} m/s, color, opacity 0..1, additive (emissive: fire, sparks), seed int, area {x,y,z} m birth box (rain/snow/dust fall through it from its top), width m trail ribbon across local Y }. A new preset loads its defaults and fields in the same set override them, e.g. { preset: "fire", rate: 40 }; the record stores the merged numbers. Particles are born where the record is at each frame (route, parent, take carry), only while it and its parents are shown, at rate x the take level. To emit from the body (a breath at the mouth), a motion spec entry objects.<id> = { follow: "landmark:mouth", aim: "face" } moves it there every frame. Measure with inspect_studio { scope: "entities", ids }: effect { frame (the playhead), alive, emitter [x,y,z], bounds { min, max } m }`},{path:`stage.keyLight.x`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:-30,max:30},{path:`stage.keyLight.y`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:.5,max:30},{path:`stage.keyLight.z`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:-30,max:30},{path:`stage.keyLight.intensity`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:4},{path:`stage.keyLight.warmth`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1},{path:`stage.environmentImage`,type:`image`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`data:image only`},{path:`stage.environment`,type:`string`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`location description every shot prompt is built from`},{path:`stage.style`,type:`string`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`look / style line for shot prompts`},{path:`stage.hasEnvSheet`,type:`boolean`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`author supplies an environment sheet instead of a description`},{path:`stage.camera`,documentPath:`shotAspect`,type:`enum`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,enum:[`16:9`,`2.39:1`,`9:16`,`1:1`,`4:3`,`12:7`,`fal 480P`],note:`output aspect ratio`},{path:`stage.cameraPresetId`,type:`id`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`},{path:`stage.sensorId`,type:`enum`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,enum:[`super16`,`super35`,`fullFrame`,`65mm`]},{path:`stage.keyLight.color`,type:`color`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`key light colour #rrggbb, overrides warmth, e.g. "#9db6e6" cool moonlight or "#ffad5c" low sun; null = white tinted by warmth`},{path:`stage.lighting.preset`,type:`enum`,persisted:!0,readOnly:!0,undoDomain:`stage`,normalizer:`createSceneStage`,enum:[`studio`,`day`,`overcast`,`golden`,`dusk`,`night`,`interior`,`stage`],note:`label of the last recipe stage.applyLighting applied; studio is the neutral grey default`},{path:`stage.lighting.sky`,type:`color`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`background and fog colour at the horizon, e.g. "#0b1426" night; null = the UI theme's studio grey`},{path:`stage.lighting.skyTop`,type:`color`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`sky colour overhead: shot camera and exports grade from sky at the horizon to this, e.g. "#020408"; null = flat sky`},{path:`stage.lighting.ambient`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:3,note:`multiplier on the hemisphere and ambient light; 1 = studio, 0.6 = night, 0 = black stage`},{path:`stage.lighting.hemiSky`,type:`color`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`hemisphere light from above, e.g. "#34507f" cool night sky; studio "#ffffff"`},{path:`stage.lighting.hemiGround`,type:`color`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`hemisphere bounce from below, e.g. "#6e5136" warm ground; studio "#5a5d64"`},{path:`stage.lighting.fill`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:3,note:`multiplier on the fixed fill and rim lights; 1 = studio, 0 = key only`},{path:`stage.lighting.fog`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1,note:`haze 0..1 fading the set into the sky colour: 0 = far horizon only, 0.45 = from ~18 m to ~38 m, 1 = from 2 m to 14 m`},{path:`stage.lighting.exposure`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:.2,max:3,note:`camera exposure multiplier on lit surfaces; 1 = studio, e.g. 1.4 to lift a dark frame`},{path:`stage.lighting.shadowSoftness`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1,note:`key shadow penumbra; 0 = crisp (studio), 0.75 = soft moonlight, 1 = overcast`},{path:`stage.lighting.envLight`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:2,note:`sky environment light on every surface: a map from sky, skyTop, hemiGround and a glow toward the key (sun or moon) tints and fills clay from all sides; it takes over the flat hemisphere as it rises. 0 = hemisphere only (studio), 1 = the map alone at the same brightness (every other recipe), e.g. 1.4 for a brighter fill`},{path:`stage.lighting.ao`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:1,note:`ambient occlusion strength: contact darkening within ~0.5 m where a body meets the floor or a prop and in creases (armpits, the back of a squat's knees), in the viewport and every export. 0 = off (studio), 0.8 = most recipes, 1 = overcast`},{path:`stage.lighting.hdr`,type:`id`,nullable:!0,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`HDR environment map that replaces the sky environment light: a built-in ("builtin:night-street", "builtin:overcast-field", "builtin:studio-softbox") or a file the user loaded ("hdr-<32 hex>"); inspect_studio { scope: "catalogue" } environments lists them with each map's brightest direction. It lights the set only while envLight > 0 (its light = map x hdrIntensity x envLight; studio has envLight 0, so set envLight 1). stage.applyLighting clears it unless keep has "lighting.hdr". null = the look's own sky`},{path:`stage.lighting.hdrRotation`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:-180,max:180,angle:!0,note:`degrees the HDR map turns about the vertical axis, light and backdrop together: +90 carries a light at +x (screen right from the default camera) to -z (behind the subject), so a brightest [x, y, z] lands at [x cos r + z sin r, y, z cos r - x sin r]; wrapped at the upper bound`},{path:`stage.lighting.hdrIntensity`,type:`number`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,min:0,max:4,note:`multiplier on the HDR map's radiance in its light and its backdrop; 1 = the file as authored, e.g. 0.5 to calm a bright daylight map`},{path:`stage.lighting.hdrBackground`,type:`boolean`,persisted:!0,undoDomain:`stage`,normalizer:`createSceneStage`,note:`true = the HDR map is the backdrop behind the set (the floor fades into its horizon), in the viewport, shot and every export; false = keep the look's sky as the backdrop and use the map only as light`},{path:`shot.crud`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:null,actions:[`shot.create`,`shot.split`,`shot.duplicate`,`shot.remove`,`shot.setRange`,`shot.reorder`],note:`create/split/duplicate/reorder/remove/range through the shared action registry`},{path:`shot.cameraKeys`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:null,frameMin:0},{path:`shot.cameraRail`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:`repairCamera`,actions:[`shot.setCameraRail`,`shot.clearCameraRail`],note:`rail points; crane/dolly timing follow the shot's camera block`},{path:`shot.targetModel`,type:`id`,persisted:!0,undoDomain:`shot`,normalizer:`repairCamera`},{path:`shot.kind`,type:`enum`,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,enum:[`clip`,`still`],note:`clip or still; a still holds one picture for endFrame - startFrame + 1 frames`},{path:`shot.caption`,type:`string`,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,note:`trimmed, at most 500 characters`},{path:`shot.cast`,type:`array`,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,note:`per-shot placement overrides keyed by character id: { x, z, rot, posture?, pose? }`},{path:`shot.stylizedAssetId`,type:`id`,nullable:!0,persisted:!0,undoDomain:`shot`,normalizer:null,readOnly:!0,note:`image asset id only`},{path:`shot.freeCamera`,type:`vec3`,persisted:!1,undoDomain:`shot`,normalizer:null,note:`transient until keyed`},{path:`scenes`,type:`array`,persisted:!0,undoDomain:null,normalizer:null,actions:[`scene.create`,`scene.duplicate`,`scene.rename`,`scene.delete`,`scene.switch`],note:`the project's scene list and the open scene; outside the undo history`},{path:`project`,type:`string`,persisted:!0,undoDomain:null,normalizer:null,actions:[`project.save`],note:`save to the current project file; opening one needs the user's file picker`},{path:`selection`,type:`id`,persisted:!1,undoDomain:null,normalizer:null},{path:`timeline`,type:`number`,persisted:!1,undoDomain:null,normalizer:null},{path:`view.mode`,type:`enum`,persisted:!1,undoDomain:null,normalizer:null,enum:[`scene`,`pose`,`camera`,`motion`]},{path:`view.partColoursGuideModeInset`,type:`array`,persisted:!1,undoDomain:null,normalizer:null,actions:[`view.setPartColours`,`view.setGuideMode`,`view.setInset`,`view.setGhosts`],note:`partColours/guideMode/inset/ghosts; viewer settings, not document fields`},{path:`read.sceneDescription`,type:`string`,persisted:!1,undoDomain:null,normalizer:null},{path:`read.captureFrame`,type:`image`,persisted:!1,undoDomain:null,normalizer:null},{path:`undo`,type:`boolean`,persisted:!1,undoDomain:null,normalizer:null}].map(e=>Object.freeze({...e,...e.enum?{enum:Object.freeze([...e.enum])}:{},...e.actions?{actions:Object.freeze([...e.actions])}:{},...e.min&&typeof e.min==`object`?{min:r(e.min)}:{},...e.max&&typeof e.max==`object`?{max:r(e.max)}:{},...e.gizmo?{gizmo:Object.freeze({min:r(e.gizmo.min),max:r(e.gizmo.max)})}:{}})));function a(e){return i.find(t=>t.path===e)}var o=e=>e.persisted!==!1&&!e.actions&&!e.readOnly,s=Object.freeze(`INVALID_ARGUMENT.INVALID_CONTEXT.INVALID_IDENTITY.INVALID_TURN_ID.INVALID_SESSION_ID.INVALID_RECEIPT.INVALID_RANGE.INVALID_REQUEST.UNKNOWN_TOOL.UNKNOWN_VARIANT.DUPLICATE_NAME.CONTEXT_LIMIT.CONTEXT_TOO_LARGE.AMBIGUOUS_TARGET.AMBIGUOUS_BASIS.TARGET_NOT_READY.TARGET_BUSY.STALE_TARGET.STALE_SCENE.STALE_ENVIRONMENT.STALE_CURSOR.CAPABILITY_MISSING.LIVE_HUB_UNAVAILABLE.AUTH_REQUIRED.GENERATION_LIMIT.RATE_LIMITED.BACKEND_UNAVAILABLE.VERIFICATION_FAILED.REPAIR_REGRESSED.CANCELLED.UNCERTAIN_APPLY.UNDO_CONFLICT.CONFIRMATION_REQUIRED.TIMEOUT.UNDO_EXPIRED.INTERNAL_ERROR.SCOPE_DENIED.SCOPE_BUSY`.split(`.`)),c=e=>e?.code??([`TypeError`,`ReferenceError`,`RangeError`,`SyntaxError`].includes(e?.name)?`INTERNAL_ERROR`:`INVALID_ARGUMENT`),l=`#c2c6c8`,u=[`#e2e5e6`,l,`#9aa1a5`,`#767d81`,`#d9b18c`,`#8fae9b`,`#d94a4a`,`#4a7bd9`,`#e2c04a`,`#4fa86a`],d=6,f=`cozyclay.objectColors.recent`,p=/^#?([0-9a-f]{3})$/i,m=/^#?([0-9a-f]{6})$/i;function h(e){if(typeof e!=`string`)return null;let t=e.trim(),n=p.exec(t);if(n)return`#${n[1].toLowerCase().replace(/./g,e=>e+e)}`;let r=m.exec(t);return r?`#${r[1].toLowerCase()}`:null}function g(e,t){let n=Array.isArray(e)?e.map(h).filter((e,t,n)=>e&&n.indexOf(e)===t&&!u.includes(e)):[],r=h(t),i=(r&&!u.includes(r)?[r,...n.filter(e=>e!==r)]:n).slice(0,d);return Array.isArray(e)&&i.length===e.length&&i.every((t,n)=>t===e[n])?e:i}function _(e){try{let t=JSON.parse(e?.getItem(f)??`[]`);return g(Array.isArray(t)?t:[],null)}catch{return[]}}function v(e,t){try{e?.setItem(f,JSON.stringify(t))}catch{}}var y=`effect`,b={kind:y,label:`Effect`,group:`Effects`,footprint:{width:0,depth:0},height:0,color:`#7fd4f0`},x=(e,t,n)=>({x:e,y:t,z:n}),S=x(0,0,0),C=Object.freeze({smoke:{rate:60,life:2.8,size:.012,grow:6,speed:.05,spread:.1,gravity:-.3,wind:x(.02,0,0),color:`#7d8a99`,opacity:.42,additive:!1,area:S,width:0},exhale:{rate:120,life:2.4,size:.035,grow:8,speed:.9,spread:.35,gravity:-.35,wind:x(.02,0,0),color:`#a3abb4`,opacity:.3,additive:!1,area:x(.01,0,.01),width:0},steam:{rate:26,life:2,size:.03,grow:4,speed:.1,spread:.2,gravity:-.45,wind:x(.02,0,0),color:`#bcc5ce`,opacity:.2,additive:!1,area:x(.07,0,.07),width:0},fire:{rate:140,life:.75,size:.12,grow:.3,speed:.4,spread:.15,gravity:-2.2,wind:S,color:`#ff7a1f`,opacity:1,additive:!0,area:x(.22,0,.22),width:0},sparks:{rate:40,life:1,size:.012,grow:.6,speed:2.6,spread:.55,gravity:6,wind:S,color:`#ff9d33`,opacity:1,additive:!0,area:x(.05,0,.05),width:0},dust:{rate:30,life:7,size:.014,grow:1.2,speed:0,spread:1,gravity:.01,wind:x(.04,0,.01),color:`#a89a82`,opacity:.55,additive:!1,area:x(3,2.2,3),width:0},rain:{rate:1600,life:1.2,size:.01,grow:1,speed:0,spread:0,gravity:9.8,wind:S,color:`#9aabbd`,opacity:.4,additive:!1,area:x(8,5,8),width:0},snow:{rate:220,life:8,size:.025,grow:1,speed:0,spread:0,gravity:9.8,wind:x(.1,0,0),color:`#ffffff`,opacity:.85,additive:!1,area:x(8,4,8),width:0},trail:{rate:0,life:.3,size:0,grow:1,speed:0,spread:0,gravity:0,wind:S,color:`#a7b8ca`,opacity:.75,additive:!1,area:S,width:.5}}),w=Object.freeze(Object.keys(C)),T={rate:[0,2e3],life:[.05,12],size:[.001,5],grow:[.05,20],speed:[0,60],spread:[0,1],gravity:[-30,30],opacity:[0,1],width:[0,10]},E={wind:[-20,20],area:[0,100]},D=2147483647,O=([e,t],n,r)=>{let i=Number(n);return Number.isFinite(i)?Math.min(t,Math.max(e,i)):r};function k(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n=w.includes(t.preset)?t.preset:`smoke`,r=C[n],i={preset:n};for(let[e,n]of Object.entries(T))i[e]=O(n,t[e],r[e]);for(let[e,n]of Object.entries(E)){let a=t[e]&&typeof t[e]==`object`?t[e]:{};i[e]=x(...[`x`,`y`,`z`].map(t=>O(n,a[t],r[e][t])))}i.color=h(t.color)??r.color,i.additive=typeof t.additive==`boolean`?t.additive:r.additive;let a=Number(t.seed);return i.seed=Number.isFinite(a)?Math.min(D,Math.max(0,Math.round(a))):1,i}function ee(e){return e?.renderer===`effect`?{effect:k(e.effect)}:{}}function A(e,t){let n=e?.set?.effect?.preset;if(!w.includes(n))return e;let r=t?.find?.(t=>t.id===e.id)?.effect;if(r?.preset===n)return e;let i=structuredClone(C[n]);return{...e,set:{...e.set,effect:{...i,seed:r?.seed??1,...e.set.effect}}}}var te=(e,t)=>({type:`number`,minimum:e,maximum:t}),ne=([e,t])=>({type:`object`,properties:{x:te(e,t),y:te(e,t),z:te(e,t)},required:[],additionalProperties:!1}),re=Object.freeze({type:`object`,properties:{preset:{type:`string`,enum:[...w]},...Object.fromEntries(Object.entries(T).map(([e,[t,n]])=>[e,te(t,n)])),...Object.fromEntries(Object.entries(E).map(([e,t])=>[e,ne(t)])),color:{type:`string`,minLength:1,maxLength:32,pattern:`^#[0-9a-fA-F]{6}$`},additive:{type:`boolean`},seed:{type:`integer`,minimum:0,maximum:D}},required:[],additionalProperties:!1}),ie=`text`,ae=[375,307,454,1117,800,1213,1007,289,486,486,828,828,303,525,303,828,828,828,828,828,828,828,828,828,828,828,304,306,828,828,828,785,1374,1069,938,1043,968,824,778,1057,953,365,760,996,763,1135,949,1094,838,1096,947,915,894,926,997,1399,999,931,906,444,532,446,828,828,288,786,822,828,836,808,525,839,782,326,361,771,363,1174,782,871,824,833,513,775,511,782,828,1150,826,828,753,599,240,597,949],oe=Object.freeze({resolution:1e3,ascent:1090,descent:333}),se=1.5,ce=1.25,le=.8,ue=.005,de={size:[.02,10],depth:[0,2]},fe=200,pe=8,me=[`left`,`center`,`right`],he=Object.freeze({value:`Text`,size:.3,depth:0,align:`center`}),ge={kind:ie,label:`Text`,group:`Text`,footprint:{width:1,depth:ue},height:.3,color:l},_e=Object.freeze({type:`object`,properties:{value:{type:`string`,minLength:1,maxLength:fe},size:{type:`number`,minimum:de.size[0],maximum:de.size[1]},depth:{type:`number`,minimum:de.depth[0],maximum:de.depth[1]},align:{type:`string`,enum:me}},required:[],additionalProperties:!1}),ve=([e,t],n,r)=>{let i=Number(n);return Number.isFinite(i)?Math.min(t,Math.max(e,i)):r};function ye(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{},n=[...(typeof t.value==`string`?t.value.replace(/\r\n?/g,`
|
|
2
|
+
`).split(`
|
|
3
|
+
`).slice(0,pe):[]).join(`
|
|
4
|
+
`)].slice(0,fe).join(``);return{value:n.trim()?n:he.value,size:ve(de.size,t.size,he.size),depth:ve(de.depth,t.depth,he.depth),align:me.includes(t.align)?t.align:he.align}}var be=e=>e>=4352&&e<=4607||e>=11904&&e<=42191||e>=44032&&e<=55215||e>=63744&&e<=64255||e>=65280&&e<=65519;function xe(e){let t=e.codePointAt(0);return t>=32&&t<=126?ae[t-32]/oe.resolution:be(t)?ce:le}function Se(e){return e.depth>0&&[...e.value].every(e=>e===`
|
|
5
|
+
`||e.codePointAt(0)>=32&&e.codePointAt(0)<=126)}function Ce(e){let{size:t,align:n}=e,r=e.value.split(`
|
|
6
|
+
`),i=r.map(e=>[...e].reduce((e,t)=>e+xe(t),0)*t),a=Math.max(...i,t*.2),o=oe.descent/oe.resolution*t;return{width:a,height:(r.length-1)*se*t+(oe.ascent+oe.descent)/oe.resolution*t,rows:r.map((e,s)=>({text:e,width:i[s],x:n===`left`?-a/2:n===`right`?a/2-i[s]:-i[s]/2,baseline:o+(r.length-1-s)*se*t}))}}function we(e){if(e?.renderer!==`text`)return{};let t=ye(e.text),{width:n,height:r}=Ce(t),i=e=>Number(e.toFixed(4));return{text:t,footprint:{width:i(n),depth:i(Math.max(t.depth,ue))},height:i(r),supportY:i(r)}}function Te(e,t){if(e?.renderer!==`text`||t?.text===void 0||!t.text||typeof t.text!=`object`)return{};let n=we({renderer:ie,text:{...e.text,...t.text}});return JSON.stringify(n.text)===JSON.stringify(e.text)?{}:n}var Ee=24,De=40,Oe=e=>{let t=JSON.stringify(e)??String(e);return t.length>De?`${t.slice(0,37)}...`:t},ke=e=>e===null?`null`:Array.isArray(e)?`an array`:typeof e==`object`?`an object`:typeof e==`number`&&!Number.isFinite(e)?String(e):`a ${typeof e}`,Ae=e=>e.length>Ee?`${e.slice(0,Ee).join(`, `)}, ... (${e.length} in all)`:e.join(`, `),je=e=>Object.hasOwn(e,`const`)?JSON.stringify(e.const):e.type===`integer`?`an integer`:e.type===`array`?`an array${e.items?.type?` of ${e.items.type}s`:``}`:e.type===`object`?`an object`:e.type===`null`?`null`:`a ${e.type}`,Me=(e,t,n)=>`${e}: expected ${je(t)}, got ${Object.hasOwn(t,`const`)?Oe(n):ke(n)}.`,Ne=(e,t,n)=>{let r=Object.keys(t.properties);return`${e} has unknown field ${Oe(n)}; ${r.length?`allowed: ${Ae(r)}`:`it takes no fields`}.`},Pe=(e,t)=>`${e}: missing required field "${t}".`;function Fe(e,t,n){if(!Array.isArray(n))return Me(e,t,n);let r=t.minItems??0,i=t.maxItems??1/0;return`${e}: expected ${r===i?`exactly ${r}`:i===1/0?`at least ${r}`:r===0?`at most ${i}`:`${r} to ${i}`} item${r===i&&r===1?``:`s`}, got ${n.length}.`}var Ie=(e,t)=>{let n=new Set,r=t.map(e=>JSON.stringify(e)).find(e=>n.has(e)?!0:(n.add(e),!1));return`${e}: items must be unique; ${r&&r.length<=De?r:`one item`} appears twice.`};function Le(e,t,n){if(typeof n!=`string`)return Me(e,t,n);if(!n.trim())return`${e}: must not be empty.`;let r=[...n].length;return t.maxLength!==void 0&&r>t.maxLength?t.description?`${e}: over ${t.maxLength} characters. ${t.description}`:`${e}: at most ${t.maxLength} characters, got ${r}.`:`${e}: ${Oe(n)} does not match ${t.pattern}.`}var Re=(e,t,n)=>`${e}: ${Oe(n)} is not one of: ${Ae(t.enum)}.`;function ze(e,t,n){return typeof n!=`number`||!Number.isFinite(n)?Me(e,t,n):t.type===`integer`&&!Number.isSafeInteger(n)?`${e}: expected an integer, got ${n}.`:`${e}: must be greater than ${t.exclusiveMinimum}, got ${n}.`}var Be=e=>e.oneOf??e.anyOf?(e.oneOf??e.anyOf).every(Be):e.type!==`object`&&e.type!==`array`,Ve=e=>[e.minimum,e.maximum].some(e=>e!==void 0)?` within [${[e.minimum??`-inf`,e.maximum??`inf`].join(`, `)}]`:``,He=e=>e.oneOf??e.anyOf?(e.oneOf??e.anyOf).flatMap(He):Object.hasOwn(e,`const`)?[JSON.stringify(e.const)]:e.enum?e.enum.map(e=>JSON.stringify(e)):e.type===`boolean`?[`true`,`false`]:[`${je(e)}${e.type===`number`||e.type===`integer`?Ve(e):``}`];function Ue(e,t,n){if(!t.every(({error:t})=>t.details?.path===e)||typeof n==`object`&&n&&!t.every(({branch:e})=>Be(e)))return null;let r=[...new Set(t.flatMap(({branch:e})=>He(e)))],i=r.length>Ee?[...r.slice(0,Ee),`... (${r.length} in all)`]:r;return`${e} must be ${i.length>1?`${i.slice(0,-1).join(`, `)} or ${i.at(-1)}`:i[0]}, got ${typeof n==`object`&&n?ke(n):Oe(n)}.`}var We=[`storyboard`,`animation`],Ge=[`stand`,`sit`,`lie`],Ke=65536,qe=Object.freeze({entities:24,entityIndex:400,shots:8,assets:48,recentReceipts:3,jobs:8}),Je=Object.freeze([`inspect_studio`,`run_action`,`verify_result`]);Object.freeze([`operate_studio`,`arrange_objects`,`arrange_characters`,`patch_elements`,`frame_shot`,`undo_edit`]);var Ye=Object.freeze({inspect_studio:`Read the scene`,operate_studio:`Selection and view`,arrange_objects:`Arrange objects`,arrange_characters:`Arrange characters`,patch_elements:`Edit properties`,frame_shot:`Frame the shot`,verify_result:`Verify the result`,undo_edit:`Undo an edit`,run_action:`Run an editor action`}),Xe=Object.freeze(Object.keys(Ye)),Ze=Object.freeze([`character`,`object`,`shot`,`stage`]),Qe=tt({selectionKinds:[`scene`,`object`,`character`,`rig`,`camera`],modes:[`scene`,`pose`,`camera`,`motion`],shotModes:[`keys`,`follow`,`rail`],framingSizes:[`extreme close-up`,`close-up`,`medium close-up`,`medium shot`,`medium-wide shot`,`wide shot`,`extreme wide shot`],framingViews:[`front`,`front three-quarter`,`profile`,`rear three-quarter`,`back`],framingLevels:[`ground`,`low`,`hip`,`eye`,`high`,`overhead`],framingSides:[`left`,`right`],positionSides:[`left`,`right`,`front`,`behind`],positionBases:[`world`,`subject`,`shot_camera`],collisionPolicies:[`report`,`avoid`],objectOps:[`create`,`update`,`remove`,`group`,`ungroup`],characterOps:[`create`,`update`,`remove`],inspectionScopes:[`selection`,`scene`,`entities`,`shot`,`motion`,`catalogue`,`actions`,`document`],receiptStatuses:[`applied`,`partial`,`noop`,`transient`,`installed`,`undone`],opStatuses:[`applied`,`partial`,`noop`],jobStates:[`queued`,`generating`,`preparing`,`verifying`,`repairing`,`committing`,`reconciling`,`installed`,`review_required`,`failed`,`cancelled`,`stale_target`,`stale_environment`]}),$e=class extends Error{constructor(e,t,n={}){super(t),this.name=`StudioProtocolError`,this.code=e,this.details=n}toJSON(){return{code:this.code,message:this.message,...Object.keys(this.details).length?{details:this.details}:{}}}},et=e=>new TextEncoder().encode(e).byteLength;function tt(e){if(e&&typeof e==`object`&&!Object.isFrozen(e)){for(let t of Object.values(e))tt(t);Object.freeze(e)}return e}var j=(e,t,n=`$`,r={})=>{throw new $e(e,t,{path:n,...r})},nt=e=>typeof e==`object`&&!!e&&!Array.isArray(e),rt=(e=120)=>({type:`string`,minLength:1,maxLength:e}),M=(e,t)=>({type:`number`,...e===void 0?{}:{minimum:e},...t===void 0?{}:{maximum:t}}),N=(e=0,t=2**53-1)=>({...M(e,t),type:`integer`}),P={type:`boolean`},F=e=>({const:e}),I=e=>({type:`string`,enum:e}),it=e=>({oneOf:[e,{type:`null`}]}),at=(e,t,n=0,r=!1)=>({type:`array`,items:e,minItems:n,maxItems:t,...r?{uniqueItems:r}:{}}),L=(e,t={})=>({type:`object`,properties:{...e,...t},required:Object.keys(e),additionalProperties:!1}),ot=(...e)=>({oneOf:e}),st={type:`object`,properties:{},required:[],additionalProperties:!0},R={...rt(),pattern:`^[A-Za-z0-9][A-Za-z0-9._:-]*$`},ct={...rt(36),pattern:`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`},lt=L({x:M(),y:M(),z:M()}),ut={type:`number`,exclusiveMinimum:0},dt=L({x:ut,y:ut,z:ut}),ft={...L({startFrame:N(),endFrameExclusive:N(1)}),"x-studio-range":!0},pt=(e=100,t=1)=>at(R,e,t,!0),mt=rt(120),ht={...rt(120),description:`Object id, or the name of a part created EARLIER in this ops list (create it first).`},gt={workspaceId:R,documentEpoch:R,sceneId:R,sceneEpoch:R},_t=L(gt),vt=L({surface:F(`studio`),...gt,workspaceHandle:it(R)}),yt=L({scene:N(),physics:N(),view:N()}),bt=it(L({kind:I(Qe.selectionKinds),id:R},{hierarchyId:R})),xt=L({mode:I(Qe.modes),frame:N(),playing:P,lookThrough:P,grid:P,autoColor:P}),St=ot(L({world:lt}),L({relativeTo:ht,basis:I(Qe.positionBases),side:I(Qe.positionSides),gapM:M(0),support:ot(F(`floor`),L({objectId:ht}))}),L({between:at(ht,2,2,!0),fraction:M(0,1),support:F(`floor`)}),L({onObject:ht},{offsetXZ:L({x:M(),z:M()})})),Ct=ot(L({yawDeg:M()}),L({towardId:ht}),L({sameAsId:ht}),L({awayFromId:ht})),wt=ot(L({intent:L({size:I(Qe.framingSizes),view:I(Qe.framingViews),level:I(Qe.framingLevels),side:I(Qe.framingSides)},{focalMm:ut})}),L({exact:L({position:lt,lookAt:lt,focalMm:ut})})),Tt={...I([`parent`]),description:`"parent" reads position.world, rotationDeg and facing.yawDeg in the parent's local frame (its pivot and rotation, not its scale); omit for world space.`},Et=ot(L({op:F(`create`),source:L({kind:R}),position:St},{name:mt,facing:Ct,scale:dt,rotationDeg:{...lt,description:`Euler XYZ degrees (x pitch, y yaw, z roll), as in update. Exclusive with facing. A pitched/rolled part rests its lowest corner on its support.`},parent:{...mt,description:`Group this new object under a parent: an existing object id, or the name of an object created earlier in this same ops list. Moving the parent then moves it too.`},space:Tt}),L({op:F(`update`),id:R},{position:St,facing:Ct,rotationDeg:lt,scale:dt,color:rt(32),name:mt,hidden:P,space:Tt}),L({op:F(`remove`),id:R}),L({op:F(`group`),parentId:R,childIds:pt()}),L({op:F(`ungroup`),childIds:pt()})),Dt=ot(L({op:F(`create`),name:mt,position:St},{facing:Ct,scale:ut}),L({op:F(`update`),characterId:R},{position:St,facing:Ct,scale:ut,name:mt,hidden:P}),L({op:F(`remove`),characterId:R})),Ot={...rt(2097152),pattern:`^data:image/[A-Za-z0-9.+-]+[;,]`},kt=L({frame:N(),framing:L({pos:lt,yaw:M(),pitch:M(),fovDeg:M(1,179)})},{id:R}),At=ot(M(0,1),L({t:M(0,1)},{bank:M(-90,90),pitch:M(-90,90)})),jt=it(L({points:at(lt,64,2)},{speed:M(0,50),faceTravel:P,loop:P,extend:P,marks:at(At,6)})),Mt=L({},{type:I([`point`,`spot`]),color:{...rt(32),pattern:`^#[0-9a-fA-F]{6}$`},intensity:M(0,1e3),range:M(0,100),angle:M(1,89),softness:M(0,1),shadow:P,flicker:M(0,1),aim:it(lt)}),Nt=it(L({},{color:{...rt(32),pattern:`^#[0-9a-fA-F]{6}$`},intensity:M(0,20),halo:M(0,4)})),Pt=it(st),Ft={"character.pose":it(R),"character.identityImage":it(Ot),"object.light":Mt,"object.glow":Nt,"object.grasp":Pt,"object.effect":re,"object.text":_e,"object.parent":it(R),"object.path":jt,"stage.environmentImage":it(Ot),"shot.cameraKeys":at(kt,64),"shot.targetModel":it(R)};function It(e){if(Object.hasOwn(Ft,e.path))return Ft[e.path];if(e.type===`number`)return M(e.min,e.max);if(e.type===`boolean`)return P;if(e.type===`enum`)return I([...e.enum]);if(e.type===`id`)return R;if(e.type===`color`)return{...rt(32),pattern:`^#[0-9a-fA-F]{6}$`};if(e.type===`image`)return it(Ot);if(e.type===`vec3`){let{min:t,max:n}=e;return t&&typeof t==`object`&&n&&typeof n==`object`?L({x:M(t.x,n.x),y:M(t.y,n.y),z:M(t.z,n.z)}):lt}return e.type===`string`?rt(240):null}function Lt(e){return e.filter(o).map(({path:e,type:t,min:n,max:r,enum:i,note:a})=>({path:e,type:t,...n===void 0?{}:{min:n&&typeof n==`object`?{...n}:n},...r===void 0?{}:{max:r&&typeof r==`object`?{...r}:r},...i?{enum:[...i]}:{},...a?{note:a}:{}}))}var Rt=tt(Lt(i));function zt(e){let t={};for(let n of Ze){let r={};for(let t of e){if(!o(t)||!t.path.startsWith(`${n}.`))continue;let e=It(t);e&&(r[t.path.slice(n.length+1)]=e)}t[n]={type:`object`,properties:r,required:[],additionalProperties:!1}}return t}var Bt=tt(zt(i)),Vt=tt(Object.fromEntries(Ze.map(e=>[e,Object.keys(Bt[e].properties).map(t=>`${e}.${t}`)]))),Ht=ot(L({target:L({kind:F(`character`),id:R}),set:Bt.character}),L({target:L({kind:F(`object`),id:R}),set:Bt.object}),L({target:L({kind:F(`shot`)},{id:R}),set:Bt.shot}),L({target:L({kind:F(`stage`)}),set:Bt.stage})),Ut={inspect_studio:L({scope:I(Qe.inspectionScopes)},{ids:pt(32),select:pt(32),query:mt,cursor:rt(512),limit:{...N(1,32),default:12}}),operate_studio:L({},{selection:bt,shotId:R,frame:N(),playing:P,mode:I(Qe.modes),view:L({},{lookThrough:P,grid:P,autoColor:P})}),arrange_objects:L({ops:{...at(Et,100,1),description:`Applied in order, as one undo step. Each op sees the parts created by earlier ops, so build an assembly in one call: create the main part, then place the rest with position.onObject / relativeTo(+side,gapM) / between naming earlier parts (e.g. relativeTo "Hood"). Reference parts created in this call by name, never by id.`}},{collisionPolicy:{...I(Qe.collisionPolicies),default:`report`}}),arrange_characters:L({ops:at(Dt,8,1)}),patch_elements:L({ops:at(Ht,32,1)}),frame_shot:L({subjectIds:pt(1),framing:wt},{shotId:R,caption:{type:`string`,maxLength:500},keyAtFrame:N()}),verify_result:L({checks:{...at(I([`placement`,`framing`,`motion`,`lighting`]),4,1,!0),description:`lighting measures the shot frame rendered at the playhead: checks.lighting { meanLuma 0..1, clippedPct (a channel at full scale), crushedPct (pure black), subjects: [{ id, meanLuma, contrast (5th to 95th percentile luma spread, 0..1) }] inside each target character's projected box, look: { preset, envLight, ao } the stage look's environment light and occlusion strength }. motion also answers exportFraming (one per character with a take): what the camera the export renders shows of the take over sampledFrames: camera (shot where a shot covers the frame, studio = the Studio camera as it stands when none does; shotIds), character { screenFraction [min, max] of the frame height, inFrame [lowest share of its joints' screen box inside the frame, frame], behindCamera, cut { head, hand_l, hand_r, foot_l, foot_r } }, and every object the take names { id, name, inFrame, out, cut }; out, cut and behindCamera are spans [first, last] of sampled frames; { character: { id }, reason } when it cannot be measured`}},{receiptId:R,targets:pt(),range:ot(F(`whole_clip`),ft),visual:{...I([`none`,`frame`,`contact_sheet`,`plan`,`trace`]),default:`none`},frames:{...ot(I([`even`,`beats`]),at(N(),8,1,!0)),default:`even`,description:`contact_sheet frames: even spacing, beats (grab/release, beat starts, the worst QA frames, then even fill, answered in visualRefs[0].picks), or up to 8 timeline frames of your choice`},views:{...at(I([`front`,`side`,`three-quarter`,`top`]),2,1,!0),description:`contact_sheet from cameras of its own around the character instead of the shot camera (which stays as it is): a row per view, each held still over the frames and framed on focus, so small actions fill the tile; side and three-quarter look from the focus's side; a sheet always holds two views at least 60 degrees apart: if the asked ones look along nearly one line, side, front or top is added and named in visualRefs[0].addedView`},focus:{...ot(rt(120),at(rt(120),3,1,!0)),description:`with views: what to frame, as refs (object:<id>, joint:<Bone>, prop:<prop>.<point>, landmark:mouth); default the whole character`},trail:{...ot(rt(120),at(rt(120),3,1,!0)),description:`with views: refs whose path over the range is drawn as one dot per frame (spacing shows speed; later frames faint, the tile's own frame ringed), colours in visualRefs[0].trails`},ghosts:{...P,description:`with views: each tile also shows the first target's poses around its frame as translucent ghosts (onion skin), earlier ones blue, later ones orange, carried props included, so spacing and arcs read in one tile; how many and how far apart is view.setGhosts (while it is off: 3 each side, every 4 frames), answered in visualRefs[0].ghosts`}}),undo_edit:L({receiptId:R}),run_action:L({action:R},{args:st,confirmationToken:R})},Wt=tt(Ut),Gt=tt(Xe.map(e=>({name:e,slice:1,parameters:Ut[e]}))),Kt=L({min:lt,max:lt}),qt=L({id:R,kind:I([`object`,`character`,`rig`]),token:R},{name:mt,detailsOmitted:P,position:lt,yawDeg:M(),rotationDeg:lt,scale:ot(ut,dt),bounds:it(Kt),libraryKind:R,renderer:R,color:it(rt(32)),tint:it(rt(32)),modelId:it(rt(120)),assetId:R,parentId:it(R),attachment:it(L({characterId:R,bone:it(R)})),pathPointCount:N(0,64),pathMarks:at(ot(M(0,1),L({t:M(0,1)},{bank:M(-90,90),pitch:M(-90,90)})),6),local:L({position:lt,rotationDeg:lt}),motion:L({takeId:it(R),frames:N(),ikKeyCount:N()},{poseId:it(R),keyIds:pt(8,0)}),capabilities:L({rigReady:P,ik:P,measuredFeet:P}),characterKind:I([`rig`,`proxy`]),posture:I(Ge)}),Jt=L({id:R,kind:I([`object`,`character`,`rig`])},{name:mt,position:lt}),Yt=L({id:R},{label:mt,generation:F(`motion`),timeoutMs:N(1,3e5)}),Xt=L({id:R,name:mt,range:ft,keyCount:N()},{subjectIds:pt(24,0),kind:I([`clip`,`still`]),caption:rt(500)}),Zt=L({id:R,name:mt,range:ft,mode:I(Qe.shotModes)},{subjectIds:pt(24,0),kind:I([`clip`,`still`]),caption:rt(500)}),Qt=L({position:lt,lookAt:lt,focalMm:ut,sensorId:R,slate:mt}),$t=I([`primitive`,`set-piece`,`image`,`mesh`]),en=ot(L({kind:R,name:mt,type:$t}),L({id:R,name:mt,type:$t})),tn=L({id:R,characterId:R,state:I(Qe.jobStates)},{targetIds:pt(24,0),progress:it(M(0,1)),phase:mt}),nn=L({schema:F(`studio-context-v1`),host:vt,revision:yt,units:L({distance:F(`m`),angle:F(`deg`),up:F(`+Y`),yawZero:F(`+Z`),yawPositiveToward:F(`+X`),pivot:F(`base`),fps:F(24),rangeEnd:F(`exclusive`)}),scene:L({name:mt,aspect:rt(40),floorY:M(),frameCount:N(),objectCount:N(),characterCount:N()},{previsMode:I(We)}),selection:bt,activeCharacterId:it(R),view:xt,shot:it(Zt),camera:it(Qt),entities:at(qt,24),entityPage:L({returned:N(0,24),total:N(),truncated:P,nextCursor:it(rt(512))}),shots:at(Xt,8),shotsTruncated:P,assets:at(en,qe.assets),recentReceipts:at(L({id:R,summary:mt,canUndoDirect:P}),3),jobs:at(tn,8),capabilities:L({profile:F(`studio-slice-1`),tools:at(I(Xe),Xe.length,0,!0)},{rigReady:P,cameraReady:P,bridgeReady:P,storyboard:P})},{entityIndex:at(Jt,qe.entityIndex),actionIndex:at(Yt,512)}),rn=L({...gt,targetId:R,token:R}),an=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],on=L({dataUrl:{...rt(6e6),pattern:`^data:image/(png|jpeg|webp);base64,`}},{name:rt(120)}),sn=L({surface:F(`studio`),sessionId:ct,turnId:ct,text:rt(16e3),context:nn},{model:rt(120),effort:I(an),attachFrame:P,attachments:at(on,4,1),supervisor:P}),cn=L({surface:F(`studio`),sessionId:ct,turnId:ct},{jobId:R}),ln=L({before:N(),after:N()}),un=L({historyEntryId:R,entries:F(1),canUndoDirect:P}),dn=L({characterId:R,beforeTakeId:it(R),takeId:R,targetToken:R,frameCount:N(1),fps:F(24),durationSeconds:ut,blocks:at(L({sourceBeat:N(0,7),startFrame:N(),endFrameExclusive:N(1)}),120,1),selectionChanged:F(!1)}),fn=L({id:R,status:I([`verified`,`unverified`]),profile:F(`studio-motion-v1`),range:ft,evaluatedFrames:N(),physicsRevision:N(),limitations:at(mt,12)},{surfaceMeasured:P,maxFloorPenetrationM:M(0),maxContactSlipM:M(0),maxContactFloatM:M(0),unsupportedFrames:N(),supportedCollisionFrames:N(),continuityRegressed:P,semanticStatus:I([`pending_image_review`,`passed`,`failed`,`unavailable`])}),pn=L({path:rt(120)},{number:M(),text:it(rt(512)),flag:P,vec:lt,count:N(),bytes:N()}),mn=L({},{position:lt,yawDeg:M(),rotationDeg:lt,scale:ot(ut,dt),name:mt,color:rt(32),hidden:P,modelId:R,renderer:R,parentId:it(R),childIds:pt(100,0),childCount:N(0),bounds:it(Kt),removed:P,range:ft,camera:Qt,keyId:R,frame:N(),subjectIds:pt(24,0),selection:bt,activeCharacterId:it(R),shotId:it(R),view:xt,token:R,takeId:it(R),statureM:ut,patched:at(pn,32,1)}),hn=[`left`,`right`,`on-axis`],gn=L({coverage:mt},{relationSatisfied:P,overlapIds:pt(100,0),actualGapM:M(),requestedGapM:M(0),maximumFootprintOverlapM:M(0),basis:I(Qe.positionBases),clipped:P,occluded:P,behindCamera:P,screenFraction:M(0),derivedSize:I(Qe.framingSizes),support:mt,baseY:M(),facesTargetId:R,cameraSide:I(hn),axisConsistent:P,evaluatedFrames:N(1),sampledFrames:at(N(),64,1),sampledChecks:at(L({frame:N(),screenFraction:M(),clipped:P,behindCamera:P,occluded:P}),64,1),issueFrames:at(L({frame:N(),codes:at(mt,4,1),screenFraction:M()}),64,0)}),_n=L({subjects:at(L({id:R,position:lt,yawDeg:M()}),24),pairs:at(L({a:R,b:R,distanceM:M(0)}),24),shots:at(L({shotId:R,subjectIds:pt(2,0),camera:it(L({position:lt,lookAt:lt})),cameraSide:it(I(hn)),occluders:at(L({subjectId:R,byObjectId:R}),8)}),8),axisConsistent:it(P)}),vn=L({code:R},{id:R,message:mt,suggestedOutwardDeltaM:M(),count:N()}),yn={ok:F(!0),commandId:R,receiptId:R,host:_t,status:I(Qe.receiptStatuses),authored:P,revision:ln,affectedIds:pt(100,0),delta:at(L({id:R,after:mn}),8),checks:gn,undo:it(un),warnings:at(vn,12)},bn={counts:L({created:N(),updated:N(),deleted:N()}),detailCursor:it(rt(512))},xn=at(L({index:N(),status:I(Qe.opStatuses)},{droppedPaths:at(rt(120),32,1)}),32,1),Sn={...yn,authored:F(!0),undo:un},Cn={action:R,summary:rt(240)},wn={completed:L({...yn,status:F(`completed`),kind:I([`job`,`document`,`transaction`,`mutation`])},{...Cn,...bn,output:st,jobId:R,txId:R,nextHost:_t,ops:xn}),started:L({...yn,status:F(`started`),kind:F(`job`),jobId:R,authored:F(!1),undo:F(null)},{...Cn}),applied:L({...Sn,status:F(`applied`)},{mutated:F(!0),ops:xn,...bn,...Cn}),partial:L({...Sn,status:F(`partial`),ops:xn},{mutated:F(!0),...bn}),noop:L({...yn,status:F(`noop`),authored:F(!1),mutated:F(!1),undo:F(null)},{ops:xn,...Cn}),transient:L({...yn,status:F(`transient`),authored:F(!1),view:ln,undo:F(null)},{mutated:P,...Cn}),installed:L({...Sn,status:F(`installed`),jobId:R,artifactId:R,installed:dn,verification:fn},{mutated:F(!0),explicitUnverifiedAcceptance:P,acceptance:F(`advisory-policy`),...bn}),undone:L({...Sn,status:F(`undone`),undoneReceiptId:R,restoredTargets:at(rn,100,1)},{mutated:F(!0),...bn})},Tn=ot(...Object.values(wn)),En=L({ok:F(!1),commandId:R,host:_t,code:I(s),phase:I([`admission`,`execution`,`prepare`,`verify`,`repair`,`commit`,`reconcile`,`undo`]),affectedIds:pt(100,0),expectedTargets:at(rn,24),currentTargets:at(rn,24),mutated:ot(P,F(`unknown`)),preserved:L({authoredState:I([`unchanged`,`changed`,`unknown`])}),recovery:L({action:I([`none`,`inspect`,`retry`,`new_intent`,`reconcile`,`sign_in`])},{retryAllowed:P})},{message:rt(2e3),jobId:R,txId:R,candidates:at(L({id:R,kind:I([`object`,`character`,`rig`]),position:it(lt)}),5)}),Dn=tt({catalogue:Gt,variants:Qe,Vec3:lt,FrameRange:ft,PositionSpec:St,FacingSpec:Ct,ObjectOp:Et,CharacterOp:Dt,Framing:wt,Identity:_t,Host:vt,TargetGuard:rn,Entity:qt,ShotSummary:Xt,StudioContextV1:nn,StudioTurn:sn,StudioStop:cn,Receipt:Tn,ReceiptVariants:wn,Failure:En,GeometryFacts:_n});function On(e,t,n=`INVALID_ARGUMENT`,r=`$`){if(e.oneOf||e.anyOf){let i=[],a=[];for(let o of e.oneOf??e.anyOf)try{i.push(On(o,t,n,r))}catch(e){if(!(e instanceof $e))throw e;a.push({branch:o,error:e})}if(i.length===0&&a.length){let e=nt(t)&&nt(t.target)?t.target.kind:void 0,i=e!==void 0&&a.find(({branch:t})=>t.properties?.target?.properties?.kind?.const===e),o=!i&&Ue(r,a,t);throw o&&j(n,o,r),(i||a.reduce((e,t)=>t.error.details.path.length>e.error.details.path.length?t:e)).error}return i.length!==1&&e.oneOf&&j(n,`${r}: matches ${i.length} variants; send the fields of exactly one.`,r),i[0]}if(Object.hasOwn(e,`const`))return t!==e.const&&j(n,Me(r,e,t),r),t;if(e.type===`null`)return t!==null&&j(n,Me(r,e,t),r),null;if(e.type===`object`){nt(t)||j(n,Me(r,e,t),r);let i=e.additionalProperties===!0;for(let a of Object.keys(t))!Object.hasOwn(e.properties,a)&&!i&&j(n,Ne(r,e,a),r);let a={};if(i)for(let n of Object.keys(t))Object.hasOwn(e.properties,n)||(a[n]=structuredClone(t[n]));for(let[i,o]of Object.entries(e.properties))Object.hasOwn(t,i)?a[i]=On(o,t[i],n,`${r}.${i}`):e.required.includes(i)?j(n,Pe(r,i),`${r}.${i}`):Object.hasOwn(o,`default`)&&(a[i]=structuredClone(o.default));return e[`x-studio-range`]&&a.endFrameExclusive<=a.startFrame&&j(n,`Frame range must be nonempty and half-open.`,r),a}if(e.type===`array`){(!Array.isArray(t)||t.length<e.minItems||t.length>e.maxItems)&&j(n,Fe(r,e,t),r);let i=t.map((t,i)=>On(e.items,t,n,`${r}[${i}]`));return e.uniqueItems&&new Set(i.map(e=>JSON.stringify(e))).size!==i.length&&j(n,Ie(r,i),r),i}if(e.type===`string`)return(typeof t!=`string`||!t.trim()||e.maxLength!==void 0&&[...t].length>e.maxLength||e.pattern&&!new RegExp(e.pattern).test(t))&&j(n,Le(r,e,t),r),e.enum&&!e.enum.includes(t)&&j(n,Re(r,e,t),r),t;if(e.type===`boolean`)return typeof t!=`boolean`&&j(n,Me(r,e,t),r),t;if(e.type===`number`||e.type===`integer`)return(typeof t!=`number`||!Number.isFinite(t)||e.type===`integer`&&!Number.isSafeInteger(t)||e.exclusiveMinimum!==void 0&&t<=e.exclusiveMinimum)&&j(n,ze(r,e,t),r),(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&j(n,`${r}: Expected a number within [${[e.minimum,e.maximum].filter(e=>e!==void 0).join(`, `)}], got ${t}.`,r),t;throw Error(`Unsupported internal Studio schema.`)}var kn=e=>On(_t,e,`INVALID_IDENTITY`);function An(e){return[...new Set([...[`object`,`character`,`rig`].includes(e.selection?.kind)?[e.selection.id]:[],...e.activeCharacterId?[e.activeCharacterId]:[],...e.shot?.subjectIds??[],...e.jobs.flatMap(e=>[e.characterId,...e.targetIds??[]])])]}function jn(e){let t=et(JSON.stringify(e)??``);t>65536&&j(`CONTEXT_TOO_LARGE`,`Studio context exceeds ${Ke/1024} KiB.`,`$`,{bytes:t,maxBytes:Ke});let n=On(nn,e,`INVALID_CONTEXT`),r=new Set(n.entities.map(e=>e.id));r.size!==n.entities.length&&j(`INVALID_CONTEXT`,`Duplicate entity ID.`);for(let e of An(n))r.has(e)||j(`TARGET_NOT_READY`,`Mandatory target is absent from context.`);n.activeCharacterId&&!n.entities.some(e=>e.id===n.activeCharacterId&&e.kind===`character`)&&j(`INVALID_CONTEXT`,`Active target is not a character.`),[`object`,`character`,`rig`].includes(n.selection?.kind)&&!n.entities.some(e=>e.id===n.selection.id&&e.kind===n.selection.kind)&&j(`INVALID_CONTEXT`,`Selection kind disagrees with the selected entity.`),n.selection?.kind===`scene`&&n.selection.id!==n.host.sceneId&&j(`INVALID_CONTEXT`,`Selected scene is not the bound scene.`);for(let e of n.entities)e.bounds&&[`x`,`y`,`z`].some(t=>e.bounds.min[t]>e.bounds.max[t])&&j(`INVALID_CONTEXT`,`Inverted entity bounds.`),e.kind===`object`&&typeof e.scale==`number`&&j(`INVALID_CONTEXT`,`Objects use three-axis scale.`),e.kind!==`object`&&nt(e.scale)&&j(`INVALID_CONTEXT`,`Cast uses scalar scale.`);let i=n.entityPage;if((i.returned!==n.entities.length||i.total<i.returned||i.truncated!==i.total>i.returned||(i.truncated?i.nextCursor===null:i.nextCursor!==null))&&j(`INVALID_CONTEXT`,`Entity pagination is inconsistent.`),n.entityIndex){let e=new Set(n.entityIndex.map(e=>e.id));e.size!==n.entityIndex.length&&j(`INVALID_CONTEXT`,`Duplicate entity index ID.`),(n.entityIndex.length>i.total||n.entities.some(t=>!e.has(t.id)))&&j(`INVALID_CONTEXT`,`Entity index must cover every detailed entity and no more than the total.`)}n.view.frame>=Math.max(1,n.scene.frameCount)&&j(`INVALID_CONTEXT`,`Playhead is outside the scene.`),new Set(n.shots.map(e=>e.id)).size!==n.shots.length&&j(`INVALID_CONTEXT`,`Duplicate shot ID.`);for(let e of[...n.shots,...n.shot?[n.shot]:[]])e.range.endFrameExclusive>n.scene.frameCount&&j(`INVALID_CONTEXT`,`Shot is outside the scene.`);return n.shot&&!n.shots.some(e=>e.id===n.shot.id&&e.range.startFrame===n.shot.range.startFrame&&e.range.endFrameExclusive===n.shot.range.endFrameExclusive)&&j(`INVALID_CONTEXT`,`Current shot and range must survive projection.`),n}function Mn(e){let t=new Set;for(let n of Array.isArray(e?.ops)?e.ops:[]){let e=nt(n)?n.target?.kind:void 0;if(Ze.includes(e)){t.add(e);for(let t of nt(n.set)?Object.keys(n.set):[])Object.hasOwn(Bt[e].properties,t)||j(`INVALID_ARGUMENT`,`Unknown ${e} path "${e}.${t}". Valid ${e} paths: ${Vt[e].join(`, `)}.`)}}t.size>1&&j(`INVALID_ARGUMENT`,`One domain per patch: split character, object, shot and stage edits into separate commands.`)}function Nn(e){(!nt(e)||!Xe.includes(e.name))&&j(`UNKNOWN_TOOL`,`Unsupported Studio tool.`),e.name===`patch_elements`&&Mn(e.args);let{args:t}=On(L({name:I(Xe),args:Ut[e.name]}),e);if(e.name===`inspect_studio`&&t.ids&&t.query!==void 0&&j(`INVALID_ARGUMENT`,`IDs and query are exclusive.`),e.name===`operate_studio`&&(!Object.keys(t).length||t.view&&!Object.keys(t.view).length)&&j(`INVALID_ARGUMENT`,`Transient operation must specify an action.`),t.ops){let e=t.ops.filter(e=>e.op===`create`&&e.name!==void 0).map(e=>e.name.normalize(`NFC`).trim());new Set(e).size!==e.length&&j(`DUPLICATE_NAME`,`Create names must be unique; resolve existing targets by ID.`);for(let e of t.ops)e.op===`update`&&Object.keys(e).length===2&&j(`INVALID_ARGUMENT`,`Update has no fields.`),e.facing&&e.rotationDeg&&j(`INVALID_ARGUMENT`,`Facing and rotationDeg are exclusive: facing sets yaw only (toward/away/same-as/yawDeg); rotationDeg {x,y,z} sets the full rotation, with y as the yaw.`),e.op===`group`&&e.childIds.includes(e.parentId)&&j(`INVALID_ARGUMENT`,`Cannot group an object under itself.`),e.op===`create`&&e.parent!==void 0&&e.name!==void 0&&e.parent.normalize(`NFC`).trim()===e.name.normalize(`NFC`).trim()&&j(`INVALID_ARGUMENT`,`Cannot group an object under itself.`);t.collisionPolicy===`avoid`&&!t.ops.some(e=>[`create`,`update`].includes(e.op)&&e.position?.relativeTo)&&j(`INVALID_ARGUMENT`,`collisionPolicy avoid needs at least one op with position.relativeTo (it nudges outward from that reference); other ops are placed as given.`)}if(e.name===`frame_shot`&&t.framing.exact&&JSON.stringify(t.framing.exact.position)===JSON.stringify(t.framing.exact.lookAt)&&j(`INVALID_ARGUMENT`,`Camera position and aim cannot coincide.`),e.name===`patch_elements`)for(let e of t.ops)Object.keys(e.set).length||j(`INVALID_ARGUMENT`,`Patch has no fields.`);return e.name===`verify_result`&&(!!t.receiptId==!!t.targets&&j(`INVALID_ARGUMENT`,`Exactly one of receiptId or targets is required.`),t.checks.includes(`motion`)&&t.range===void 0&&(t.range=`whole_clip`,Object.defineProperty(t,"rangeWasDefaulted",{value:!0,enumerable:!1}))),{name:e.name,args:t}}function Pn(e){if(e?.ok===!1){let t=On(En,e,`INVALID_RECEIPT`);return et(JSON.stringify(t))>8192&&j(`INVALID_RECEIPT`,`Failure receipt exceeds 8 KiB.`),(t.mutated===!1&&t.preserved.authoredState!==`unchanged`||t.mutated===!0&&t.preserved.authoredState!==`changed`||t.mutated===`unknown`&&(t.preserved.authoredState!==`unknown`||t.recovery.action!==`reconcile`||t.recovery.retryAllowed===!0))&&j(`INVALID_RECEIPT`,`Failure must preserve uncertainty and actual state evidence.`),tt(t)}let t=On(Tn,e,`INVALID_RECEIPT`);if(et(JSON.stringify(t))>8192&&j(`INVALID_RECEIPT`,`Receipt exceeds 8 KiB; use a detail cursor.`),t.delta.some(e=>!t.affectedIds.includes(e.id)||!Object.keys(e.after).length)&&j(`INVALID_RECEIPT`,`Readback must identify affected targets and actual state.`),t.ops){let e=t.ops.some(e=>e.status===`partial`);t.ops.some((e,t)=>e.index!==t)&&j(`INVALID_RECEIPT`,`Operation results must report every operation in order.`),t.ops.some(e=>e.status===`partial`!=!!e.droppedPaths?.length)&&j(`INVALID_RECEIPT`,`A partial operation must name the paths the domain dropped, and only a partial one may.`),t.status===`applied`&&e&&j(`INVALID_RECEIPT`,`Applied status cannot hide a dropped path.`),t.status===`partial`&&!e&&j(`INVALID_RECEIPT`,`Partial status requires at least one dropped path.`),t.status===`noop`&&t.ops.some(e=>e.status===`applied`)&&j(`INVALID_RECEIPT`,`A noop cannot report an applied operation.`)}if(t.status===`started`||t.status===`completed`?(t.revision.after<t.revision.before&&!t.nextHost&&j(`INVALID_RECEIPT`,`Completion revisions must not move backwards in one document.`),t.status===`started`&&(t.authored||t.undo||t.revision.before!==t.revision.after)&&j(`INVALID_RECEIPT`,`Started jobs cannot claim an authored commit.`),t.kind===`mutation`&&(!t.authored||!t.undo||t.revision.after<=t.revision.before||!t.delta.length)&&j(`INVALID_RECEIPT`,`A completed composite mutation needs retained undo and advancing revision evidence.`),t.undo&&(!t.authored||!t.affectedIds.length)&&j(`INVALID_RECEIPT`,`An undo entry requires an authored result and affected targets.`)):t.status===`noop`||t.status===`transient`?((t.authored||t.undo!==null||t.revision.before!==t.revision.after)&&j(`INVALID_RECEIPT`,`Non-authored operations cannot create history or advance authored revision.`),t.status===`noop`&&(t.mutated!==!1||t.delta.length)&&j(`INVALID_RECEIPT`,`Noop must prove no mutation.`),t.status===`transient`&&(!t.view||t.view.after<t.view.before||!t.delta.length)&&j(`INVALID_RECEIPT`,`Transient receipt requires view revisions and actual readback.`)):((!t.authored||!t.undo||t.revision.after!==t.revision.before+1||!t.affectedIds.length||!t.delta.length||t.mutated===!1)&&j(`INVALID_RECEIPT`,`Authored mutation requires one revision and one undo entry with actual readback.`),t.delta.length<t.affectedIds.length&&!t.detailCursor&&j(`INVALID_RECEIPT`,`Omitted batch readback requires a detail cursor.`)),t.status===`undone`&&(new Set(t.restoredTargets.map(e=>e.targetId)).size!==t.affectedIds.length||t.restoredTargets.some(e=>!t.affectedIds.includes(e.targetId)||Object.keys(gt).some(n=>e[n]!==t.host[n])))&&j(`INVALID_RECEIPT`,`Undo must identify every restored target and its new token in the bound host.`),t.status===`installed`){(!t.jobId||!t.artifactId||!t.installed||!t.verification||!t.affectedIds.includes(t.installed.characterId))&&j(`INVALID_RECEIPT`,`Installation requires correlated target, artifact and verification evidence.`);let{frameCount:e,blocks:n}=t.installed,r=0;for(let e of n)(e.startFrame!==r||e.endFrameExclusive<=r||e.endFrameExclusive-r>120)&&j(`INVALID_RECEIPT`,`Installed schedule is not contiguous or bounded.`),r=e.endFrameExclusive;(r!==e||t.installed.durationSeconds!==e/24||t.verification.range.startFrame!==0||t.verification.range.endFrameExclusive!==e||t.verification.evaluatedFrames>e)&&j(`INVALID_RECEIPT`,`Installed schedule and verification coverage disagree.`),t.verification.status===`verified`&&t.verification.evaluatedFrames!==e&&j(`INVALID_RECEIPT`,`Verified motion requires whole-clip coverage.`),t.verification.status===`unverified`&&t.explicitUnverifiedAcceptance!==!0&&t.acceptance!==`advisory-policy`&&j(`INVALID_RECEIPT`,`Unverified installation requires explicit user or advisory-policy acceptance.`)}else(t.installed||t.verification||t.jobId&&![`started`,`completed`].includes(t.status)||t.artifactId||t.explicitUnverifiedAcceptance!==void 0)&&j(`INVALID_RECEIPT`,`Installation evidence is exclusive to installed receipts.`);return tt(t)}var Fn={"Load a character to pose it — Pose mode edits its rig with IK":`加载角色后才能摆姿势 — 姿势模式用 IK 编辑其骨骼`,"That picture format is not supported — use PNG, JPG, WebP or GIF":`不支持该图片格式 — 请使用 PNG、JPG、WebP 或 GIF`,"A newer edit comes after this deletion. Use Undo history instead.":`此删除之后还有更新的编辑。请改用撤销历史。`,"Double-click the line to add a dot":`双击线条添加一个点`,"That image is no longer in storage":`该图片已不在存储中`,"This image's usage changed, so it was not deleted. Please review it again.":`该图片的使用情况已变化,因此未删除。请重新检查。`,"This image's scene references changed, so it was not deleted. Please review it again.":`该图片的场景引用已变化,因此未删除。请重新检查。`,"That image is used by a scene and was not deleted":`该图片正被场景使用,未删除`,"That image is now used by a scene and was not deleted":`该图片现在正被场景使用,未删除`,"The scene changed while deleting, so the image was kept. Please review storage again.":`删除期间场景发生变化,图片已保留。请重新检查存储。`,"The live editor is disconnected. Reconnect before sending.":`实时编辑器已断开。请重新连接后再发送。`,"MP4 encoding is unavailable. Use a current browser with H.264 WebCodecs support (such as Chrome or Edge), enable hardware acceleration, then retry.":`MP4 编码不可用。请使用支持 H.264 WebCodecs 的最新浏览器(如 Chrome 或 Edge),开启硬件加速后重试。`,"Video encoding failed. Retry the same request. If resources are tight, shorten the shot range or lower output resolution before starting a new export.":`视频编码失败。请重试相同请求。若资源紧张,请缩短镜头范围或降低输出分辨率后重新导出。`,"Frame rendering failed. Let the scene finish loading, then retry. If it repeats, shorten the range or reduce output resolution for a new export.":`帧渲染失败。请等场景加载完成后再试。若反复出现,请缩短范围或降低输出分辨率后重新导出。`,"Export cancelled. No further files will be handed off.":`导出已取消。不会再交付其他文件。`,"Export could not finish. Retry the same request. For memory or resource problems, close other heavy tabs or use a shorter range / lower output resolution in a new export.":`导出未能完成。请重试相同请求。若为内存或资源问题,请关闭其他占用较大的标签页,或在新的导出中使用更短的范围/更低的分辨率。`,"An export is already running":`已有导出正在进行`,"Export completed. Check your export folder or browser downloads; the OS save is not confirmed.":`导出已完成。请查看导出文件夹或浏览器下载;系统保存未确认。`,"Export pipeline completed. The requesting tool handles the file handoff.":`导出流程已完成。文件交付由发起请求的工具处理。`,"Cancelling at the current work boundary…":`正在当前工作边界处取消…`,Preparing:`准备中`,Encoding:`编码中`,Finalizing:`收尾中`,Completed:`已完成`,Failed:`失败`,Cancelled:`已取消`,"Depth range sampled":`已采样深度范围`,"Frames submitted to encoder":`已提交给编码器的帧`,"Finalizing MP4. Progress is indeterminate; this stage cannot be interrupted.":`正在完成 MP4。进度不确定;此阶段无法中断。`,"Finishing encoder output. Progress is indeterminate.":`正在完成编码器输出。进度不确定。`,"Handing off existing PNGs. The file handoff cannot be cancelled.":`正在交付现有 PNG。文件交付无法取消。`,"Building the ZIP. Cancel takes effect after the current work unit, before the file handoff.":`正在构建 ZIP。取消将在当前工作单元结束后、文件交付前生效。`,"Cancel stops at the next frame boundary, before the file handoff.":`取消将在下一个帧边界停止,届时尚未交付文件。`,"Preparing the renderer and checking MP4 support…":`正在准备渲染器并检查 MP4 支持…`,"Encoding the requested frames, not yet a completed file.":`正在编码所请求的帧,尚未生成完整文件。`,"Retry keeps the original shot, camera, range and settings; it does not change your edits.":`重试会沿用原镜头、摄影机、范围与设置,不会改变你的编辑。`,"Cancel export":`取消导出`,"Retry same export":`重试相同导出`,"Add at least one Shot before exporting OTIO":`导出 OTIO 前请至少添加一个镜头`,"The shot renderer is not ready":`镜头渲染器尚未就绪`,"Add at least one Shot before exporting a keyframe pack":`导出关键帧包前请至少添加一个镜头`,"Depth and normal passes exported":`深度和法线通道已导出`,"Add at least one Shot before exporting a storyboard":`导出故事板前请至少添加一个镜头`,"Composing the storyboard…":`正在编排故事板…`,"Add a panel first — storyboard exports describe panels":`请先添加面板 — 故事板导出需要面板`,"ROOT PATH":`根路径`,"Prompt copied to clipboard":`提示词已复制到剪贴板`,"Frame export finished. Check your export folder or browser downloads.":`帧导出完成。请查看导出文件夹或浏览器下载。`,Redone:`已重做`,Undone:`已撤销`,"Saving…":`保存中…`,"Save failed":`保存失败`,"Not saved":`未保存`,"Unsaved changes":`未保存的更改`,Saved:`已保存`,"Sign in with ChatGPT in the Agent panel to generate a blueprint.":`请在智能体面板中登录 ChatGPT 以生成蓝图。`,"Sign in to the Agent (⌘B) to sculpt from an image.":`请登录智能体(⌘B)以从图像雕塑。`,"The live editor is disconnected — reconnect to sculpt.":`实时编辑器已断开 — 请重新连接后再雕塑。`,"No model is available — add a provider key in the Agent panel.":`没有可用模型 — 请在智能体面板中添加服务商密钥。`,"New sculpt":`新建雕塑`,"Add a reference image in the Sculpt panel and press Start — or select a sculpt and press 5.":`在雕塑面板中添加参考图并按开始 — 或选中雕塑并按 5。`,"The graphics context was lost — restoring the stage. If it stays black, reload the page; your work is autosaved.":`图形上下文已丢失 — 正在恢复舞台。若持续黑屏,请刷新页面;你的工作已自动保存。`,"Graphics restored.":`图形已恢复。`,"Dot added — drag it to bend the route":`已添加点 — 拖动它使路径弯曲`,"3D graphics (WebGL) is turned off in this browser":`此浏览器的 3D 图形(WebGL)已关闭`,'Quit the browser completely (Cmd+Q) and reopen it, or turn on "Use graphics acceleration when available" in its settings. chrome://gpu shows the WebGL status.':`请完全退出浏览器(Cmd+Q)后重新打开,或在设置中开启“尽可能使用图形加速”。chrome://gpu 可查看 WebGL 状态。`,"The 3D view lost its graphics context":`3D 视图丢失了图形上下文`,"Waiting for the browser to restore it. If this stays, reload the studio — scenes autosave.":`正在等待浏览器恢复。若持续如此,请刷新工作室 — 场景会自动保存。`,Reload:`刷新`,"Click or ▸ to expand · drag to move":`点击或 ▸ 展开 · 拖动移动`,"Click or ▾ to fold · drag to move":`点击或 ▾ 折叠 · 拖动移动`,"Expand inset view":`展开小窗视图`,"Collapse inset view":`折叠小窗视图`,"Shot view":`镜头视图`,"Top-View":`顶视图`,"Resize inset view":`调整小窗大小`,Shot:`镜头`,"Look through the shot camera":`通过镜头摄影机观察`,"Look through the shot camera — right-drag, WASD and orbit set the recording lens (Esc returns)":`通过镜头摄影机观察 — 右键拖动、WASD 和环绕设置录制镜头(Esc 返回)`,"Look through":`镜头视角`,"Return to the editor view (Esc)":`返回编辑器视图 (Esc)`,"Shot camera":`镜头摄影机`,"Esc · exit":`Esc · 退出`,"SUBJECT OUT OF FRAME":`角色不在画面内`,"A new version of CozyClay is ready.":`CozyClay 新版本已就绪。`,"Reload to update":`刷新以更新`,Later:`稍后`,"Object deleted.":`物体已删除。`,"Undo object deletion":`撤销物体删除`,Undo:`撤销`,"Project access was not granted.":`未获得项目访问权限。`,Restore:`恢复`,Dismiss:`关闭`,"Image deleted. This session can undo it.":`图片已删除。本次会话内可撤销。`,"This account cannot generate images.":`此账号无法生成图像。`,"Sign in with ChatGPT in the Agent panel first.":`请先在智能体面板中登录 ChatGPT。`,"unknown error":`未知错误`,"The image route did not return a PNG.":`图像接口未返回 PNG。`,Draft:`草稿`,"The studio hit a render error":`工作室遇到渲染错误`,"Scenes autosave as you work, so reloading resumes from the last saved state.":`场景会随工作自动保存,刷新后会从上次保存的状态继续。`,"Reload the studio":`刷新工作室`,"Your first 60 seconds":`你的最初 60 秒`,"Core loop complete":`核心流程完成`,"Dismiss guide":`关闭指南`,"You made your first panel.":`你做出了第一个面板。`,"You made your first shot.":`你做出了第一个镜头。`,"Describe, review on the Board, then stylize or export. You can close this guide and keep adding panels.":`描述、在看板上检查,然后风格化或导出。你可以关闭本指南并继续添加面板。`,"Select, move, ask, and play are the core CozyClay loop. You can close this guide and keep blocking.":`选择、移动、提问和播放是 CozyClay 的核心流程。你可以关闭本指南并继续摆位。`,"Continue editing":`继续编辑`,"Follow these four actions to see a result quickly.":`跟随这四个步骤,快速看到结果。`,"Skip guide":`跳过指南`,"QA clean":`QA 通过`,Settings:`设置`,"Language and analytics":`语言与统计`,Medium:`中景`,Wide:`广角`,"Close-Up":`特写`,"Low Angle":`低角度`,"High Angle":`高角度`,"Saved scenes were written by a newer CozyClay — they have been left untouched and this session will not save":`已保存的场景由更新版本的 CozyClay 创建 — 已保持原样,本次会话也不会保存`},In={"Character added to the scene":`角色已添加到场景`,"The active character's rig is not loaded":`当前角色的骨骼尚未加载`,"The path already fills the clip — extend the duration or clear a waypoint":`路径已填满整个片段 — 请延长时长或清除一个路径点`,"Root path constraints off":`根路径约束已关闭`,"Root path on — click the set floor in the Shot view to drop waypoints; Subject 1 is the frame 0 start":`根路径已开启 — 在镜头视图中点击布景地面放置路径点;角色 1 是第 0 帧的起点`,"Edited pose":`已编辑的姿势`,"Pose saved":`姿势已保存`,"Nothing to undo":`没有可撤销的操作`,"IK edit undone":`已撤销 IK 修改`,"Nothing to redo":`没有可重做的操作`,"Confirm Replace existing keys before applying this pin.":`应用此固定前请确认替换现有键。`,"Pose mode — preview the correction, then apply it to the selected motion block":`姿势模式 — 先预览修正,再应用到所选动作片段`,"Pose mode — drag handles in the main view; the shot camera stays frozen in the inset":`姿势模式 — 在主视图中拖动手柄;镜头摄影机在小窗中保持冻结`,"Pose mode off — keyed poses keep playing":`姿势模式已关闭 — 已打关键帧的姿势会继续播放`,"Nothing to drop":`没有可放置的对象`,Cutout:`抠图`,"its picture is missing from the store":`其图片不在存储中`,"Grouped under a new Empty":`已归入新的空物体`,"Could not group this object":`无法编组此物体`,"Missing character":`角色不存在`,"Character 1":`角色 1`,"Character 2":`角色 2`,Root:`根`,"Could not save the project":`无法保存项目`,"Could not export the animation project":`无法导出动画项目`,"Discard unsaved changes and start a new project?":`放弃未保存的更改并新建项目?`,"That starter scene is not in this build":`此版本中没有该起始场景`,"Could not open the project":`无法打开项目`,"This browser would not read that file. Open it once more.":`此浏览器未能读取该文件,请再打开一次。`,"Project access was not granted — allow access and try again.":`未获得项目访问权限 — 请允许访问后重试。`,"SCENE 01":`场景 01`,"Draw the selected Shot's rail in the Top-View":`在顶视图中绘制所选镜头的轨道`,"Camera rail deleted — Follow keeps the current distance":`摄影机轨道已删除 — 跟随模式保持当前距离`},Ln={"+ New scene":`+ 新建场景`,"Select scene":`选择场景`,Rename:`重命名`,Duplicate:`复制`,"Click again to permanently delete this scene":`再次点击将永久删除此场景`,"Confirm delete":`确认删除`,Show:`显示`,Hide:`隐藏`,"Remove from group":`从组中移出`,Frame:`适配取景`,"Group under new Empty":`归入新的空物体`,"Move out to Props":`移出到道具`,"IK ON":`IK 开`,"At least one scene is required":`至少需要一个场景`,Outliner:`大纲视图`,"Search Outliner":`搜索大纲`,"No matches":`无匹配项`,"practical light":`实用灯光`,"node only":`仅节点`,"smoke, fire, rain…":`烟、火、雨…`,"words, signs, logos":`文字、标牌、标志`,"Add object":`添加物体`,"PATH START":`路径起点`,"PATH END":`路径终点`,"PLAYER STILL":`播放器静止`,START:`起点`,CAM:`摄影机`,LIGHT:`灯光`,"T-pose":`T 姿势`,Relaxed:`放松`,Contrapposto:`对立式站姿`,Walking:`行走`,Seated:`坐姿`,"Arms crossed":`抱臂`,Pointing:`指向`,"Hands on hips":`叉腰`,"Looking back":`回望`,"Hands up":`举手`,Wave:`挥手`,Thinking:`思考`,Crouch:`蹲伏`,Kneel:`跪姿`,Run:`奔跑`,Jump:`跳跃`,Basic:`基础`,Gesture:`手势`,Action:`动作`,Floor:`地面`,"My poses":`我的姿势`,"Close pose studio":`关闭姿势工作室`,"Pose mode is on — applying keys the pose as a full-body correction at the current frame; the motion stays.":`姿势模式已开启 — 应用后会在当前帧以全身修正关键帧记录该姿势,动作保持不变。`,"A sample motion is moving the character — applying a pose clears it and returns to the blocking pose.":`当前示例动作正在驱动角色 — 应用姿势会清除它并回到摆位姿势。`,"Key pose as IK correction":`将姿势记录为 IK 修正关键帧`,"Clear motion and apply pose":`清除动作并应用姿势`,"Apply pose":`应用姿势`,"Reset pose":`重置姿势`,"Pose categories":`姿势分类`,"Your pose library is empty. Pose the character and save it — it stays here for every project.":`你的姿势库是空的。给角色摆好姿势并保存 — 之后所有项目都能使用。`,"Save the character's current pose":`保存角色当前姿势`,"Save pose":`保存姿势`,"Shot settings":`镜头设置`,Torso:`躯干`,"Root / Hips":`根 / 髋部`,Spine:`脊柱`,Chest:`胸部`,Neck:`颈部`,Head:`头部`,"Left Arm":`左臂`,"Left Shoulder":`左肩`,"Left Elbow":`左肘`,"Left Hand":`左手`,"Right Arm":`右臂`,"Right Shoulder":`右肩`,"Right Elbow":`右肘`,"Right Hand":`右手`,"Left Leg":`左腿`,"Left Knee":`左膝`,"Left Foot":`左脚`,"Right Leg":`右腿`,"Right Knee":`右膝`,"Right Foot":`右脚`,"Static / locked-off":`固定机位`,"Zoom in":`推近(变焦)`,"Zoom out":`拉远(变焦)`,"Push-in (dolly in)":`推入(前移推轨)`,"Pull-out (dolly out)":`拉出(后移推轨)`,"Pan left":`左摇`,"Pan right":`右摇`,"Tilt up":`上仰`,"Tilt down":`下俯`,"Tracking / follow":`跟拍 / 跟随`,"Orbit / arc":`环绕 / 弧线`,"Crane up":`摇臂上升`,"Crane down":`摇臂下降`,Handheld:`手持`,"Crash zoom in":`急推变焦`,"Dolly-zoom (vertigo)":`推轨变焦(眩晕效果)`,"Whip pan":`快速甩摇`,"Aerial / drone":`航拍 / 无人机`,"extreme close-up":`大特写`,"close-up":`特写`,"medium close-up":`近景`,"medium shot":`中景`,"medium-wide shot":`中远景`,"wide shot":`远景`,"extreme wide shot":`大远景`,overhead:`俯拍`,"high angle":`高角度`,"eye level":`平视`,"chest level":`胸高`,"hip level":`胯高`,"knee level":`膝高`,"ground level":`地面高度`,cube:`立方体`,sphere:`球体`,capsule:`胶囊`,cylinder:`圆柱`,cone:`圆锥`,plane:`平面`,cutout:`抠图`,Cube:`立方体`,Sphere:`球体`,Capsule:`胶囊`,Cylinder:`圆柱`,Cone:`圆锥`,Plane:`平面`,front:`正面`,back:`背面`,"left profile":`左侧面`,"right profile":`右侧面`,"front ¾ L":`正面 ¾ 左`,"front ¾ R":`正面 ¾ 右`,"rear ¾ L":`背面 ¾ 左`,"rear ¾ R":`背面 ¾ 右`,"Scene structure":`场景结构`,"Scene hierarchy":`场景层级`,Primitives:`基础形状`,Lights:`灯光`,Effects:`效果`,"Point light":`点光源`,"Spot light":`聚光灯`,Effect:`效果`,Cast:`角色`,"Frame selection":`将所选内容适配到画面`,"Drop to floor":`放到地面`},Rn={"camera to subject":`摄影机到角色`,"nearest prime on the cropped filmback":`裁切画幅上最接近的定焦镜头`,Lens:`镜头`,"angle relative to the subject's eyes":`相对角色眼睛的角度`,Angle:`角度`,"Move keys":`运动关键帧`,"derived from the keyframings, not chosen from a list":`由关键帧推导,而非从列表中选择`,"Click a Shot block's lower strip to key the current framing at that frame.":`点击镜头块下方的空条,在该帧记录当前取景。`,"Follow cam":`跟随摄影机`,"Select a Shot block below to edit its camera.":`在下方选择一个镜头块以编辑其摄影机。`,"Target model":`目标模型`,"The timeline flags this shot when the cut runs past the model's clip length or leaves its delivery ratios. Nothing is re-timed or re-cropped.":`当片段超出模型的时长上限或偏离交付画幅时,时间线会标记该镜头,但不会自动重定时或重新裁切。`,"Cut for":`适配对象`,"Target video model":`目标视频模型`,None:`无`,Placement:`摆放`,Transform:`变换`,"Stage position — does not change the take":`舞台位置 — 不改变动作片段`,Position:`位置`,Rotation:`旋转`,"Use stage placement":`使用舞台摆放`,"Edit the selected subject's placement, turn and size. Drag the Transform tool in the viewport for direct manipulation.":`编辑所选角色的位置、朝向和大小。也可在视口中拖动变换工具直接操作。`,Scale:`缩放`,Environment:`环境`,"I have an environment sheet":`我有环境设定图`,"Environment description":`环境描述`,"Look / style":`外观 / 风格`,"Environment reference":`环境参考图`,"A picture of this location. It travels with every framing capture so a render takes its materials, palette and lighting from the real place.":`该地点的照片。每次取景捕捉都会带上它,使渲染从真实地点获取材质、色调和光照。`,"Environment reference set":`已设置环境参考图`,"None (the look's sky)":`无(使用外观自带天空)`,"Loading HDR…":`正在加载 HDR…`,"Load HDR…":`加载 HDR…`,Intensity:`强度`,"Show as background":`显示为背景`,"Remove HDR":`移除 HDR`,Light:`灯光`,"Drag the sun in the scene to move the light. Shadows and warmth follow it.":`在场景中拖动太阳以移动灯光。阴影和色温会随之变化。`,Look:`外观`,"Lighting look":`灯光外观`,Brightness:`亮度`,"Warm ↔ Cool":`暖 ↔ 冷`,Exposure:`曝光`,"Sky light":`天光`,"Ambient occlusion":`环境光遮蔽`,Sky:`天空`,"Sky colour":`天空颜色`,"light position":`灯光位置`,"Reset light":`重置灯光`,Text:`文字`,Words:`文字`,"Letter height":`字高`,"Depth (0 = flat)":`厚度(0 = 平面)`,Align:`对齐`,Left:`左`,Centre:`居中`,Right:`右`,Type:`类型`,Point:`点光源`,Spot:`聚光灯`,Colour:`颜色`,"Intensity (cd)":`强度(cd)`,"Range (0 = none)":`范围(0 = 无)`,"Cone angle":`光锥角度`,"Edge softness":`边缘柔和度`,Flicker:`闪烁`,"Shadow (off: only 2 lights cast)":`阴影(关闭:仅 2 盏灯投射)`,Shadow:`阴影`,Glow:`自发光`,"Glows (lit by itself)":`自发光(自身照明)`,"Halo (× size)":`光晕(× 大小)`,"Type a value and press Enter, or drag a number sideways to scrub (Shift for fine).":`输入数值后按 Enter,或左右拖动数值调节(按住 Shift 微调)。`,Name:`名称`,"Attached to":`附着于`,"Put it back in the set, where it is now":`放回布景中它当前所在的位置`,Detach:`分离`,Parent:`父级`,"(none)":`(无)`,"Height (m)":`高度(m)`,Clay:`黏土`,"Card height (m)":`卡片高度(m)`,"Card width (m)":`卡片宽度(m)`,"This card's background is removed. You are editing the original photograph — apply again to change what goes.":`此卡片的背景已移除。你正在编辑原始照片 — 再次应用可更改被移除的范围。`,"Background editor — drag over the background to cut it out":`背景编辑器 — 在背景上拖动即可抠除`,"Drag over the background — the cut grows out from wherever the brush touches.":`在背景上拖动 — 从画笔触及处向外扩展抠除范围。`,"Cut out":`抠出`,"Bring back":`恢复`,Redo:`重做`,"Clear the selection":`清除选择`,Tolerance:`容差`,Brush:`画笔`,"Brush size":`画笔大小`,"Edge shrink":`边缘收缩`,"Edge feather":`边缘羽化`,"Tolerance is how far a drag spreads: low keeps to one flat colour, high walks across a shaded wall. It applies to the next drag and to Auto-detect, not to what is already purple.":`容差决定拖动扩散的范围:较低时只保留单一平色,较高时会跨越明暗渐变的墙面。它作用于下一次拖动和自动识别,不会改变已经标为紫色的区域。`,"Auto-detect background":`自动识别背景`,"Removing…":`正在移除…`,"Nothing is marked yet":`尚未标记任何区域`,"Cut out grows the selection from wherever you drag; Bring back is the same growth fenced to what is already selected, so one drag returns a wrongly-cut region whole. Applying removes exactly what is purple and trims the empty margin — the card keeps the original photograph and this selection, so you can come back and change your mind.":`抠出会从拖动处扩展选区;恢复则把同样的扩展限制在已选区域内,因此一次拖动就能整块找回误抠区域。应用时只移除紫色部分并裁掉空白边距 — 卡片会保留原始照片和此次选区,随时可以回来修改。`,"Object colour":`物体颜色`,"auto ":`自动 `,"Custom colour":`自定义颜色`,"Colour hex":`颜色 hex`,"The shot renderer is not ready yet.":`镜头渲染器尚未就绪。`,"Image from pose":`从姿势生成图像`,"Frame source":`帧来源`,"Current view":`当前视图`,"This frame is sent":`使用此帧生成`,"Frame the viewport, then capture":`调整视口取景后捕捉`,"The shot camera's view":`镜头摄影机视图`,Recapture:`重新捕捉`,Capture:`捕捉`,"The frame sent to the image model":`发送给图像模型的帧`,"Not captured yet — Generate captures this view.":`尚未捕捉 — 点击生成会捕捉当前视图。`,References:`参考图`,"Remove reference":`移除参考图`,"Add a reference picture (or drop one here)":`添加参考图(也可拖放到此处)`,"Describe the image — e.g. a knight in silver armour, dusk light, cinematic":`描述图像 — 例如:银甲骑士、黄昏光线、电影感`,"Generate image":`生成图像`,"View larger":`放大查看`,Download:`下载`,"Use as reference":`用作参考`,"Generated image":`生成的图像`,Close:`关闭`,Older:`更早`,Newer:`更新`,"Cleared the current motion and applied the pose":`已清除当前动作并应用姿势`,"Pose applied":`姿势已应用`,"Save the pose the character is in right now — with a motion loaded, that is the current frame plus IK corrections":`保存角色当前的姿势 — 若已加载动作,则为当前帧加上 IK 修正后的姿势`,"Save current pose":`保存当前姿势`,"Identity image":`角色定妆图`,"A character sheet or photo of this person. It travels with every framing capture so a render keeps the same face, hair and wardrobe.":`此角色的设定图或照片。每次取景捕捉都会带上它,使渲染保持相同的面容、发型和服装。`,"Identity reference":`角色定妆参考`,"Identity image set":`已设置角色定妆图`,"New Project":`新建项目`,"Open Project…":`打开项目…`,"Save Project":`保存项目`,"Save Project As…":`项目另存为…`,"Choose Project":`选择项目`,"Untitled Project":`未命名项目`,"Everything you add to the set lives here. Pick one to edit it, or click it in the shot view. Drop a picture anywhere here — or on the shot view — to stand it up as a cutout. You can also drop a .glb, .obj or .fbx to import a 3D object.":`添加到布景的所有道具都在这里。选中一个即可编辑,也可在镜头视图中点击。把图片拖到此处或镜头视图中,即可立起为抠图卡片。也可以拖入 .glb、.obj 或 .fbx 文件导入 3D 物体。`,"A photo of the real thing, standing in the set as a card":`以卡片形式立在布景中的实物照片`,"Import image as cutout":`将图片导入为抠图`,"A GLB, OBJ or FBX model standing in the set":`立在布景中的 GLB、OBJ 或 FBX 模型`,"Import 3D object":`导入 3D 物体`,Stand:`站立`,Sit:`坐下`,Lie:`躺下`,Posture:`姿态`,Clear:`清除`,"Choose a reference picture":`选择参考图`,Replace:`替换`,"Choose image":`选择图片`,"Foot lock":`脚部锁定`,On:`开`,Off:`关闭`,Ready:`就绪`,Unavailable:`不可用`,Influence:`影响`,All:`全部`,"Object opacity":`物体不透明度`,"Scene object opacity while posing":`摆姿势时场景物体的不透明度`,"Select a body group to pose it in the viewport.":`选择一个身体部位,在视口中摆姿势。`,"Active tool":`当前工具`,IK:`IK`,Pin:`固定`,"IK preview":`IK 预览`,"The drag is previewed. Apply it to the selected motion block or cancel it.":`正在预览拖动结果。将其应用到所选动作片段,或取消。`,"Apply range":`应用到区间`,"Grab a hand, foot, elbow or knee handle in the viewport.":`在视口中抓住手、脚、肘或膝的控制点。`,Rig:`骨骼`,"Character rig":`角色骨骼`,Measure:`测量`,Score:`评分`,Refine:`精修`,"taking longer than usual":`比平时耗时更长`,"Candidate fixes, best first":`候选修正(优先显示最佳)`,refused:`已拒绝`,"Sculpt activity":`雕塑活动`,"locked while running":`运行期间锁定`,"Sculpt model":`雕塑模型`,"add key":`需要密钥`,"No model available":`没有可用模型`,"Loading models…":`正在加载模型…`,Effort:`推理强度`,"Blueprint (model sheet)":`蓝图(设定图)`,"front · side · back · top":`正面 · 侧面 · 背面 · 顶面`,"Pose on the sheet":`设定图姿势`,"Pose: as in the reference":`姿势:与参考一致`,"Pose: neutral rest pose":`姿势:中性静止姿势`,"Notes (optional): what it is, what to keep or fix":`备注(可选):它是什么,需要保留或修正什么`,"Blueprint notes":`蓝图备注`,"Drawing the four-view sheet":`正在绘制四视图设定图`,"usually ~40–90s":`通常约 40–90 秒`,"Generate again":`重新生成`,"Generate blueprint":`生成蓝图`,"Open full size":`原尺寸打开`,"Generated four-view model sheet":`已生成的四视图设定图`,"Request sent to the image model":`发送给图像模型的请求`,"Sculpt from image":`从图像雕塑`,Reference:`参考图`,"Replace reference image":`替换参考图`,"Drop or paste a reference image, or press Enter to choose a file":`拖放或粘贴参考图,或按 Enter 选择文件`,"Drop or paste a reference image":`拖放或粘贴参考图`,"Choose file":`选择文件`,"Reference image file":`参考图文件`,"Start (fast draft)":`开始(快速草图)`,"Sculpt stages":`雕塑阶段`,"Final IoU":`最终 IoU`,"Silhouette match (IoU)":`轮廓匹配度(IoU)`,"Cancelled.":`已取消。`,"The sculpt run failed.":`雕塑运行失败。`,"Hide overlay sheet":`隐藏叠加设定图`,"Show overlay sheet":`显示叠加设定图`,"Reference beside the sculpt overlay":`参考图与雕塑叠加对比`,"Place in scene":`放入场景`,"Fix details by chatting with the Agent (⌘B) while the sculpt is selected.":`选中雕塑时,通过与智能体对话(⌘B)修正细节。`,"Character color":`角色颜色`,"Remove subject":`移除角色`,Subjects:`角色`,Subject:`角色`,"Add second subject":`添加第二个角色`},zn={"the stylized image is missing":`找不到风格化图像`,"the shot renderer is not ready":`镜头渲染器尚未就绪`,"Panel sent to Workflow":`面板已发送到工作流`,"the shot renderer is not ready yet":`镜头渲染器尚未就绪`,"the panel is no longer on the board":`该面板已不在看板上`,Board:`看板`,"Add a panel after the last one, framed by the current camera":`以当前摄影机取景,在最后一个面板后添加面板`,"+ Panel":`+ 面板`,"No panels yet. Each panel is one held picture of the scene through the shot camera.":`还没有面板。每个面板都是镜头摄影机下场景的一帧定格画面。`,"Add the first panel, framed by the current camera":`以当前摄影机取景添加第一个面板`,"Duplicate this panel after itself":`在此面板后复制一个`,"Delete this panel (Delete)":`删除此面板 (Delete)`,"Generate a new stylized picture from this panel's frame and caption (replaces the current one)":`根据此面板的帧和说明生成新的风格化图像(替换当前图像)`,"Generate a stylized picture from this panel's frame and caption":`根据此面板的帧和说明生成风格化图像`,"Stylizing...":`正在风格化...`,"Re-stylize":`重新风格化`,Stylize:`风格化`,"Remove the stylized picture; the greybox stays":`移除风格化图像,保留灰模`,Remove:`移除`,"Send this panel to a Workflow video node":`将此面板发送到工作流视频节点`,"Send to Workflow":`发送到工作流`,"Stylized image":`风格化图像`,Greybox:`灰模`,"Export — another export is running":`导出 — 另一个导出正在进行`,"Export this panel as a pack (zip)":`将此面板导出为资源包(zip)`,"Action or dialogue":`动作或对白`,Hold:`停留`,Assets:`资源`,"Resize bottom dock":`调整底部停靠栏大小`,Dock:`停靠栏`,"Body contact off — floor constraints are disabled":`身体接触关闭 — 地面约束已禁用`,"Body contact on — body markers stay above the floor":`身体接触开启 — 身体标记保持在地面之上`,"Foot snap off — the feet follow the body":`脚部吸附关闭 — 双脚跟随身体移动`,"Foot snap on — the feet stay planted while the body moves":`脚部吸附开启 — 身体移动时双脚保持踩地`,"Follow rides the subject's motion — without a loaded motion the camera composes a static frame":`跟随会随角色动作移动 — 未加载动作时摄影机保持静态构图`,"Draw this Camera Block's rail in the Top-View":`在顶视图中绘制此摄影机块的轨道`,"Shot Camera":`镜头摄影机`,"Viewing in the main view":`正在主视图中查看`,"Shot aspect ratio":`镜头画幅比`,"No shot yet":`还没有镜头`,"Back to the editor view (Esc)":`返回编辑器视图 (Esc)`,Exit:`退出`,"Look through the shot camera (Esc returns)":`通过镜头摄影机观察 (Esc 返回)`,"Cycle composition guides":`切换构图参考线`," · click to cycle":` · 点击切换`,Details:`详情`,"Object actions":`物体操作`,"Select the camera, a character, the light, the environment or a prop in the Outliner, and its settings appear here.":`在大纲视图中选择摄影机、角色、灯光、环境或道具,其设置会显示在这里。`,"Delete or Backspace to remove":`按 Delete 或 Backspace 删除`,"Open Agent (Cmd/Ctrl+B)":`打开智能体 (Cmd/Ctrl+B)`,Agent:`智能体`,"Ask the agent…":`向智能体提问…`,"Resize Details and Agent":`调整详情与智能体面板大小`,"Collapse Agent":`折叠智能体`,"Collapse Agent (Cmd/Ctrl+B)":`折叠智能体 (Cmd/Ctrl+B)`,"Untitled Scene":`未命名场景`,"Couldn't find the selected pose — pick again":`找不到所选姿势 — 请重新选择`,"Back to the default pose":`已返回默认姿势`,"When set, exports are written here instead of your browser's Downloads folder.":`设置后,导出文件会写入此文件夹,而不是浏览器的下载文件夹。`,"Folder access was denied. Choose another folder or use Downloads.":`文件夹访问被拒绝。请选择其他文件夹或使用下载文件夹。`,"Could not choose the export folder.":`无法选择导出文件夹。`,"Could not clear the export folder.":`无法清除导出文件夹。`,"Browser downloads":`浏览器下载`,"This browser cannot choose an export folder; exports continue to Downloads.":`此浏览器无法选择导出文件夹;导出将继续保存到下载文件夹。`,"Export folder":`导出文件夹`,"Export folder actions":`导出文件夹操作`,Allow:`允许`,"Choosing…":`选择中…`,"Choose folder…":`选择文件夹…`,"Use Downloads":`使用下载文件夹`,"Existing files are never overwritten; numbered names are used.":`同名文件永远不会被覆盖,而是使用带编号的名称。`,"Key frames":`关键帧`,"Ghosts (onion skin)":`残影(洋葱皮)`,Ghosts:`残影`,"before the playhead":`播放头之前`,"after the playhead":`播放头之后`,"Translucent poses of the selected character's take before and after the playhead; never in exports":`半透明显示所选角色动作片段中播放头前后的姿势;不会出现在导出中`,"Each side":`每侧数量`,Step:`间隔`,"While the agent works, its latest motion draft plays on the character as a teal figure; never in exports":`智能体工作时,其最新动作草稿会以青色形象在角色上播放;不会出现在导出中`,"Agent draft":`智能体草稿`,Library:`资源库`,File:`文件`,Edit:`编辑`,Window:`窗口`,Help:`帮助`,"Add a shot first — a pack describes one cut":`请先添加镜头 — 资源包描述一个剪辑`,"Contact sheet (PNG)":`缩略图总览 (PNG)`,"Every panel with its caption on one sheet":`所有面板及其说明合成一张图`,"Panel pack (zip)":`面板包 (zip)`,"The selected panel's frame, stylized image, camera and prompt as one zip":`将所选面板的帧、风格化图像、摄影机和提示词打包为一个 zip`,"All panels (zip)":`所有面板 (zip)`,"One zip with a folder per panel":`一个 zip,每个面板一个文件夹`,"Animatic (mp4)":`动态分镜 (mp4)`,"Every panel held for its hold, as one MP4":`按各自停留时长衔接所有面板,合成一个 MP4`,"Cut list (OTIO)":`剪辑表 (OTIO)`,"Download the OTIO cut list; each panel is a clip as long as its hold":`下载 OTIO 剪辑表;每个面板是一个与停留时长等长的片段`,"Depth + normal (PNG)":`深度 + 法线 (PNG)`,"Depth and normal conditioning plates of the current framing":`当前取景的深度和法线条件控制图`,"Open…":`打开…`,Save:`保存`,"Save As…":`另存为…`,"Export as Animation project…":`导出为动画项目…`,"Exports: keyframe pack, video, passes, storyboard, cut list":`导出:关键帧包、视频、通道、故事板、剪辑表`,"First/last frames, clip, camera and prompt as one zip — hold Shift for every shot":`首/末帧、片段、摄影机和提示词打包为一个 zip — 按住 Shift 导出所有镜头`,"Keyframe pack (zip)":`关键帧包 (zip)`,"Render the whole timeline to one MP4 — every shot back to back, camera and motion, no editor chrome":`将整条时间线渲染为一个 MP4 — 所有镜头依次衔接,仅含摄影机和动作,无编辑器界面`,"Video — whole timeline (mp4)":`视频 — 整条时间线 (mp4)`,"Render one shot to its own MP4 — the shot you opened the menu from, or the one under the playhead":`将单个镜头渲染为 MP4 — 从菜单打开的镜头,或播放头下的镜头`,"Video — this shot only (mp4)":`视频 — 仅此镜头 (mp4)`,"Depth + normal passes":`深度 + 法线通道`,"Depth pass of the whole shot as an mp4 for video-model conditioning":`将整个镜头的深度通道导出为 mp4,用于视频模型条件控制`,"Depth (mp4)":`深度 (mp4)`,"Contact sheet of every shot with its prompt":`包含所有镜头及其提示词的缩略图总览`,"Add a shot first — a storyboard is one row per shot":`请先添加镜头 — 故事板每个镜头一行`,"Storyboard (PNG)":`故事板 (PNG)`,"Download OTIO cut list":`下载 OTIO 剪辑表`,"OTIO cut list":`OTIO 剪辑表`,"Add a shot to export OTIO":`添加镜头后才能导出 OTIO`,"Add a shot to export video or OTIO":`添加镜头后才能导出视频或 OTIO`,"Preferences…":`偏好设置…`,"Open Workflow":`打开工作流`,Workflow:`工作流`,"Keyboard shortcuts":`键盘快捷键`,"About Cozy Clay":`关于 Cozy Clay`,"Menu bar":`菜单栏`,"Stage / Pose / Camera / Motion mode":`舞台 / 姿势 / 摄影机 / 动作模式`,"Pick the tool of the current mode":`选择当前模式的工具`,"Frame the selection":`将所选内容适配到画面`,"Play / pause":`播放 / 暂停`,"Step one frame":`移动一帧`,"Export keyframe pack":`导出关键帧包`,"Duplicate object":`复制物体`,"Delete the selection":`删除所选内容`,"Previs studio: stage, pose, camera and motion.":`预演工作室:舞台、姿势、摄影机和动作。`,Version:`版本`,Hierarchy:`层级`,General:`常规`,Appearance:`外观`,Viewport:`视口`,Hotkeys:`快捷键`,"Preferences navigation":`偏好设置导航`,Preferences:`偏好设置`,"Close preferences":`关闭偏好设置`,"Search preferences":`搜索偏好设置`,"Preference sections":`偏好设置分区`,"Timeline frame rate":`时间线帧率`,"Finalizing MP4; this stage cannot be interrupted.":`正在完成 MP4;此阶段无法中断。`,Retry:`重试`,"just now":`刚刚`,"Resize hierarchy panel":`调整层级面板大小`,"Resize hierarchy and inspector panel":`调整层级和属性面板大小`,"Resize frame monitor":`调整帧监视器大小`,"Resize shot preview":`调整镜头预览大小`,"No MCP client is attached to this studio":`此工作室未连接任何 MCP 客户端`,"MCP connected":`MCP 已连接`,"MCP offline":`MCP 离线`,Stage:`舞台`,Sculpt:`雕塑`,Move:`移动`,Rotate:`旋转`,"Pose fix (IK parts)":`姿势修正(IK 部位)`,"Pin (range pin)":`固定(区间固定)`,"Pinning needs a motion take":`固定需要已加载的动作片段`,"Move camera":`移动摄影机`,"Rotate camera":`旋转摄影机`,"Front view":`前视图`,"Side view":`侧视图`,"Back view":`后视图`,"Lens — pick a prime or set the field of view":`镜头 — 选择定焦或设置视场角`,"Output aspect ratio":`输出画幅比`,"Add an object, a character or a camera":`添加物体、角色或摄影机`,Add:`添加`,Scene:`场景`,Tools:`工具`,"Mode and tools":`模式与工具`,"Views and shot cameras":`视图与镜头摄影机`,Perspective:`透视`,View:`视图`,"Show the Top-View inset":`显示顶视图小窗`,Top:`顶视`,"Shot cameras":`镜头摄影机`,"Show this shot's camera in the preview":`在预览中显示此镜头的摄影机`,"Shot framing":`镜头取景`,"Shot preset":`镜头预设`,Cam:`摄影机`,"Camera preset":`摄影机预设`,Free:`自由`,"Recenter on subject":`重新对准角色`,Shading:`着色`,"Clay Lit":`黏土受光`,"Viewport display toggles":`视口显示开关`,"Viewport display":`视口显示`,"Blender-style viewport — dark void with a reference grid instead of the deck":`Blender 风格视口 — 用深色虚空和参考网格替代台面`,"Reference grid":`参考网格`,"Distinct display colors per object — captures include them while on":`每个物体使用区分色 — 开启时捕捉也会包含`,"Auto Color":`自动配色`,"Composition guides":`构图参考线`,"Body part colours":`身体部位颜色`,Shaded:`明暗`,Flat:`平面`,Panels:`面板`,"Show the agent chat column (Cmd/Ctrl+B)":`显示智能体对话栏 (Cmd/Ctrl+B)`,"Agent panel":`智能体面板`,"Fly speed — scroll while right-dragging to change it":`飞行速度 — 右键拖动时滚动调节`,Empty:`空物体`,Mesh:`网格`,Node:`节点`,Prop:`道具`,Bone:`骨骼`,Selection:`所选内容`,"Focal length":`焦距`,"No shot camera":`无镜头摄影机`,"Focal length — drag to change, click an arrow for the next lens":`焦距 — 拖动改变,点击箭头切换下一个镜头`,Dark:`深色`,Theme:`主题`,Display:`显示`,Language:`语言`,"Choose the labels used throughout the editor.":`选择编辑器界面使用的语言。`,"Dark keeps the studio dim around the stage; Light uses bright glass panels.":`深色主题让舞台周围保持昏暗;浅色主题使用明亮的玻璃面板。`,Editor:`编辑器`,"Auto colour":`自动配色`,"Give scene objects stable display colours.":`为场景物体使用稳定的显示颜色。`,"Anonymous analytics":`匿名统计`,"Help improve CozyClay with anonymous product events.":`通过匿名产品事件帮助改进 CozyClay。`,"Use a dark reference grid instead of the clay deck.":`使用深色参考网格替代黏土台面。`,"Shortcuts are read-only here. They stay active whenever focus is outside a text field.":`此处快捷键为只读。只要焦点不在文本输入框内,快捷键始终生效。`},Bn={frames:`帧`,"Agent draft beats":`智能体草稿节拍`,"The agent's newest draft, not installed yet":`智能体的最新草稿,尚未应用`,"Compiled take":`已编译的动作片段`,"Drag to trim · right-click restores the full take":`拖动裁剪 · 右键恢复完整片段`,"Trim take start":`裁剪片段起点`,"Retime segment by stretch":`拖动拉伸调整片段速度`,"Drag — wider is slower, narrower is faster":`拖动 — 拉长变慢,缩短变快`,"Trim take end":`裁剪片段终点`,"Cut the Full-Body clip at the playhead":`在播放头处切分全身片段`,Cut:`切分`,"Selected Full-Body segment speed":`所选全身片段的速度`,"Selected Full-Body segment speed value":`所选全身片段的速度值`,Body:`身体`,"Root path":`根路径`,"Camera Cuts":`摄影机剪辑`,"Crane height: click to add, click a point to select, drag vertically to change height":`摇臂高度:点击添加,点击点选中,上下拖动改变高度`,average:`平均`,"Pin the instant at the playhead: the spot being walked then never moves again":`固定播放头这一刻:此时正经过的位置此后不再移动`,"Cut at playhead":`在播放头处切分`,"Back to constant speed — clears the curve and every cut":`恢复匀速 — 清除曲线和所有切分`,"Reset curve":`重置曲线`,"Drag the curve · double-click or the button cuts · Delete removes a cut":`拖动曲线 · 双击或按按钮切分 · Delete 删除切分`,"Cut: click to select, Delete removes it":`切分:点击选中,Delete 删除`,PROP:`道具`,"Drawing…":`绘制中…`,"Redraw path":`重绘路径`,"Draw path":`绘制路径`,"Metres per second; 0 spreads the route across the whole take":`米/秒;为 0 时在整个片段内均匀走完`,Speed:`速度`,"Travel speed":`移动速度`,"fills take":`铺满片段`,"Turn to face the direction of travel":`转向行进方向`,"Faces travel":`朝行进方向`,"Fixed facing":`固定朝向`,"Keep going in the last direction after the route ends":`路径结束后沿最后方向继续前进`,"Keep going":`继续前进`,Loop:`循环`,"Delete this route; the object stands still again":`删除此路径;物体将重新静止`,"Delete path":`删除路径`,"Draw a route on the Top-View map to make this prop travel.":`在顶视图地图上绘制路径,让此道具移动。`,Dots:`点`,"Add a dot where the prop is on this frame":`在当前帧道具所在位置添加一个点`,"No room for a dot here: the route is full, or the playhead is on a dot or an end":`此处无法添加点:路径已满,或播放头位于某个点或端点`,"Add dot at playhead":`在播放头处添加点`,"Ends are always level; select a dot between them to lean the prop there":`两端始终水平;选中中间的点可让道具在该处倾斜`,Bank:`侧倾`,"Roll about the direction of travel; positive leans onto the right side":`绕行进方向滚转;正值向右侧倾`,Pitch:`俯仰`,"Nose up (positive) or down; the prop holds this angle at the dot":`抬头(正值)或低头;道具在该点保持此角度`,"Eases back to level at the next dot · E shows rings on the dot":`在下一个点缓动回水平 · 按 E 在点上显示圆环`,"Ends stay level":`两端保持水平`,"Select a dot to lean the prop there":`选中一个点让道具在该处倾斜`,CAMERA:`摄影机`,"Turn Waypoint off to edit or preview this camera.":`关闭路径点后才能编辑或预览此摄影机。`,"Turn Waypoint off":`关闭路径点`,Stop:`停止`,Preview:`预览`,"Redraw rail":`重绘轨道`,"Draw rail":`绘制轨道`,"Shot curve":`镜头曲线`,"Draw dolly speed in the Shot box":`在镜头栏中绘制推轨速度`,"Draw crane height in the Shot box":`在镜头栏中绘制摇臂高度`,Height:`高度`,"Pin the instant at the playhead: the spot being passed then never moves again":`固定播放头这一刻:此时经过的位置此后不再移动`,"Read automatically from the camera position":`从摄影机位置自动读取`,Distance:`距离`,"Cap dolly travel speed":`限制推轨的最高移动速度`,"Read automatically from the camera tilt":`从摄影机俯仰自动读取`,"Lens height of the selected crane point — click a purple dot in the scene to pick one, double-click the lifted curve to add one":`所选摇臂点的镜头高度 — 点击场景中的紫点选择,双击抬起的曲线可添加`,"Point height":`点高度`,"Crane points on this rail — click the Shot block's key strip to add one":`此轨道上的摇臂点 — 点击镜头栏的关键帧条添加`," pts":` 点`,"Remove the selected interior crane point":`删除所选中间摇臂点`,"Remove point":`删除点`,Advanced:`高级`,"Delete this Shot's rail geometry and return to Follow":`删除此镜头的轨道几何并返回跟随模式`,"Delete rail":`删除轨道`,"Keep the camera at the captured distance from the subject":`让摄影机与角色保持捕获时的距离`,"Follow On":`跟随开`,"Follow Off":`跟随关`,"Choose whether the dolly starts at the rail head or the nearest useful point":`选择推轨从轨道起点还是最近的有效点出发`,"Head start":`起点出发`,Nearest:`最近点`,"Set how softly the rig catches up":`设置摄影机跟随的柔和程度`,Damping:`阻尼`,"Aim ahead of subject travel":`朝角色行进方向预瞄`,"Look-ahead":`预瞄`,"Dolly on rail":`轨道推轨`,"Camera preview":`摄影机预览`,"Animation timeline":`动画时间线`,Sequencer:`序列器`,"Playback transport":`播放控制`,"Previous frame":`上一帧`,"Previous frame (k)":`上一帧 (k)`,"Pause playback":`暂停播放`,"Play playback":`开始播放`,"Play / pause (Space)":`播放/暂停 (Space)`,"Next frame":`下一帧`,"Next frame (j)":`下一帧 (j)`,"Sequencer actions":`序列器操作`,"Split the selected Camera Cut at the playhead":`在播放头处切分所选摄影机剪辑`,"Add or select a shot first — the rail belongs to a shot":`请先添加或选择镜头 — 轨道属于镜头`,"Draw or redraw the selected camera rail":`绘制或重绘所选摄影机轨道`,"Add a Camera Cut track block":`添加摄影机剪辑轨道块`,"+ Track":`+ 轨道`,"Timeline view tools":`时间线视图工具`,"Timeline zoom":`时间线缩放`,"Two-finger up/down over FRAME ruler to zoom — click to reset to 1×":`在帧标尺上双指上下滚动缩放 — 点击重置为 1×`,"Root path mode":`根路径模式`,"Enable or disable root path constraints (P)":`开启或关闭根路径约束 (P)`,"Pose correction tools":`姿势修正工具`,"Load a rig to edit poses":`加载骨骼后才能编辑姿势`,"Foot snap":`脚部吸附`,"Foot snap — keep the feet planted while you move the body (hips); the knees bend instead of the feet sinking through the floor":`脚部吸附 — 移动身体(髋部)时双脚保持踩地;膝盖弯曲而不是脚陷进地面`,"Body contact":`身体接触`,"Body contact — keep hands, knees, feet, head, and hips above the floor":`身体接触 — 让手、膝、脚、头和髋部都不低于地面`,"Motion controls":`动作控制`,"Clear loaded motion":`清除已加载的动作`,"Clear the compiled take, then restore the blocking pose":`清除已编译的动作片段,然后恢复摆位姿势`,"Clear motion":`清除动作`,"Click the set floor in the Shot view to drop waypoints":`在镜头视图中点击布景地面放置路径点`,"Collapse timeline":`折叠时间线`,"Scrub timeline":`浏览时间线`,Pins:`固定`,"IK keys":`IK 键`,Rail:`轨道`,Crane:`摇臂`,"Add a 2 second shot without changing existing shots":`添加一个 2 秒镜头,不改变现有镜头`,"+ Add shot":`+ 添加镜头`,"No shots yet — use + Add shot in the lane header to create one.":`还没有镜头 — 点击轨道标题栏的 + 添加镜头创建。`,s:`秒`,"Split at the playhead":`在播放头处切分`,Split:`切分`,"Duplicate shot":`复制镜头`,"Delete shot and leave free-camera time":`删除镜头并留出自由摄影机时间`,"Crane height — drag a point, click empty time to add one":`摇臂高度 — 拖动点,点击空白时间添加`,"Dolly speed — drag the line; cuts and reset live in the camera bar above":`推轨速度 — 拖动线条;切分和重置在上方摄影机栏`,"Click the crane graph to add a point; click a point and drag it to change height":`点击摇臂曲线添加点;点击点并拖动改变高度`,"Click at a frame to store the current camera framing":`在某一帧点击以保存当前摄影机取景`,"Click the set floor in the Shot view to add waypoints":`在镜头视图中点击布景地面添加路径点`,"Expand timeline":`展开时间线`},Vn={"Agent server is not running":`智能体服务器未运行`,"Checking…":`检查中…`,helper:`助手`,advisor:`顾问`,vision:`视觉`,blocker:`阻断`,concern:`顾虑`,note:`备注`,done:`完成`,partial:`部分完成`,missing:`缺失`,"Supervisor review unavailable":`监督审查不可用`,Supervisor:`监督`,Less:`收起`,"Autofix is on: the blocker fixes would be applied as written":`自动修复已开启:阻断项修复将按原样应用`,"Apply fixes as next prompt":`将修复作为下一轮提示`,"Send as next prompt":`作为下一轮发送`,"Sign-in could not start.":`无法开始登录。`,"The agent server is not running":`智能体服务器未运行`,"Task mode":`任务模式`,Tasks:`任务`,"in progress":`进行中`,next:`下一步`,"not finished":`未完成`,Plan:`计划`,"Close image":`关闭图片`,"Image the agent checked":`智能体查看过的图片`,Installed:`已安装`,"Not installed yet":`尚未安装`,"Not installed":`未安装`,Goals:`目标`,met:`已达成`,missed:`未达成`,"Largest issues":`最严重的问题`,"What the agent looked at":`智能体查看的内容`,running:`运行中`,failed:`失败`,stopped:`已停止`,"The turn failed.":`本轮失败。`,"Compile waits for a free worker":`编译正在等待空闲工作进程`,"need a look":`需要查看`,waiting:`等待中`,"No steps yet.":`暂无步骤。`,"Sent to this task.":`已发送到此任务。`,Chat:`对话`,"Cancelled; its changes go back.":`已取消;改动已回滚。`,"Undone.":`已撤销。`,"Undo task":`撤销任务`,Touches:`涉及`,"Tell this task…":`告诉此任务…`,"Tell this task":`告诉此任务`,"Block a two-shot":`摆一个双人镜头`,"Frame the selected character":`给所选角色取景`,"Light the set warmer":`把布光调暖`,"Read the scene":`读取场景`,"Selection and view":`选择与视图`,"Arrange objects":`摆放物体`,"Arrange characters":`摆放角色`,"Edit properties":`编辑属性`,"Frame the shot":`取景镜头`,"Generate motion":`生成动作`,"Verify the result":`验证结果`,"Undo an edit":`撤销编辑`,"Run an editor action":`执行编辑器操作`,"Direct the scene":`导演场景`,"Ask the agent to block, frame or animate…":`让智能体摆位、取景或做动画…`,"Supervisor review — please address:":`监督审查 — 请处理:`,"Supervisor review — apply these fixes exactly, in order, in ONE script call, then verify_result; do not re-derive them:":`监督审查 — 请按顺序在一次 script 调用中完全照此修复,然后 verify_result;不要重新推导:`,"Also check:":`同时检查:`,Script:`脚本`,"cameras cross the line":`摄影机越轴`,"motion checked":`动作已检查`,"motion unverified":`动作未验证`,"looked at a contact sheet":`查看了缩略图总览`,"looked at the frame":`查看了画面`,"stale evidence":`过期的证据`,"not applied":`未应用`,"result unknown":`结果未知`," · its edits were rolled back":` · 其编辑已回滚`,started:`已开始`,Working:`处理中`,Stopped:`已停止`,Done:`完成`,"Changed the scene":`修改了场景`,"Stopped by you. What already ran stays in the scene; Cmd+Z undoes this turn.":`你已停止。已执行的操作会留在场景中;按 Cmd+Z 可撤销这一轮。`,"Stopped by you while a step was running; its result is unknown.":`你在某一步运行时停止了;该步骤结果未知。`,"Stopped by you before anything changed in the scene.":`你在场景发生任何改动前停止了。`,Queued:`排队中`,"Waiting for scope":`等待占用范围`,Starting:`启动中`,Running:`运行中`,"Paused: Studio lost":`已暂停:Studio 已断开`,"Being checked":`检查中`,"Starts when another task frees its part":`等其他任务释放该部分后开始`,"Working…":`处理中…`,timeline:`时间线`,stage:`舞台`,scene:`场景`,object:`物体`,character:`角色`,shot:`镜头`},Hn={"Capsule figure":`胶囊人物`,"(unreadable image)":`(无法读取的图片)`,"Untitled model":`未命名模型`,"Untitled image":`未命名图片`,Model:`模型`,"HDR environment":`HDR 环境`,Matte:`遮罩`,Image:`图像`,"Loading details…":`正在加载详情…`,"Unused by every scene. Delete it?":`所有场景都未使用。删除吗?`,Delete:`删除`,Cancel:`取消`,"Deleting…":`正在删除…`,"Manage storage":`管理存储`,"Review unused and in-use stored images. Deleted images can be restored until this page is reloaded.":`查看未使用和正在使用的存储图片。删除的图片可在刷新页面前恢复。`,"No stored image assets.":`没有存储的图片资源。`,Unused:`未使用`,"No unused image assets. Every stored image is still used by a scene.":`没有未使用的图片资源。所有存储图片仍被场景使用。`,"In use":`使用中`,"No stored image assets are used by a scene.":`没有被场景使用的存储图片资源。`,Unreadable:`无法读取`,"Basic Shapes":`基础形状`,Characters:`角色`,Props:`道具`,Cameras:`摄影机`,Motions:`动作`,Poses:`姿势`,Shape:`形状`,Character:`角色`,"No imported props yet. Drop or paste a picture, or drop a .glb, .obj or .fbx into the studio.":`还没有导入的道具。拖放或粘贴图片,或将 .glb、.obj、.fbx 文件拖入工作室。`,Camera:`摄影机`,"No shot cameras yet. Use + Add › Camera in the viewport.":`还没有镜头摄影机。使用视口中的 + 添加 › 摄影机。`,Motion:`动作`,"No takes for this character yet. Ask the agent to compile one.":`此角色还没有动作片段。请让智能体编译一个。`,Pose:`姿势`,"No saved poses yet. Save one from the pose studio.":`还没有保存的姿势。请在姿势工作室中保存。`,"Nothing matches this search.":`没有匹配此搜索的结果。`,Note:`通知`,Generate:`生成`,Export:`导出`,Info:`信息`,"No events yet this session. Notices, generation jobs and exports appear here.":`本次会话还没有事件。通知、生成任务和导出会显示在这里。`,Content:`内容`,"Expand content":`展开内容`,"Collapse content":`折叠内容`,"Expand Content":`展开内容`,"Collapse Content — the Sequencer takes the full width":`折叠内容 — 序列器将占满宽度`,"Content and Log":`内容与日志`,Log:`日志`,Folder:`文件夹`,Location:`位置`,"This session":`本次会话`,"Search objects":`搜索物体`,Search:`搜索`,"Search the log":`搜索日志`,Folders:`文件夹`,"Drag into the scene to place":`拖入场景以放置`,"New project":`新建项目`,"Start from an empty stage.":`从空舞台开始。`,Storyboard:`故事板`,"Describe scenes in words and direct one panel at a time. Output: image references.":`用文字描述场景,逐个面板进行导演。产出:图像参考。`,Animation:`动画`,"Block and shoot continuous motion. Output: clip references.":`摆位并拍摄连续动作。产出:片段参考。`,Recently:`最近`,"Project name":`项目名称`,Create:`创建`,"Enter a project name to create a project":`输入项目名称以创建项目`,"Browser project store":`浏览器项目存储`,Recent:`最近`,Learn:`了解`,"Choose project":`选择项目`,"Project navigation":`项目导航`,"Project mode":`项目模式`,"Block a shot in three moves":`三步完成镜头摆位`,"Choose a template, name the project, then place a character and frame the camera in the editor.":`选择模板、命名项目,然后在编辑器中放置角色并为摄影机取景。`,"Start a new project":`开始新项目`,"Recent projects":`最近项目`,Refresh:`刷新`,"Open project file…":`打开项目文件…`,"Open project":`打开项目`,"A saved .cclayproject file":`已保存的 .cclayproject 文件`,"No recent projects in this browser yet. ":`此浏览器中还没有最近项目。`,"Open a project file…":`打开项目文件…`,"Project templates":`项目模板`,"Start from an empty stage":`从空舞台开始`,"Project preview":`项目预览`,"Choose the project storage folder":`选择项目存储文件夹`,"Projects are stored in this browser":`项目存储在此浏览器中`,"Frame rate":`帧率`,Units:`单位`,"Folder access needs to be re-allowed.":`需要重新允许文件夹访问。`,"Using the browser project store.":`正在使用浏览器项目存储。`,"Re-allow":`重新允许`,"Create project":`创建项目`,"No recent projects yet.":`还没有最近项目。`," shots":` 个镜头`,"Remove from list":`从列表中移除`,"Missing object":`缺少物体`,"Load a motion before creating a pin.":`创建固定前请先加载动作。`,"Choose a hand or foot.":`请选择手或脚。`,"In and Out must be whole frames.":`In 和 Out 必须是整数帧。`,"Out must be on or after In.":`Out 必须不早于 In。`,"Choose a scene object.":`请选择场景物体。`,"That scene object is no longer available.":`该场景物体已不可用。`,"Blend must be at least one frame.":`混合必须至少为一帧。`,"Hold at In":`固定在 In`,"Range pins":`区间固定`,"Hold a hand or foot across a frame range":`在帧区间内固定手或脚`,New:`新建`,"Load a motion to enable range pins.":`加载动作后才能使用区间固定。`,Part:`部位`,"Pin part":`固定部位`,Range:`区间`,In:`起点`,Out:`终点`,"Set In to playhead":`将 In 设为播放头`,"Set Out to playhead":`将 Out 设为播放头`,"Keyboard: I sets In · O sets Out":`键盘:I 设置 In · O 设置 Out`,Target:`目标`,"Pin target":`固定目标`,"Hold where it is at In":`固定在 In 时的位置`,"Capture the part's world position at the In frame.":`记录该部位在 In 帧的世界坐标。`,"Stick to object":`附着到物体`,"Follow a scene object's transform and travel path.":`跟随场景物体的变换和移动路径。`,"Add a scene object to use an object target.":`添加场景物体后才能使用物体目标。`,"Scene object":`场景物体`,"Choose an object":`选择物体`,Following:`跟随对象`,"Body follows when out of reach":`够不到时身体跟随`,Blend:`混合`,"Replace confirmed":`已确认替换`,"Replace existing keys":`替换现有键`,"Update pin":`更新固定`,"Apply pin":`应用固定`,"No pins yet. Choose a part and apply a range.":`还没有固定。选择部位并应用区间。`,"Missing object target":`缺少物体目标`,"The referenced object was deleted.":`引用的物体已被删除。`,"Invalid target":`无效目标`,"Delete pin":`删除固定`,"Workflow output":`工作流输出`,"In project file":`项目文件内`,"External URL":`外部 URL`,"Browser-only copy":`仅浏览器副本`,Missing:`缺失`,"Project resources":`项目资源`,Size:`大小`,"Missing resources":`缺失资源`,"The project file would be too large.":`项目文件会过大。`,"Unknown reason":`未知原因`,"The project was not saved":`项目未保存`,OK:`确定`,"your AI video tool":`你的 AI 视频工具`,"your selected image model":`你选择的图像模型`," as the start frame, and ":`作为起始帧,并将 `," as the end frame.":`作为结束帧。`," as the reference frame.":`作为参考帧。`," as the reference image.":`作为参考图像。`,"Your shot is ready":`你的镜头已就绪`,"Close the result":`关闭结果`,"Camera move start frame":`摄影机运动起始帧`,Start:`开始`,"Camera move end frame":`摄影机运动结束帧`,End:`结束`,"Finished scene frame":`完成场景帧`,"Camera move made from timeline keyframes":`由时间线关键帧生成的摄影机运动`,Prompt:`提示词`,copied:`已复制`,"Copied ✓":`已复制 ✓`,"Copy prompt":`复制提示词`,Exported:`已导出`,"Export start and end frames":`导出起始和结束帧`,"Export frame":`导出帧`,"Handing off to your AI":`交付给 AI 的步骤`,"Copy the prompt":`复制提示词`,"Copied. Paste it into your AI service's prompt box.":`已复制。粘贴到 AI 服务的提示框中。`,"Press “Copy prompt” above, then paste it into your AI service.":`点击上方的“复制提示词”,然后粘贴到 AI 服务中。`,"Export the frame":`导出帧`,"Press “Export start and end frames” to save both PNGs.":`点击“导出起始和结束帧”保存两个 PNG。`,"Press “Export frame” to save the PNG.":`点击“导出帧”保存 PNG。`,"This result has no frame to export.":`此结果没有可导出的帧。`,"Attach the image to your AI":`将图像附加到 AI`,"Use your AI service's image attach button to upload the start and end frames together.":`使用 AI 服务的图片附件按钮,同时上传起始帧和结束帧。`,"Use your AI service's image attach button to upload blocking-frame.png.":`使用 AI 服务的图片附件按钮上传 blocking-frame.png。`,"The prompt describes the scene's content and mood; the frame shows the camera framing. Use both to reproduce this scene as closely as possible.":`提示词描述场景的内容和氛围;帧展示摄影机取景。两者结合才能尽量还原此场景。`,"Optional · Reference video":`可选 · 参考视频`,"A video recorded with the recording feature: ":`使用录制功能生成的 `," file. Use it separately from the reference frame in the prompt above.":`文件。请与上方提示词中的参考帧分开使用。`},Un=Object.freeze({...Fn,...In,...Ln,...Rn,...zn,...Bn,...Vn,...Hn}),Wn=`cozyclay.locale`,Gn=new Set([`en`,`ko`,`zh`]);function Kn(){try{let e=localStorage.getItem(Wn);return Gn.has(e)?e:null}catch{return null}}var qn=Kn()??`en`,Jn=qn===`ko`,Yn=qn===`zh`,Xn=Kn()!==null;function z(e,t,n){return Jn?t:Yn?n??Un[e]??e:e}function Zn(e){if(Gn.has(e)){try{localStorage.setItem(Wn,e)}catch{}window.location.reload()}}var Qn=1.8,$n=1.3,er=Object.freeze({super16:Object.freeze({id:`super16`,label:`Super 16`,widthMm:12.52,heightMm:7.41}),super35:Object.freeze({id:`super35`,label:`Super 35`,widthMm:24.89,heightMm:18.66}),fullFrame:Object.freeze({id:`fullFrame`,label:`Full Frame`,widthMm:36,heightMm:24}),"65mm":Object.freeze({id:`65mm`,label:`65mm`,widthMm:52.63,heightMm:23.01})}),tr=`fullFrame`,nr=16/9,rr=Object.freeze({"16:9":16/9,"2.39:1":2.39,"9:16":9/16,"1:1":1,"4:3":4/3,"12:7":12/7,"fal 480P":832/480});function ir(e){return rr[e]??1.7777777777777777}function ar(e=tr,t=nr){let n=er[e]??er.fullFrame,r=Number.isFinite(t)&&t>0?t:nr;return Math.min(n.heightMm,n.widthMm/r)}function or(e,t=tr,n=nr){return ar(t,n)/(2*Math.tan(e/2))}function sr(e,t=tr,n=nr){return 2*Math.atan(ar(t,n)/(2*e))}var cr=[14,18,24,28,35,50,85,100,135];function lr(e,t=tr,n=nr){let r=or(e,t,n);return cr.reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var ur=[[2.8,`extreme close-up`,`ultra-realistic skin texture with visible pores and micro-detail, tack-sharp eyes, shallow depth of field`],[1.6,`close-up`,`ultra-realistic skin texture and fine facial detail, soft background blur, shallow depth of field`],[1.15,`medium close-up`,`natural skin and fabric texture, clear facial detail, shallow depth of field`],[.8,`medium shot`,`balanced detail on the subject and the surrounding space, moderate depth of field`],[.52,`medium-wide shot`,`the full figure with the environment clearly visible, deep focus`],[.3,`wide shot`,`full body in a richly detailed environment, deep focus`],[0,`extreme wide shot`,`a small figure within a vast, highly detailed environment, epic sense of scale, deep focus`]],dr=[[2.5,`overhead`,`a directly overhead bird's-eye view looking down at the subject`],[1.8,`high angle`,`a high angle looking down at the subject`],[1.5,`eye level`,`eye level`],[1.25,`chest level`,`chest level`],[.95,`hip level`,`a low hip-level angle`],[.45,`knee level`,`a low knee-level angle looking up at the subject`],[-1/0,`ground level`,`a dramatic ground-level angle looking up at the subject`]],fr=(e,t)=>e.find(([e])=>t>=e)??e[e.length-1];function pr(e,t,n,r=Qn,i={}){let a=i.sensorId??`fullFrame`,o=i.aspectRatio??1.7777777777777777,s=e.x-t.x,c=e.z-t.z,l=e.y-$n,u=Math.hypot(s,c),d=Math.max(Math.hypot(u,l),1e-6),f=r/(2*d*Math.tan(n/2)),[,p,m]=fr(ur,f),[,h,g]=fr(dr,e.y),_=Math.atan2(e.y-r*.94,Math.max(u,1e-6))*180/Math.PI,v=t.rot*Math.PI/180,y={x:Math.sin(v),z:Math.cos(v)},b={x:s/Math.max(u,1e-6),z:c/Math.max(u,1e-6)},x=y.x*b.x+y.z*b.z,S=y.x*b.z-y.z*b.x>=0?`right`:`left`,C=S===`right`?`R`:`L`,w,T;return x>.85?(w=`front`,T=`seen from the front, the face toward the camera`):x<-.85?(w=`back`,T=`seen from directly behind, the back of the head toward the camera`):x>.34?(w=`front ¾ ${C}`,T=`a three-quarter front view from the ${S}`):x<-.34?(w=`rear ¾ ${C}`,T=`a three-quarter rear view from the ${S}`):(w=`${S} profile`,T=`a ${S}-side profile view`),{sizeLabel:p,sizeContext:m,levelLabel:h,levelPhrase:g,viewShort:w,viewPhrase:T,focalMm:lr(n,a,o),exactFocalMm:or(n,a,o),sensorId:er[a]?.id??`fullFrame`,usedSensorHeightMm:ar(a,o),distance:d,screenFraction:f,elevationDeg:_}}var mr=[{id:`nano_banana_pro`,label:`Nano Banana Pro`},{id:`nano_banana_2`,label:`Nano Banana 2`},{id:`gpt_image_2`,label:`GPT Image 2`},{id:`seedream_5`,label:`Seedream 5.0`},{id:`flux_2`,label:`Flux 2`,numericLens:!0,flavor:`fine film grain, high micro-detail`}],hr=`Custom…`,gr=[`Static / locked-off`,`Push-in (dolly in)`,`Pull-out (dolly out)`,`Pan left`,`Pan right`,`Tilt up`,`Tilt down`,`Tracking / follow`,`Orbit / arc`,`Crane up`,`Crane down`,`Handheld`,`Crash zoom in`,`Dolly-zoom (vertigo)`,`Whip pan`,`Aerial / drone`,hr];function _r({mode:e=`image`,model:t,shot:n,subject:r,subject2:i=null,posePhrase:a=``,pose2Phrase:o=``,environment:s,style:c,cameraMove:l=gr[0],customMove:u=``,hasCharSheet:d=!1,hasEnvSheet:f=!1}){let p=t?.numericLens?`${n.focalMm}mm lens at f/2.2`:`${n.focalMm}mm lens`,m=e===`video`?`Cinematic ${n.sizeLabel} at ${p}, ${n.levelPhrase}, ${n.viewPhrase}.`:`Photorealistic cinematic film still, ${n.sizeLabel} at ${p}, ${n.levelPhrase}, ${n.viewPhrase}.`,h=(e,t)=>t?`${e}, ${t}`:e,g;g=d?i?`Both subjects are the characters from the attached character sheet. Each one exactly matches their own body pose and placement shown in the blocking frame.`:`The subject is the character from the attached character sheet, exactly matching the body pose and placement shown in the blocking frame.`:i?`Two subjects. Subject 1: ${h(r,a)}. Subject 2: ${h(i,o)}. Each subject exactly matches their own body pose and placement shown in the blocking frame.`:`Subject: ${h(r,a)}, exactly matching the body pose and placement shown in the blocking frame.`;let _=f?`The setting is the location from the attached environment sheet.`:`Environment: ${s}.`,v=l===`Custom…`?u.trim()||`static, locked-off shot`:l.toLowerCase();return[m,g,_,`${c}, ${n.sizeContext}.`,e===`video`?`Camera move: ${v}.`:null,`Use the attached blocking frame ONLY as a camera and staging guide — it fixes the exact framing, this camera angle, the lens, and the subject placement. Its floor grid is a measuring aid that encodes distance and scale: read the subject's depth and size from it, but do NOT draw the grid itself. Replace the entire setting with the described environment and render real people; do NOT reproduce its grey mannequins, grey box set, measurement grid, or flat lighting.`,t?.flavor??null,e===`video`&&(t?.audio||t?.capabilities?.audio)?`Include natural ambient sound.`:null,`16:9.`].filter(Boolean).join(` `)}var vr=.02,yr=(e,t,n)=>Math.min(n,Math.max(t,e)),br=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)?e:t;function xr(e){let t=0;for(let n=0;n<e.length-1;n+=1)t+=(e[n]+e[n+1])/2;return t}function Sr(e,t){let n=yr(t,0,1)*(e.length-1),r=Math.min(e.length-2,Math.floor(n)),i=n-r;return e[r]*(1-i)+e[r+1]*i}function Cr(e,t=24){if(!e.length)return Array(t).fill(1);if(e.length===1)return Array(t).fill(e[0]);let n=Array(t);for(let r=0;r<t;r+=1)n[r]=Sr(e,r/(t-1));return n}function wr(e){let t=e.map(e=>Math.max(0,br(e,0))),n=xr(t)/(t.length-1);return n<=1e-9?t.map(()=>1):t.map(e=>e/n)}function Tr(e){return e.every(e=>Math.abs(e-1)<1e-6)}function Er(){return{cuts:[],envelopes:[Array(24).fill(1)]}}function Dr(e){return!e||e.cuts.length===0&&e.envelopes.every(Tr)}function Or(e){if(!e||typeof e!=`object`)return null;let t=Array.isArray(e.cuts)?e.cuts:[],n=[];for(let e of t){let t=br(e?.t,NaN),r=br(e?.d,NaN);if(!(t>0&&t<1&&r>0&&r<1))continue;let i=n[n.length-1];i&&(t<=i.t+1e-6||r<=i.d+1e-6)||n.push({t,d:r})}let r=Array.isArray(e.envelopes)?e.envelopes:[],i=[];for(let e=0;e<=n.length;e+=1){let t=Array.isArray(r[e])?r[e].map(e=>br(e,1)):[];i.push(wr(Cr(t.length>=2?t:[1,1])))}return{cuts:n,envelopes:i}}function kr(e,t,n,r=.18){let i=e.length,a=Math.max(0,br(n,0)),o=yr(br(t,0),0,1),s=r/3,c=Array(i);for(let e=0;e<i;e+=1){let t=Math.abs(e/(i-1)-o);c[e]=t<=s?1:t>=r?0:.5*(1+Math.cos((t-s)/(r-s)*Math.PI))}let l=e.map((e,t)=>Math.max(0,e*(1-c[t])+a*c[t])),u=e=>e===0||e===i-1?.5:1,d=i-1,f=0,p=0;for(let e=0;e<i;e+=1)c[e]>1e-9?f+=u(e)*l[e]:p+=u(e)*l[e];if(p>1e-9){let e=Math.max(0,(d-f)/p);for(let t=0;t<i;t+=1)c[t]<=1e-9&&(l[t]*=e);if(d-f<0){let e=d/f;for(let t=0;t<i;t+=1)c[t]>1e-9&&(l[t]*=e)}}else if(f>1e-9){let e=d/f;for(let t=0;t<i;t+=1)l[t]*=e}else return Array(i).fill(1);return l}function Ar(e,t){let n=e.length,r=xr(e);if(r<=1e-9)return yr(t,0,1);let i=yr(t,0,1)*(n-1),a=Math.min(n-2,Math.floor(i)),o=i-a,s=0;for(let t=0;t<a;t+=1)s+=(e[t]+e[t+1])/2;let c=e[a]*(1-o)+e[a+1]*o;return s+=(e[a]+c)/2*o,s/r}function jr(e,t){let n=yr(br(t,0),0,1);if(!e)return n;let r=[{t:0,d:0},...e.cuts,{t:1,d:1}],i=0;for(;i<r.length-2&&n>r[i+1].t;)i+=1;let a=r[i],o=r[i+1],s=o.t-a.t,c=s>1e-9?(n-a.t)/s:1;return a.d+(o.d-a.d)*Ar(e.envelopes[i],c)}function Mr(e,t,n){let r=Array(24);for(let i=0;i<24;i+=1)r[i]=Sr(e,t+(n-t)*(i/23));return r}function Nr(e,t){let n=e??Er(),r=br(t,NaN);if(!(r>.02&&r<.98))return e;for(let t of n.cuts)if(Math.abs(t.t-r)<.02)return e;let i=jr(n,r);if(!(i>1e-6&&i<1-1e-6))return e;let a=0;for(;a<n.cuts.length&&r>n.cuts[a].t;)a+=1;let o=a===0?{t:0}:n.cuts[a-1],s=a===n.cuts.length?{t:1}:n.cuts[a],c=(r-o.t)/(s.t-o.t),l=n.envelopes[a];return{cuts:[...n.cuts.slice(0,a),{t:r,d:i},...n.cuts.slice(a)],envelopes:[...n.envelopes.slice(0,a),wr(Mr(l,0,c)),wr(Mr(l,c,1)),...n.envelopes.slice(a+1)]}}function Pr(e,t){if(!e||!e.cuts[t])return e;let n=[{t:0,d:0},...e.cuts,{t:1,d:1}],r=n[t],i=n[t+1],a=n[t+2],o=(i.t-r.t)/(a.t-r.t),s=(i.d-r.d)/(a.d-r.d),c=1-o,l=1-s,u=e.envelopes[t],d=e.envelopes[t+1],f=Array(24);for(let e=0;e<24;e+=1){let t=e/23;if(t<=o){let n=Sr(u,o>1e-9?t/o:0);f[e]=s/Math.max(1e-9,o)*n}else{let n=Sr(d,c>1e-9?(t-o)/c:0);f[e]=l/Math.max(1e-9,c)*n}}return{cuts:[...e.cuts.slice(0,t),...e.cuts.slice(t+1)],envelopes:[...e.envelopes.slice(0,t),wr(f),...e.envelopes.slice(t+2)]}}var Fr=e=>{let t=Math.round(e*1e4)/1e4;return t===0?0:t},Ir=e=>typeof e==`number`&&Number.isFinite(e),B=class extends Error{constructor(e,t){super(`${e}: ${t}`),this.path=e}};function Lr(e,t,n,r){if(e===void 0&&n)return[...n];if(!Array.isArray(e)||e.length!==3||!e.every(Ir))throw new B(t,`must be three numbers [x, y, z], got ${JSON.stringify(e)}`);return e.forEach((e,n)=>r(e,`${t}[${n}]`)),e.map(Fr)}function Rr(e,t,n,r,i){if(e===void 0)return n;if(!Ir(e)||e<r||e>i)throw new B(t,`must be a number from ${r} to ${i}, got ${JSON.stringify(e)}`);return Fr(e)}function zr(e,t,n,r,i){if(e===void 0&&n!==void 0)return n;if(!Number.isInteger(e)||e<r||e>i)throw new B(t,`must be a whole number from ${r} to ${i}, got ${JSON.stringify(e)}`);return e}var Br=(e,t)=>zr(e,t,0,0,999999);function Vr(e,t,n,r){if(e===void 0&&n!==void 0)return n;if(!r.includes(e))throw new B(t,`must be one of ${r.join(`, `)}; got ${JSON.stringify(e)}`);return e}var Hr=/^#?([0-9a-f]{3})$/i,Ur=/^#?([0-9a-f]{6})$/i;function Wr(e,t){let n=typeof e==`string`?e.trim():``,r=Hr.exec(n);if(r)return`#${r[1].toLowerCase().replace(/./g,e=>e+e)}`;let i=Ur.exec(n);if(i)return`#${i[1].toLowerCase()}`;throw new B(t,`colour must be #rgb or #rrggbb, got ${JSON.stringify(e)}`)}var Gr=48,Kr=6,qr=8,Jr=6,Yr=Math.cos(Math.PI/6),Xr=(e,t,n)=>[e[0]+(t[0]-e[0])*n,e[1]+(t[1]-e[1])*n],Zr=(e,t)=>Math.hypot(t[0]-e[0],t[1]-e[1]);function Qr(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n],i=e[(n+1)%e.length];t+=r[0]*i[1]-i[0]*r[1]}return t}function $r(e){let t=0,n=0;for(let r=0;r<e.length;r+=1){let i=e[r],a=e[(r+1)%e.length],o=i[0]*a[1]-a[0]*i[1];t+=(i[0]+a[0])*o,n+=(i[1]+a[1])*o}let r=Qr(e);return[t/(3*r),n/(3*r)]}function ei(e){let t=e.filter((t,n)=>n===0||Zr(t,e[n-1])>1e-9);for(;t.length>1&&Zr(t[0],t.at(-1))<=1e-9;)t.pop();return t}function ti({w:e,d:t,x:n,z:r,roundness:i}){let a=e/2,o=t/2,s=i*Math.min(a,o),c=s>0?Jr:0,l=[];for(let[e,t,i]of[[a-s,o-s,0],[s-a,o-s,1],[s-a,s-o,2],[a-s,s-o,3]])for(let a=0;a<=c;a+=1){let o=(i+(c?a/c:.5))*(Math.PI/2);l.push([n+e+s*Math.cos(o),r+t+s*Math.sin(o)])}return l}function ni(e){let t=e.length,n=[];for(let r=0;r<t;r+=1){let i=e[(r-1+t)%t],a=e[r],o=e[(r+1)%t],s=e[(r+2)%t],c=Math.sqrt(Zr(a,o)),l=Math.sqrt(Zr(i,a)),u=Math.sqrt(Zr(o,s));c<1e-4&&(c=1),l<1e-4&&(l=c),u<1e-4&&(u=c);let d=e=>{let t=((a[e]-i[e])/l-(o[e]-i[e])/(l+c)+(o[e]-a[e])/c)*c,n=((o[e]-a[e])/c-(s[e]-a[e])/(c+u)+(s[e]-o[e])/u)*c;return[a[e],t,-3*a[e]+3*o[e]-2*t-n,2*a[e]-2*o[e]+t+n]},f=d(0),p=d(1);for(let e=0;e<qr;e+=1){let t=e/qr;n.push([f[0]+t*(f[1]+t*(f[2]+t*f[3])),p[0]+t*(p[1]+t*(p[2]+t*p[3]))])}}return n}var ri=(e,t)=>[Math.min(...e.map(e=>e[t])),Math.max(...e.map(e=>e[t]))];function ii(e,t){let n=[0,1].map(n=>[ri(e,n),ri(t,n)]);return e.map(e=>e.map((e,t)=>{let[[r,i],[a,o]]=n[t];return i-r>1e-12?a+(e-r)*(o-a)/(i-r):e}))}function ai(e){let t=$r(e)[0],n=null;for(let r=0;r<e.length;r+=1){let i=e[r],a=e[(r+1)%e.length];if((i[0]-t)*(a[0]-t)>0)continue;let o=i[0]===a[0]?0:(t-i[0])/(a[0]-i[0]),s=i[1]+(a[1]-i[1])*o;(!n||s>n.z)&&(n={i:r,t:o,z:s})}return n?ei([Xr(e[n.i],e[(n.i+1)%e.length],n.t),...e.slice(n.i+1),...e.slice(0,n.i+1)]):e}function oi(e,t){let n=e.length,r=[0,1].map(t=>Math.max(1e-9,ri(e,t)[1]-ri(e,t)[0])),i=e.map((t,i)=>Math.hypot((e[(i+1)%n][0]-t[0])/r[0],(e[(i+1)%n][1]-t[1])/r[1])),a=i.reduce((e,t)=>e+t,0),o=[],s=0,c=0;for(let r=0;r<t;r+=1){let l=r/t*a;for(;s<n-1&&c+i[s]<l;)c+=i[s++];o.push(Xr(e[s],e[(s+1)%n],i[s]>0?Math.min(1,(l-c)/i[s]):0))}let l=new Set;return c=0,e.forEach((r,s)=>{let u=e[(s-1+n)%n],d=e[(s+1)%n],f=((r[0]-u[0])*(d[0]-r[0])+(r[1]-u[1])*(d[1]-r[1]))/(Zr(u,r)*Zr(r,d)),p=Math.round(c/a*t)%t;f<Yr&&!l.has(p)&&(l.add(p),o[p]=r),c+=i[s]}),o}function si(e,t){let n=e.points??ti(e),r=ei(e.points&&t?ii(ni(n),n):n);return Qr(r)>0&&(r=r.slice().reverse()),oi(ai(r),Gr)}function ci(e,t){let n=e.length,r=t.slice(1).map((n,r)=>(n-t[r])/(e[r+1]-e[r])),i=t.map((e,t)=>t===0?r[0]:t===n-1?r[n-2]:r[t-1]*r[t]<=0?0:(r[t-1]+r[t])/2);return r.forEach((e,t)=>{if(e===0){i[t]=0,i[t+1]=0;return}let n=i[t]/e,r=i[t+1]/e,a=n*n+r*r;a>9&&(i[t]=3*n*e/Math.sqrt(a),i[t+1]=3*r*e/Math.sqrt(a))}),i}function li(e,t,n,r,i,a,o){let s=t-e,c=(o-e)/s,l=c*c,u=l*c;return(2*u-3*l+1)*n+(u-2*l+c)*s*i+(-2*u+3*l)*r+(u-l)*s*a}function ui(e){let[t,n,r]=e.size,i=e.sections.map(e=>e.y),a=e.sections.map(t=>si(t,e.smooth)),o=[],s=[];if(!e.smooth)a.forEach((e,t)=>{s.push(o.length),o.push({y:i[t],ring:e})});else{let e=a[0].map((e,t)=>[0,1].map(e=>ci(i,a.map(n=>n[t][e]))));for(let t=0;t<i.length&&(s.push(o.length),o.push({y:i[t],ring:a[t]}),t!==i.length-1);t+=1)for(let n=1;n<Kr;n+=1){let r=i[t]+(i[t+1]-i[t])*n/Kr;o.push({y:r,ring:a[t].map((n,o)=>[0,1].map(n=>li(i[t],i[t+1],a[t][o][n],a[t+1][o][n],e[o][n][t],e[o][n][t+1],r)))})}}return{rings:o.map(({y:e,ring:i})=>i.map(([i,a])=>[i*t,(e-.5)*n,a*r])),at:s}}var di=[2,12],fi=[3,24],pi=[4,48],mi=[6,40],hi=16,gi=.25,_i=.02,vi=2147483647;function yi(e,t,n,r){if(!Ir(e)||e<n||e>r)throw new B(t,`must be a number from ${n} to ${r}, got ${JSON.stringify(e)}`);return Fr(e)}function bi(e,t,n){if(e===void 0)return n;if(typeof e!=`boolean`)throw new B(t,`must be true or false`);return e}function xi(e,t,[n,r],i){if(!Array.isArray(e)||e.length<n||e.length>r)throw new B(t,`must be ${n}-${r} ${i}, got ${Array.isArray(e)?e.length:JSON.stringify(e)}`);return e}function Si(e,t,n){if(!Array.isArray(e)||e.length!==n.length||!e.every(Ir))throw new B(t,`must be [${n.join(`, `)}] fractions of size, got ${JSON.stringify(e)}`);return e.map((e,n)=>yi(e,`${t}[${n}]`,-.5,.5))}var Ci=(e,t,n)=>(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);function wi(e){let t=e.length;for(let n=0;n<t;n+=1)for(let r=n+2;r<t;r+=1){if(n===0&&r===t-1)continue;let[i,a,o,s]=[e[n],e[(n+1)%t],e[r],e[(r+1)%t]];if(Ci(i,a,o)*Ci(i,a,s)<0&&Ci(o,s,i)*Ci(o,s,a)<0)return[n,r]}return null}function Ti(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new B(t,`must be { y, points } or { y, w, d }`);let n=e.points!==void 0,r=n?[`y`,`points`]:[`y`,`w`,`d`,`x`,`z`,`roundness`];for(let n of Object.keys(e))if(!r.includes(n))throw new B(`${t}.${n}`,`unknown key (a section is { y, points } or { y, w, d, x, z, roundness })`);let i=yi(e.y,`${t}.y`,0,1);if(n){let n=xi(e.points,`${t}.points`,fi,`[x, z] points`).map((e,n)=>Si(e,`${t}.points[${n}]`,[`x`,`z`])),r=wi(n);if(r)throw new B(`${t}.points`,`edges ${r[0]} and ${r[1]} cross; list the outline in order around the section`);if(Math.abs(Qr(n))<1e-6)throw new B(`${t}.points`,`the outline encloses no area`);return{y:i,points:n}}let a={y:i,w:yi(e.w,`${t}.w`,.01,1),d:yi(e.d,`${t}.d`,.01,1)};for(let[n,r]of[[`x`,`w`],[`z`,`d`]])if(a[n]=Rr(e[n],`${t}.${n}`,0,-.5,.5),Math.abs(a[n])+a[r]/2>.5+1e-9)throw new B(`${t}.${n}`,`the section reaches past the part's side: |${n}| + ${r}/2 must be at most 0.5`);return a.roundness=Rr(e.roundness,`${t}.roundness`,gi,0,1),a}function Ei(e,t){let n=`${t}.sections`,r=xi(e,n,di,`sections`).map((e,t)=>Ti(e,`${n}[${t}]`));if(r.forEach((e,t)=>{if(t>0&&e.y<=r[t-1].y)throw new B(`${n}[${t}].y`,`must be above the section before it (sections run bottom to top)`)}),r[0].y!==0||r.at(-1).y!==1)throw new B(n,`the first section must sit at y 0 and the last at y 1 (size[1] is the loft's full height)`);return r}function Di(e){let t=(e,t)=>e.map((e,n)=>e-t[n]),n=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],r=e=>Math.hypot(...e),i=t=>Math.max(...e.map(e=>e[t]))-Math.min(...e.map(e=>e[t])),a=[1,2].reduce((e,t)=>i(t)>i(e)?t:e,0),o=e.reduce((e,t)=>t[a]<e[a]?t:e),s=t(e.reduce((e,t)=>t[a]>e[a]?t:e),o),c=e=>r(n(s,t(e,o)))/(r(s)||1),l=e.reduce((e,t)=>c(t)>c(e)?t:e),u=n(s,t(l,o));return Math.min(r(s),c(l),Math.max(...e.map(e=>Math.abs(t(e,o).reduce((e,t,n)=>e+t*u[n],0))/(r(u)||1))))}function Oi(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let e=Math.imul(t^t>>>15,t|1);return e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function ki(e,t){let n=Oi(e),r=Math.floor(t/2)+2,i=Math.acos(1-2*n()),a=2*Math.PI*n(),o=Math.PI*(3-Math.sqrt(5)),s=[];for(let e=0;e<r;e+=1){let t=Math.max(-1,Math.min(1,1-2*(e+.5)/r+(n()-.5)/r)),c=e*o+(n()-.5)*o*.5,l=Math.sqrt(1-t*t),u=.88+.12*n(),[d,f,p]=[Math.cos(c)*l,t,Math.sin(c)*l],[m,h]=[f*Math.cos(i)-p*Math.sin(i),f*Math.sin(i)+p*Math.cos(i)];s.push([(d*Math.cos(a)+h*Math.sin(a))*u,m*u,(h*Math.cos(a)-d*Math.sin(a))*u])}let c=[0,1,2].map(e=>[Math.min(...s.map(t=>t[e])),Math.max(...s.map(t=>t[e]))]);return s.map(e=>e.map((e,t)=>Fr((e-(c[t][0]+c[t][1])/2)/(c[t][1]-c[t][0]))))}var Ai=e=>e.points??ki(e.seed,e.facetCount);function ji(e){return Ai(e).map(t=>t.map((t,n)=>t*e.size[n]))}var Mi=Object.freeze({loft:{keys:[`sections`,`smooth`],read(e,t,n){t.sections=Ei(e.sections,n),t.smooth=bi(e.smooth,`${n}.smooth`,!0)},mirror(e){e.sections=e.sections.map(e=>e.points?{y:e.y,points:e.points.map(([e,t])=>[Fr(-e),t]).reverse()}:{...e,x:Fr(-e.x)})},samples(e){let{rings:t,at:n}=ui(e);return n.slice(1).map((e,r)=>t.slice(n[r],e+1).flat())}},convex:{keys:[`points`,`seed`,`facetCount`,`facets`],read(e,t,n){let r=t=>e[t]!==void 0&&e[t]!==null;if(r(`points`)===r(`seed`))throw new B(`${n}.points`,`give either points: [[x, y, z]...] or seed (a random rock), not both`);if(r(`points`)){if(r(`facetCount`)&&e.seed!==null)throw new B(`${n}.facetCount`,`applies to a seeded rock; points already set the facets`);if(t.points=xi(e.points,`${n}.points`,pi,`[x, y, z] points`).map((e,t)=>Si(e,`${n}.points[${t}]`,[`x`,`y`,`z`])),Di(t.points)<_i)throw new B(`${n}.points`,`the points lie (nearly) on one line or plane; a hull needs depth in all three directions`)}else{if(!Number.isInteger(e.seed)||e.seed<0||e.seed>vi)throw new B(`${n}.seed`,`must be a whole number from 0 to ${vi}, got ${JSON.stringify(e.seed)}`);t.seed=e.seed;let i=r(`facetCount`)?e.facetCount:hi;if(!Number.isInteger(i)||i<mi[0]||i>mi[1])throw new B(`${n}.facetCount`,`must be a whole number from ${mi[0]} to ${mi[1]}, got ${JSON.stringify(e.facetCount)}`);t.facetCount=i}t.facets=bi(e.facets,`${n}.facets`,!0)},mirror(e){e.points=Ai(e).map(([e,t,n])=>[Fr(-e),t,n]),delete e.seed,delete e.facetCount},samples:e=>[ji(e)]}}),Ni=1e-9;function Pi(e,t){return e===null?t:t===null?e:e*t<=0?0:2*e*t/(e+t)}function Fi(e,t,n=!1){let r=e.length,i=t=>e[n?(t+r)%r:t],a=e.map((e,t)=>e.map((e,a)=>Pi(n||t>0?e-i(t-1)[a]:null,n||t<r-1?i(t+1)[a]-e:null))),o=[];for(let e=0;e<(n?r:r-1);e+=1){let n=i(e),s=i(e+1),c=a[e],l=a[(e+1)%r];for(let e=0;e<t;e+=1){let r=e/t,i=r*r,a=i*r,u=2*a-3*i+1,d=a-2*i+r,f=3*i-2*a,p=a-i;o.push(n.map((e,t)=>u*e+d*c[t]+f*s[t]+p*l[t]))}}return n||o.push([...e[r-1]]),o}function Ii(e){let t=0;for(let n=0,r=e.length-1;n<e.length;r=n,n+=1)t+=e[r][0]*e[n][1]-e[n][0]*e[r][1];return t/2}var Li=(e,t,n)=>(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]),Ri=(e,t,n)=>{let r=Li(e,t,n);return Math.abs(r)<=Ni?0:Math.sign(r)},zi=(e,t,n)=>Math.min(e[0],t[0])-Ni<=n[0]&&n[0]<=Math.max(e[0],t[0])+Ni&&Math.min(e[1],t[1])-Ni<=n[1]&&n[1]<=Math.max(e[1],t[1])+Ni;function Bi(e,t,n,r){let i=Ri(e,t,n),a=Ri(e,t,r),o=Ri(n,r,e),s=Ri(n,r,t);return i!==a&&o!==s||i===0&&zi(e,t,n)||a===0&&zi(e,t,r)||o===0&&zi(n,r,e)||s===0&&zi(n,r,t)}function Vi(e){let t=e.flatMap((e,t)=>e.map((n,r)=>({loop:t,edge:r,n:e.length,a:n,b:e[(r+1)%e.length]})));for(let e=0;e<t.length;e+=1)for(let n=e+1;n<t.length;n+=1){let r=t[e],i=t[n],a=r.loop===i.loop&&(r.edge+1)%r.n===i.edge,o=r.loop===i.loop&&(i.edge+1)%i.n===r.edge,s;if(a||o){let[e,t,n]=a?[r.b,r.a,i.b]:[r.a,r.b,i.a];s=Ri(e,t,n)===0&&(t[0]-e[0])*(n[0]-e[0])+(t[1]-e[1])*(n[1]-e[1])>0}else s=Bi(r.a,r.b,i.a,i.b);if(s)return{a:{loop:r.loop,edge:r.edge},b:{loop:i.loop,edge:i.edge}}}return null}function Hi([e,t],n){let r=!1;for(let i=0,a=n.length-1;i<n.length;a=i,i+=1){let[o,s]=n[i],[c,l]=n[a];s>t!=l>t&&e<(c-o)*(t-s)/(l-s)+o&&(r=!r)}return r}function Ui(e){let t=e.map((e,t)=>t);Ii(e)<0&&t.reverse();let n=[];for(;t.length>3;){let r=e=>[t[(e+t.length-1)%t.length],t[e],t[(e+1)%t.length]],i=t.findIndex((n,i)=>{let[a,o,s]=r(i).map(t=>e[t]);return Li(a,o,s)<=Ni?!1:!t.some(t=>!r(i).includes(t)&&Li(a,o,e[t])>=0&&Li(o,s,e[t])>=0&&Li(s,a,e[t])>=0)});i<0&&(i=0),n.push(r(i)),t.splice(i,1)}return n.push(t),n}var Wi=.005,Gi=24,Ki=e=>e.size.map(e=>e/2);function qi(e,t,n){if(e===void 0)return n;if(typeof e!=`boolean`)throw new B(t,`must be true or false, got ${JSON.stringify(e)}`);return e}function Ji(e,t,n,[r,i],[a,o]){if(!Array.isArray(e)||e.length<r||e.length>i)throw new B(t,`must be a list of ${r}-${i} points ${n}, got ${Array.isArray(e)?`${e.length} points`:JSON.stringify(e)}`);let s=n.split(`,`).length;return e.map((e,r)=>{if(!Array.isArray(e)||e.length!==s||!e.every(Ir))throw new B(`${t}[${r}]`,`must be ${s} numbers ${n}, got ${JSON.stringify(e)}`);return e.forEach((e,n)=>{if(e<a||e>o)throw new B(`${t}[${r}][${n}]`,`must be from ${a} to ${o}, got ${e}`)}),e.map(Fr)})}function Yi(e,t,n){let r=Ji(e,t,`[x, y]`,n,[-.5,.5]);return r.forEach(([e,n],i)=>{let[a,o]=r[(i+r.length-1)%r.length];if(e===a&&n===o)throw new B(`${t}[${i}]`,i?`repeats the point before it`:`repeats the last point; the loop closes by itself`)}),r}function Xi(e,t){return(e.smooth?Fi(e.profile,t):e.profile).map(([t,n])=>[t,(n-.5)*e.size[1]])}function Zi(e){let[t,,n]=Ki(e),r=Xi(e,Math.ceil(24/(e.profile.length-1))).map(([e,r])=>Array.from({length:Gi},(i,a)=>{let o=a/Gi*2*Math.PI;return[e*t*Math.sin(o),r,e*n*Math.cos(o)]}));return r.slice(1).map((e,t)=>[...r[t],...e])}var Qi={keys:[`profile`,`smooth`],read(e,t,n){let r=Ji(e.profile,`${n}.profile`,`[r, y]`,[3,32],[0,1]);if(r.forEach(([,e],t)=>{if(t&&e<r[t-1][1])throw new B(`${n}.profile[${t}][1]`,`y must not go down the profile (${e} after ${r[t-1][1]}); list it from bottom (0) to top (1)`)}),r.at(-1)[1]===r[0][1])throw new B(`${n}.profile`,`must climb: the last y must be above the first`);if(r.every(([e])=>e===0))throw new B(`${n}.profile`,`has every r at 0, so nothing would be drawn`);t.profile=r,t.smooth=qi(e.smooth,`${n}.smooth`,!0)},samples:Zi},$i=e=>e.path.map(t=>t.map((t,n)=>t*(e.size[n]-e.thickness))),ea=(e,t)=>Fi($i(e),t,e.closed);function ta(e,t){let n=e.thickness/2;if(!e.taper)return t.map(()=>n);let r=[0];for(let e=1;e<t.length;e+=1)r.push(r[e-1]+Math.hypot(...t[e].map((n,r)=>n-t[e-1][r])));return r.map(t=>{let i=t/r.at(-1);return n*(1-Math.max(0,e.taper)*i-Math.max(0,-e.taper)*(1-i))})}var na=[];for(let e of[-1,0,1])for(let t of[-1,0,1])for(let n of[-1,0,1]){let r=Math.hypot(e,t,n);r&&na.push([e/r,t/r,n/r])}function ra(e){let t=ea(e,4),n=ta(e,t),r=e.closed?e.path.length:e.path.length-1;return Array.from({length:r},(e,r)=>{let i=[];for(let e=r*4;e<=(r+1)*4;e+=1){let r=e%t.length;for(let e of na)i.push(t[r].map((t,i)=>t+e[i]*n[r]))}return i})}var ia={keys:[`path`,`thickness`,`taper`,`closed`],read(e,t,n){t.path=Ji(e.path,`${n}.path`,`[x, y, z]`,[2,32],[-.5,.5]);let r=Math.min(...t.size);if(!Ir(e.thickness)||e.thickness<Wi||e.thickness>r)throw new B(`${n}.thickness`,`must be the tube's diameter in metres, from ${Wi} to the part's smallest size (${Fr(r)} m), got ${JSON.stringify(e.thickness)}`);if(t.thickness=Fr(e.thickness),t.taper=Rr(e.taper,`${n}.taper`,0,-1,1),t.closed=qi(e.closed,`${n}.closed`,!1),t.closed&&t.taper)throw new B(`${n}.taper`,`a closed tube cannot taper: its two ends meet`);if(t.closed&&t.path.length<3)throw new B(`${n}.path`,`a closed tube needs at least 3 points`);let i=$i(t);i.forEach((e,r)=>{if(!r&&!t.closed)return;let a=i[(r+i.length-1)%i.length];if(Math.hypot(...e.map((e,t)=>e-a[t]))<1e-6)throw new B(`${n}.path[${r}]`,r?`sits on the point before it once fitted to the size`:`repeats the last point; a closed path joins its ends by itself`)})},mirror(e){e.path=e.path.map(([e,t,n])=>[Fr(-e),t,n])},samples:ra};function aa(e){let[t,n,r]=e.size;return Ui(e.outline).map(i=>i.flatMap(i=>{let[a,o]=e.outline[i];return[[a*t,o*n,r/2],[a*t,o*n,-r/2]]}))}function oa(e){return e.holes?e.holes.reduce((e,t)=>Math.abs(Ii(t))>Math.abs(Ii(e))?t:e).map(([t,n])=>[t*e.size[0],n*e.size[1],0]):null}var sa=e=>e.map(([e,t])=>[Fr(-e),t]),ca=Object.freeze({lathe:Qi,tube:ia,extrude:{keys:[`outline`,`holes`,`roundness`],read(e,t,n){if(t.outline=Yi(e.outline,`${n}.outline`,[3,64]),e.holes!==void 0&&(!Array.isArray(e.holes)||e.holes.length>4))throw new B(`${n}.holes`,`must be a list of at most 4 hole outlines, got ${JSON.stringify(e.holes).slice(0,60)}`);let r=(e.holes??[]).map((e,t)=>Yi(e,`${n}.holes[${t}]`,[3,32])),i=[`${n}.outline`,...r.map((e,t)=>`${n}.holes[${t}]`)],a=Vi([t.outline,...r]);if(a){let{a:e,b:t}=a,n=e.loop===t.loop?`another of its edges`:`${i[t.loop]} (edge ${t.edge})`;throw new B(i[e.loop],`edge ${e.edge} (point ${e.edge} to the next) touches or crosses ${n}; an outline must not cross itself or its holes`)}[t.outline,...r].forEach((e,t)=>{if(Math.abs(Ii(e))<1e-5)throw new B(i[t],`encloses no area`)}),r.forEach((e,n)=>{if(!Hi(e[0],t.outline))throw new B(i[n+1],`must lie inside the outline`);if(r.some((t,r)=>r!==n&&Hi(e[0],t)))throw new B(i[n+1],`must not lie inside another hole`)}),r.length&&(t.holes=r),t.roundness=Rr(e.roundness,`${n}.roundness`,.1,0,1)},mirror(e){e.outline=sa(e.outline),e.holes&&=e.holes.map(sa)},samples:aa,hole:oa}}),la=Object.freeze([`blade`,`tuft`,`flower`,`leaf`,`pebble`,`twig`]),ua=[`ground`,`shell`],da=4e3;function fa(e){let[t,n,r]=e.size.map(e=>e/2),i=[];if(e.spread===`ground`){for(let e of[-t,t])for(let t of[-n,n])for(let n of[-r,r])i.push([e,t,n]);return[i]}for(let e=0;e<=16;e+=1){let a=e/16*Math.PI;for(let e=0;e<24;e+=1){let o=e/24*2*Math.PI;i.push([Math.sin(a)*Math.cos(o)*t,Math.cos(a)*n,Math.sin(a)*Math.sin(o)*r])}}return[i]}var pa={keys:[`item`,`count`,`seed`,`spread`],read(e,t,n){t.item=Vr(e.item,`${n}.item`,void 0,la),t.count=zr(e.count,`${n}.count`,void 0,1,da),t.seed=Br(e.seed,`${n}.seed`),t.spread=Vr(e.spread,`${n}.spread`,`ground`,ua)},samples:fa},ma=.6,ha=e=>e.size.map(e=>e/2);function ga(e){let t=[];for(let n=0;n<=16;n+=1){let r=-1+2*n/16;for(let n=0;n<24;n+=1)t.push(...e(r,n/24*2*Math.PI))}return t}function _a(e){let[t,n,r]=ha(e),i=2+6*e.roundness,a=e.taper;return[ga((e,o)=>{let s=a>0?1-a*ma*((e+1)/2):a<0?1+a*ma*((1-e)/2):1,c=Math.max(0,1-Math.abs(e)**i)**(1/i),l=Math.cos(o),u=Math.sin(o),d=(Math.abs(l)**i+Math.abs(u)**i)**(1/i);return[[l/d*t*c*s,e*n,u/d*r*c*s]]})]}function va(e){let[t,n,r]=ha(e),i=[];for(let e of[-t,t])for(let t of[-n,n])for(let n of[-r,r])i.push([e,t,n]);return[i]}function ya(e){let[t,n,r]=ha(e);return[ga((i,a)=>{let o=1-Math.max(0,e.taper)*((i+1)/2)-Math.max(0,-e.taper)*((1-i)/2);return[[Math.cos(a)*t*o,i*n,Math.sin(a)*r*o]]})]}function ba(e){let[t,n,r]=ha(e);return[ga((i,a)=>{let o=[[Math.cos(a)*t,Math.sin(a)*n,i*r]];return e.shape===`frame`&&o.push([Math.sign(Math.cos(a))*t,Math.sign(Math.sin(a))*n,i*r]),o})]}function xa(e){let t=e.shape===`frame`?e.border:e.size[2],n=e.size[0]/2-t,r=e.size[1]/2-t;if(n<=0||r<=0)return null;let i=-e.size[2]/2;return[[-n,-r,i],[n,-r,i],[n,r,i],[-n,r,i]]}var Sa=Object.freeze({blob:{keys:[`roundness`,`taper`],read(e,t,n){t.roundness=Rr(e.roundness,`${n}.roundness`,.5,0,1),t.taper=Rr(e.taper,`${n}.taper`,0,-1,1)},samples:_a},box:{keys:[`roundness`],read(e,t,n){t.roundness=Rr(e.roundness,`${n}.roundness`,.1,0,1)},samples:va},cylinder:{keys:[`taper`],read(e,t,n){t.taper=Rr(e.taper,`${n}.taper`,0,-1,1)},samples:ya},torus:{keys:[],read(e,t,n){if(t.size[2]>=Math.min(t.size[0],t.size[1]))throw new B(`${n}.size`,`a torus's tube (size[2]) must be thinner than its outer diameter`)},samples:ba,hole:xa},frame:{keys:[`border`],read(e,t,n){let r=Math.min(t.size[0],t.size[1])/2,i=e.border===void 0?Fr(Math.min(t.size[0],t.size[1])*.15):e.border;if(!Ir(i)||i<=0||i>=r)throw new B(`${n}.border`,`must be above 0 and below half the frame's smaller side (${Fr(r)} m), got ${JSON.stringify(e.border)}`);t.border=Fr(i)},samples:ba,hole:xa},...ca,...Mi,scatter:pa}),Ca=Object.freeze(Object.keys(Sa)),wa=Object.freeze([...new Set(Object.values(Sa).flatMap(e=>e.keys))]),Ta=[`subtract`,`intersect`],Ea=Object.freeze({key:`op`,read(e,t,n){if(!Ta.includes(e.op))throw new B(`${n}.op`,`must be "subtract" or "intersect", got ${JSON.stringify(e.op)}`);if(t.parent===void 0)throw new B(`${n}.op`,`a cutter needs a parent: the part it cuts`);t.op=e.op}});function Da(e){let t=new Map(e.map(e=>[e.id,e]));for(let n of e){let e=t.get(n.parent);if(n.op&&e?.shape===`scatter`)throw new B(`parts[${n.id}].op`,`"${e.id}" is a scatter, which is drawn as instances and cannot be cut`);if(e?.op)throw new B(`parts[${n.id}].parent`,n.op?`"${e.id}" is a cutter, and a cutter only cuts drawn parts; give this one parent "${e.parent}" so both cut it`:`"${e.id}" is a cutter (op), which is not drawn and cannot carry parts; use parent "${e.parent}" instead`)}}var Oa=.35,ka={fallback:4,min:1,max:12},Aa=[`y`,`x`,`z`];function ja(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))throw new B(t,`must be an object { ${n.join(`, `)} }, got ${JSON.stringify(e)}`);for(let r of Object.keys(e))if(!n.includes(r))throw new B(`${t}.${r}`,`unknown key (allowed: ${n.join(`, `)})`);return e}var Ma=[{key:`detail`,read(e,t,n){let r=`${n}.detail`;if(t.shape===`scatter`)throw new B(r,`does not apply to a scatter: its items are already small; lump the part under it instead`);let i=ja(e.detail,r,[`amount`,`scale`,`seed`]);if(i.amount===void 0)throw new B(`${r}.amount`,`is required: the bump height from 0 (smooth) to 1 (very lumpy)`);t.detail={amount:Rr(i.amount,`${r}.amount`,0,0,1),scale:Rr(i.scale,`${r}.scale`,ka.fallback,ka.min,ka.max),seed:Br(i.seed,`${r}.seed`)}}},{key:`gradient`,read(e,t,n){let r=`${n}.gradient`,i=ja(e.gradient,r,[`color`,`axis`,`from`,`to`]);if(i.color===void 0)throw new B(`${r}.color`,`is required: the #rrggbb colour the part blends into`);t.gradient={color:Wr(i.color,`${r}.color`),axis:Vr(i.axis,`${r}.axis`,`y`,Aa),from:Rr(i.from,`${r}.from`,0,0,1),to:Rr(i.to,`${r}.to`,1,0,1)}}}],Na=Object.freeze({clay:{roughness:.82},wood:{roughness:.68,color:`#9a6b3f`,pattern:`wood`,tile:.5,grain:`long`,contrast:.32,bump:.0015,roughVar:.1},straw:{roughness:.88,color:`#c8a85c`,pattern:`straw`,tile:.6,grain:`hang`,contrast:.5,bump:.02,roughVar:.08},stone:{roughness:.9,color:`#8d8a83`,pattern:`stone`,tile:1,contrast:.32,bump:.008,roughVar:.1},brick:{roughness:.88,color:`#a5503a`,pattern:`brick`,tile:.5,grain:`hang`,contrast:.22,bump:.008,roughVar:.08,mask:`#b9b3a8`},concrete:{roughness:.92,color:`#a7a49d`,pattern:`concrete`,tile:1.2,contrast:.2,bump:.0015,roughVar:.08},metal:{roughness:.32,metalness:1,color:`#c9ccd1`,env:1,pattern:`brushed`,tile:.4,contrast:.06,bump:1e-4,roughVar:.12},glass:{roughness:.04,color:`#f2f7f7`,env:1,physical:{transmission:1,ior:1.5}},ceramic:{roughness:.35,color:`#efece4`,env:.45,physical:{clearcoat:1,clearcoatRoughness:.06}},plastic:{roughness:.3,env:.35},rubber:{roughness:.92,color:`#2d2d2f`,pattern:`stipple`,tile:.15,contrast:.08,bump:3e-4,roughVar:.06},fabric:{roughness:.95,pattern:`weave`,tile:.12,contrast:.22,bump:8e-4,roughVar:.05,physical:{sheen:1,sheenRoughness:.6}},paper:{roughness:.88,color:`#ebe6da`,pattern:`paper`,tile:.25,contrast:.08,bump:2e-4},foliage:{roughness:.62,color:`#4f7d34`,pattern:`leaves`,tile:.6,contrast:.45,bump:.015,roughVar:.15,physical:{sheen:.8,sheenRoughness:.45}}}),Pa=Object.freeze(Object.keys(Na)),Fa=Object.freeze({matte:.85,satin:.45,gloss:.12}),Ia=Object.freeze(Object.keys(Fa));function La(e,t){let n=Na[t]?.color;return n&&(!e||e.toLowerCase()===`#c2c6c8`)?n:e??`#c2c6c8`}var Ra=new Set([`cube`,`sphere`,`capsule`,`cylinder`,`cone`,`plane`]),za=[[`material`,Pa],[`finish`,Ia]],Ba=e=>Ra.has(e)?za.map(([e])=>e):[];function Va(e,t){return Ra.has(t)?Object.fromEntries(za.filter(([t,n])=>n.includes(e?.[t])).map(([t])=>[t,e[t]])):{}}function Ha(e,t){if(!Ra.has(e?.renderer))return{};let n={};for(let[r,i]of za){let a=t?.[r];a===void 0||a!==null&&!i.includes(a)||(a??void 0)!==e[r]&&(n[r]=a)}return n}var Ua=(e,t)=>(n,r,i)=>{if(n[e]!==null){if(!t.includes(n[e]))throw new B(`${i}.${e}`,`must be one of ${t.join(`, `)}; got ${JSON.stringify(n[e])}`);r[e]=n[e]}},Wa=Object.freeze([{key:`material`,read:Ua(`material`,Pa)},{key:`finish`,read:Ua(`finish`,Ia)},...Ma,Ea]),Ga=1,Ka=Object.freeze({maxParts:48,minExtent:.005,maxExtent:20,maxOffset:20,maxDepth:8,maxScatterItems:12e3}),qa=`#c2c6c8`,Ja=`.mirror`,Ya=.05,Xa=/^[a-z0-9][a-z0-9-]{0,39}$/,Za=new Set([`id`,`shape`,`size`,`position`,`rotation`,`color`,`parent`,`mirror`,...wa,...Wa.map(e=>e.key)]),Qa=e=>{let t=((e+180)%360+360)%360-180;return t===-180?180:t},$a=(e,t)=>e===void 0?qa:Wr(e,t);function eo(e,t){let n=`parts[${t}]`;if(!e||typeof e!=`object`||Array.isArray(e))throw new B(n,`must be an object`);for(let t of Object.keys(e))if(!Za.has(t))throw new B(`${n}.${t}`,`unknown key (allowed: ${[...Za].join(`, `)})`);if(typeof e.id!=`string`||!Xa.test(e.id))throw new B(`${n}.id`,`must be 1-40 characters of a-z, 0-9 and -, starting with a letter or digit; got ${JSON.stringify(e.id)}`);let r=`parts[${e.id}]`;if(!Ca.includes(e.shape))throw new B(`${r}.shape`,`must be one of ${Ca.join(`, `)}; got ${JSON.stringify(e.shape)}`);let i=Sa[e.shape];for(let t of wa)if(e[t]!==void 0&&!i.keys.includes(t))throw new B(`${r}.${t}`,`does not apply to a ${e.shape}`);let a=Lr(e.size,`${r}.size`,null,(e,t)=>{if(e<Ka.minExtent||e>Ka.maxExtent)throw new B(t,`extent must be ${Ka.minExtent}-${Ka.maxExtent} m, got ${e}`)}),o=Lr(e.position,`${r}.position`,[0,0,0],(e,t)=>{if(Math.abs(e)>Ka.maxOffset)throw new B(t,`must be within ±${Ka.maxOffset} m, got ${e}`)}),s=Lr(e.rotation,`${r}.rotation`,[0,0,0],()=>{}).map(e=>Fr(Qa(e)));if(e.parent!==void 0&&(typeof e.parent!=`string`||!e.parent))throw new B(`${r}.parent`,`must be another part's id`);if(e.mirror!==void 0&&typeof e.mirror!=`boolean`)throw new B(`${r}.mirror`,`must be true or false`);let c={id:e.id,shape:e.shape,size:a,position:o,rotation:s,color:$a(e.color,`${r}.color`)};e.parent!==void 0&&(c.parent=e.parent),e.mirror===!0&&(c.mirror=!0),i.read(e,c,r);for(let t of Wa)e[t.key]!==void 0&&t.read(e,c,r);return c}function to(e){let t=new Map(e.map(e=>[e.id,e])),n=new Map,r=(e,i)=>{if(n.has(e.id))return n.get(e.id);if(!e.parent)return n.set(e.id,0),0;let a=t.get(e.parent);if(!a)throw new B(`parts[${e.id}].parent`,`no part named "${e.parent}"`);if(i.has(a.id))throw new B(`parts[${e.id}].parent`,`parents form a cycle`);let o=r(a,new Set([...i,e.id]))+1;if(o>Ka.maxDepth)throw new B(`parts[${e.id}].parent`,`parent chain is deeper than ${Ka.maxDepth}`);return n.set(e.id,o),o};for(let t of e)r(t,new Set([t.id]));for(let n of e)if(n.mirror){for(let e=t.get(n.parent);e;e=t.get(e.parent))if(e.mirror)throw new B(`parts[${n.id}].mirror`,`"${e.id}" above it is already mirrored, which copies this part too`)}return n}function no(e){try{if(!e||typeof e!=`object`||Array.isArray(e))throw new B(`recipe`,`must be an object with a parts array`);for(let t of Object.keys(e))if(t!==`version`&&t!==`parts`)throw new B(`recipe.${t}`,`unknown key (allowed: version, parts)`);if(e.version!==void 0&&e.version!==Ga)throw new B(`recipe.version`,`only version ${Ga} is understood, got ${JSON.stringify(e.version)}`);if(!Array.isArray(e.parts)||e.parts.length===0)throw new B(`recipe.parts`,`must be a non-empty array`);let t=e.parts.map(eo),n=new Set;for(let e of t){if(n.has(e.id))throw new B(`parts[${e.id}].id`,`is used twice`);n.add(e.id)}to(t),Da(t);let r={version:Ga,parts:t},i=lo(r);if(i.length>Ka.maxParts)throw new B(`recipe.parts`,`expands to ${i.length} parts with mirrors; the limit is ${Ka.maxParts}`);let a=i.reduce((e,t)=>e+(t.shape===`scatter`?t.count:0),0);if(a>Ka.maxScatterItems)throw new B(`recipe.parts`,`scatter parts draw ${a} items with mirrors; the limit is ${Ka.maxScatterItems}`);return{ok:!0,recipe:r}}catch(e){if(e instanceof B)return{ok:!1,error:e.message,path:e.path};throw e}}function ro(e,t){let n=no(e);if(!n.ok)return n;if(!Array.isArray(t)||t.length===0)return{ok:!1,error:`edits: must be a non-empty array`,path:`edits`};let r=n.recipe.parts.map(e=>({...e})),i=new Set;for(let[e,n]of t.entries()){let t=`edits[${e}]`,a=n&&typeof n==`object`?[`set`,`add`,`remove`].filter(e=>e in n):[];if(a.length!==1)return{ok:!1,error:`${t}: must have exactly one of set, add, remove`,path:t};if(a[0]===`add`){r.push(n.add),i.add(n.add?.id);continue}let o=n[a[0]],s=r.findIndex(e=>e.id===o);if(s<0)return{ok:!1,error:`${t}.${a[0]}: no part named ${JSON.stringify(o)}`,path:`${t}.${a[0]}`};if(a[0]===`remove`){let e=new Set([o]);for(let t=!0;t;){t=!1;for(let n of r)n.parent&&e.has(n.parent)&&!e.has(n.id)&&(e.add(n.id),t=!0)}for(let t=r.length-1;t>=0;--t)e.has(r[t].id)&&r.splice(t,1);e.forEach(e=>i.add(e));continue}let{set:c,...l}=n;if(`id`in l)return{ok:!1,error:`${t}.id: rename by remove + add`,path:`${t}.id`};let u={...r[s],...l};l.parent===null&&delete u.parent,l.mirror===!1&&delete u.mirror;for(let e of Wa)l[e.key]===null&&delete u[e.key];if(`shape`in l)for(let e of wa)e in l||delete u[e];r[s]=u,i.add(o)}let a=no({version:Ga,parts:r});return a.ok?{...a,changed:[...i]}:a}var io=Math.PI/180;function ao(e,t){let[n,r,i]=t.map(e=>e*io),a=Math.cos(n),o=Math.sin(n),s=Math.cos(r),c=Math.sin(r),l=Math.cos(i),u=Math.sin(i),d=a*l,f=a*u,p=o*l,m=o*u;return[s*l,f+p*c,m-d*c,0,-s*u,d-m*c,p+f*c,0,c,-o*s,a*s,0,e[0],e[1],e[2],1]}function oo(e,t){let n=Array(16);for(let r=0;r<4;r+=1)for(let i=0;i<4;i+=1){let a=0;for(let n=0;n<4;n+=1)a+=e[n*4+i]*t[r*4+n];n[r*4+i]=a}return n}function so(e,[t,n,r]){return[e[0]*t+e[4]*n+e[8]*r+e[12],e[1]*t+e[5]*n+e[9]*r+e[13],e[2]*t+e[6]*n+e[10]*r+e[14]]}function co(e,t){let n={...e,id:`${e.id}${Ja}`,position:[Fr(-e.position[0]),e.position[1],e.position[2]],rotation:[e.rotation[0],Fr(-e.rotation[1]),Fr(-e.rotation[2])]};return delete n.mirror,Sa[n.shape].mirror?.(n),t!==void 0&&(n.parent=t),n}function lo(e){let t=e.parts,n=new Map;for(let e of t){let t=e.parent??``;n.has(t)||n.set(t,[]),n.get(t).push(e)}let r=[],i=(e,t,a,o)=>{let s=o?co(e,a):a===void 0?{...e}:{...e,parent:a},c=oo(t,ao(s.position,s.rotation));r.push({...s,matrix:c});for(let t of n.get(e.id)??[])i(t,c,s.id,o);if(e.mirror&&!o){let o=co(e,a),s=oo(t,ao(o.position,o.rotation));r.push({...o,matrix:s});for(let t of n.get(e.id)??[])i(t,s,o.id,!0)}},a=ao([0,0,0],[0,0,0]);for(let e of n.get(``)??[])i(e,a,void 0,!1);return r}function uo(e){let[t,n,r]=e.size.map(e=>e/2),i=[];for(let e of[-t,t])for(let t of[-n,n])for(let n of[-r,r])i.push([e,t,n]);return i}function fo(e){let t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let r of lo(e).filter(e=>!e.op))for(let e of uo(r)){let i=so(r.matrix,e);for(let e=0;e<3;e+=1)t[e]=Math.min(t[e],i[e]),n[e]=Math.max(n[e],i[e])}return{min:t.map(Fr),max:n.map(Fr)}}function po(e){let{min:t,max:n}=fo(e);return{footprint:{width:Fr(Math.max(Ka.minExtent,2*Math.max(Math.abs(t[0]),Math.abs(n[0])))),depth:Fr(Math.max(Ka.minExtent,2*Math.max(Math.abs(t[2]),Math.abs(n[2]))))},height:Fr(Math.max(Ya,n[1]))}}function mo(e){return{width:(e.footprint?.width??1)*(e.scaleX??1),height:(e.height??1)*(e.scaleY??1),depth:(e.footprint?.depth??1)*(e.scaleZ??1)}}var V=(e,t)=>[e[0]+t[0],e[1]+t[1],e[2]+t[2]],H=(e,t)=>[e[0]-t[0],e[1]-t[1],e[2]-t[2]],U=(e,t)=>[e[0]*t,e[1]*t,e[2]*t],W=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],ho=(e,t)=>[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]],G=e=>Math.hypot(e[0],e[1],e[2]),go=(e,t)=>G(H(e,t));function K(e){let t=G(e);return t>1e-12?[e[0]/t,e[1]/t,e[2]/t]:[0,0,0]}var _o=(e,t,n)=>Math.min(n,Math.max(t,e)),vo=e=>e*Math.PI/180,yo=e=>e*180/Math.PI,bo=()=>[[1,0,0],[0,1,0],[0,0,1]];function q(e,t){let n=[[0,0,0],[0,0,0],[0,0,0]];for(let r=0;r<3;r++)for(let i=0;i<3;i++)n[r][i]=e[r][0]*t[0][i]+e[r][1]*t[1][i]+e[r][2]*t[2][i];return n}var J=(e,t)=>[e[0][0]*t[0]+e[0][1]*t[1]+e[0][2]*t[2],e[1][0]*t[0]+e[1][1]*t[1]+e[1][2]*t[2],e[2][0]*t[0]+e[2][1]*t[1]+e[2][2]*t[2]],Y=e=>[[e[0][0],e[1][0],e[2][0]],[e[0][1],e[1][1],e[2][1]],[e[0][2],e[1][2],e[2][2]]],xo=(e,t,n)=>[[e[0],t[0],n[0]],[e[1],t[1],n[1]],[e[2],t[2],n[2]]];function So(e){let t=vo(e),n=Math.cos(t),r=Math.sin(t);return[[1,0,0],[0,n,-r],[0,r,n]]}function X(e){let t=vo(e),n=Math.cos(t),r=Math.sin(t);return[[n,0,r],[0,1,0],[-r,0,n]]}function Co(e){let t=vo(e),n=Math.cos(t),r=Math.sin(t);return[[n,-r,0],[r,n,0],[0,0,1]]}function wo(e,t){let[n,r,i]=K(e),a=vo(t),o=Math.cos(a),s=Math.sin(a),c=1-o;return[[o+n*n*c,n*r*c-i*s,n*i*c+r*s],[r*n*c+i*s,o+r*r*c,r*i*c-n*s],[i*n*c-r*s,i*r*c+n*s,o+i*i*c]]}function To(e,t){let n=K(e),r=H(t,U(n,W(t,n)));return G(r)<1e-9&&(r=H([0,1,0],U(n,n[1])),G(r)<1e-9&&(r=H([1,0,0],U(n,n[0])))),r=K(r),xo(n,r,ho(n,r))}var Eo=(e,t,n,r)=>q(To(n,r),Y(To(e,t)));function Do(e){let t=e[0][0],n=e[1][1],r=e[2][2],i=t+n+r,a,o,s,c;if(i>0){let t=.5/Math.sqrt(i+1);c=.25/t,a=(e[2][1]-e[1][2])*t,o=(e[0][2]-e[2][0])*t,s=(e[1][0]-e[0][1])*t}else if(t>n&&t>r){let i=2*Math.sqrt(1+t-n-r);c=(e[2][1]-e[1][2])/i,a=.25*i,o=(e[0][1]+e[1][0])/i,s=(e[0][2]+e[2][0])/i}else if(n>r){let i=2*Math.sqrt(1+n-t-r);c=(e[0][2]-e[2][0])/i,a=(e[0][1]+e[1][0])/i,o=.25*i,s=(e[1][2]+e[2][1])/i}else{let i=2*Math.sqrt(1+r-t-n);c=(e[1][0]-e[0][1])/i,a=(e[0][2]+e[2][0])/i,o=(e[1][2]+e[2][1])/i,s=.25*i}let l=Math.hypot(a,o,s,c);return[a/l,o/l,s/l,c/l]}function Oo([e,t,n,r]){return[[1-2*(t*t+n*n),2*(e*t-n*r),2*(e*n+t*r)],[2*(e*t+n*r),1-2*(e*e+n*n),2*(t*n-e*r)],[2*(e*n-t*r),2*(t*n+e*r),1-2*(e*e+t*t)]]}var ko=(e,t)=>yo(Math.acos(_o(W(K(e),K(t)),-1,1))),Ao=.01;function jo(e){let t=e.bones,n=t.map(e=>e.name),r=Object.fromEntries(n.map((e,t)=>[e,t])),i=t.map(e=>e.parent),a=n.map(()=>[]);i.forEach((e,t)=>{e>=0&&a[e].push(t)});let o=n.map((e,t)=>{let n=[],r=[t];for(;r.length;){let e=r.shift();n.push(e),r.unshift(...a[e])}return n}),s=t.map(e=>e.localPos.map(e=>e*Ao)),c=t.map(e=>Oo(e.localQuat)),l=t.map(e=>e.worldPos.map(e=>e*Ao)),u=t.map(e=>Oo(e.worldQuat)),d=e.landmarks,f=r.Head,p=e=>J(Y(u[f]),H(e.map(e=>e*Ao),l[f])),m={mouth:p(d.mouth),headCentre:p(d.headEllipsoid.centre),headRadii:d.headEllipsoid.radii.map(e=>e*Ao),sole:{ball:(d.sole?.ball??0)*Ao,tip:(d.sole?.tip??0)*Ao}};return{model:e.model,names:n,index:r,parent:i,children:a,subtree:o,restLocalPos:s,restLocalRot:c,restWorldPos:l,restWorldRot:u,landmarks:m}}function Mo(e){return{P:e.restWorldPos.map(e=>e.slice()),R:e.restWorldRot.map(e=>e.map(e=>e.slice()))}}function No(e,t,n,r,i){for(let a of e.subtree[n])t.P[a]=V(r,J(i,H(t.P[a],r))),t.R[a]=q(i,t.R[a])}function Po(e,t){return{quats:e.names.map((n,r)=>{let i=e.parent[r];return Do(i<0?t.R[r]:q(Y(t.R[i]),t.R[r]))}),hips:t.P[e.index.Hips].slice()}}function Fo(e,t,n){let r=[],i=[];for(let a of e.subtree[e.index.Hips]){let o=e.parent[a],s=Oo(t[a]);if(o<0){i[a]=s,r[a]=n.slice();continue}i[a]=q(i[o],s),r[a]=V(r[o],J(i[o],e.restLocalPos[a]))}return{P:r,R:i}}var Io=(e,t,n)=>V(e.P[t],J(e.R[t],n)),Lo=(e,t,n,r)=>J(t.R[n],J(Y(e.restWorldRot[n]),r)),Ro=(e,t,n)=>Math.acos(_o((n*n-e*e-t*t)/(2*e*t),-1,1))*180/Math.PI,zo=(e,t,n)=>Math.sqrt(e*e+t*t+2*e*t*Math.cos(n*Math.PI/180));function Bo(e,t,n,r=145,i=150){let a=zo(e,t,r);if(n>=a)return n;let o=a-zo(e,t,i);return n>a-2*o?n+(a-n)*(a-n)/(4*o):a-o}function Vo(e,t,n,r,i,a=145,o=150){let s=zo(n,r,a),c=G(H(t,e));if(c>=s)return t;let l=Bo(n,r,c,a,o),u=U(i,zo(n,r,o)),d=V(e,u),f=H(t,d),p=G(f)>1e-9?K(f):U(i,-1),m=W(p,u);return V(d,U(p,-m+Math.sqrt(Math.max(0,m*m-W(u,u)+l*l))))}var Ho=(e,t)=>Lo(e,t,e.index.Spine2??e.index.Hips,[0,0,-1]),Uo=(e,t)=>Lo(e,t,e.index.Hips,[0,1,0]),Wo=(e,t,n)=>Ro(e,t,Bo(e,t,zo(e,t,n)));function Go(e,t,n,r,[i,a,o]=[`Arm`,`ForeArm`,`Hand`]){let s=t.P[e.index[`${n}${i}`]],c=t.P[e.index[`${n}${a}`]],l=t.P[e.index[`${n}${o}`]];return Ro(G(H(c,s)),G(H(l,c)),G(H(r,s)))}function Ko(e,t,n){let r=e.index[`${n}Arm`],i=e.index[`${n}ForeArm`],a=H(t.P[i],t.P[r]),o=H(t.P[e.index[`${n}Hand`]],t.P[i]),s=Math.acos(_o(W(K(a),K(o)),-1,1))*180/Math.PI,c=ho(a,o);s>145&&G(c)>1e-12&&No(e,t,i,t.P[i].slice(),wo(c,Wo(G(a),G(o),s)-s))}var qo={elbow:[145,150,Ho],knee:[150,160,Uo]};function Jo(e,t,n,r,i,a,o,s,c=null){let l=t.P[n],u=t.P[r],d=t.P[i],f=G(H(u,l)),p=G(H(d,u)),m=qo[c],h=m?Vo(l,a,f,p,m[2](e,t),m[0],m[1]):a,g=h===a?0:G(H(h,a)),_=H(h,l),v=G(_),y=U(_,1/Math.max(v,1e-9)),b=_o(v,Math.abs(f-p)+1e-4,(f+p)*.9995),x=(f*f-p*p+b*b)/(2*b),S=Math.sqrt(Math.max(f*f-x*x,0)),C=K(H(o,U(y,W(o,y)))),w=V(l,V(U(y,x),U(C,S))),T=Lo(e,t,n,s);No(e,t,n,l.slice(),Eo(H(u,l),T,H(w,l),C));let E=Lo(e,t,r,s),D=V(l,U(y,b));return No(e,t,r,t.P[r].slice(),Eo(H(t.P[i],t.P[r]),E,H(D,t.P[r]),C)),g||v-b}function Yo(e,t,n,r,i,a=null){let o=e.index[`${n}Foot`],s=e.index[`${n}ToeBase`],c=H(e.restWorldPos[s],e.restWorldPos[o]),l=a?J(a.R,J(X(r-a.yaw),J(So(i),c))):J(X(r),J(So(i),c)),u=a?J(a.R,[0,1,0]):[0,1,0];No(e,t,o,t.P[o].slice(),Eo(H(t.P[s],t.P[o]),Lo(e,t,o,[0,1,0]),l,u));let d=e.index[`${n}Toe_End`];if(!a&&i>0&&d!==void 0){let n=H(t.P[d],t.P[s]),r=[n[0],0,n[2]];G(r)>1e-6&&No(e,t,s,t.P[s].slice(),Eo(n,[0,1,0],r,[0,1,0]))}}function Xo(e,t,n){let r=e.index[`${n}Hand`],i=e.index[`${n}HandMiddle1`],a=K(H(t.P[i],t.P[r])),o=H(t.P[e.index[`${n}HandIndex1`]],t.P[e.index[`${n}HandPinky1`]]);return o=K(H(o,U(a,W(o,a)))),{d:a,l:o,n:ho(a,o)}}function Zo(e,t,n,r){let i=e.index[`${n}Arm`],a=e.index[`${n}Hand`],o=wo(H(t.P[a],t.P[i]),r);No(e,t,i,t.P[i].slice(),o),No(e,t,a,t.P[a].slice(),Y(o))}function Qo(e,t,n,r,i){if(!r&&!i)return;let a=e.index[`${n}Hand`],o=e.index[`${n}ForeArm`],s=K(H(t.P[a],t.P[o])),{l:c}=Xo(e,t,n),l=K(H(c,U(s,W(c,s))));No(e,t,a,t.P[a].slice(),wo(l,_o(i,-70,70))),No(e,t,a,t.P[a].slice(),wo(s,_o(r,-85,85)))}var $o={relaxed:{Index:[12,18,10],Middle:[15,20,12],Ring:[18,22,12],Pinky:[20,24,14],Thumb:[15,10,8]},fist:{Index:[80,95,60],Middle:[85,95,60],Ring:[85,95,60],Pinky:[85,95,60],Thumb:[15,10,8]},grip:{Index:[55,60,35],Middle:[60,62,35],Ring:[62,62,35],Pinky:[65,62,35],Thumb:[15,10,8]},cigarette:{Index:[8,10,6],Middle:[10,12,8],Ring:[60,75,45],Pinky:[65,80,45],Thumb:[35,25,20]},point:{Index:[0,0,0],Middle:[80,95,60],Ring:[85,95,60],Pinky:[85,95,60],Thumb:[40,30,30]},spherical:{Index:[35,40,25],Middle:[38,42,25],Ring:[40,42,25],Pinky:[42,44,25],Thumb:[15,10,8]}},es={spherical:{Index:9,Middle:2,Ring:-5,Pinky:-12}};function ts(e){let t=Object.entries(e??{}).reduce((e,[t,n])=>e+(t===`relaxed`?0:n||0),0);return t>1?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,e===`relaxed`?n:(n||0)/t])):e}function ns(e,t,n){let r=$o.relaxed;return r[t][n]+Object.entries(ts(e)??{}).reduce((e,[i,a])=>e+(a||0)*(($o[i]?.[t]?.[n]??r[t][n])-r[t][n]),0)}var rs=(e,t)=>$o.fist[e][t];function is(e,t,n,r){let i=ts(r),a=n===`Left`?-1:1,o=(e,t)=>ns(i,e,t);for(let r of[`Index`,`Middle`,`Ring`,`Pinky`]){let a=Object.entries(i??{}).reduce((e,[t,n])=>e+(n||0)*(es[t]?.[r]??0),0),o=e.index[`${n}Hand${r}1`];a&&o!==void 0&&No(e,t,o,t.P[o].slice(),wo(Xo(e,t,n).n,a))}for(let r of[`Index`,`Middle`,`Ring`,`Pinky`,`Thumb`])for(let i=0;i<3;i++){let s=e.index[`${n}Hand${r}${i+1}`];if(s===void 0)continue;let{l:c,d:l}=Xo(e,t,n),u=r===`Thumb`&&i===0?l:c;No(e,t,s,t.P[s].slice(),wo(u,a*o(r,i)))}let s=[0,1,2,3].map(e=>Object.entries(i??{}).reduce((t,[n,r])=>t+(r||0)*(as[n]?.[e]??0),0));s.some(Boolean)&&os(e,t,n,s)}var as={fist:[-70,-5,5,80],grip:[-30,-30,30,10],spherical:[-40,-20,20,10]};function os(e,t,n,[r,i,a,o]){let s=n===`Left`?-1:1,c=t=>e.index[`${n}HandThumb${t}`];if(c(1)===void 0)return;let{d:l,n:u}=Xo(e,t,n);No(e,t,c(1),t.P[c(1)].slice(),wo(l,s*r)),No(e,t,c(1),t.P[c(1)].slice(),wo(u,i));for(let[n,r]of[[2,a],[3,o]]){let i=K(ho(K(H(t.P[c(n+1)],t.P[c(n)])),u));No(e,t,c(n),t.P[c(n)].slice(),wo(i,s*r))}}var ss=(e,t)=>[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]],cs=e=>[-e[0],-e[1],-e[2],e[3]],ls=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3];function us(e){let t=Math.hypot(e[0],e[1],e[2],e[3]);return t>1e-12?[e[0]/t,e[1]/t,e[2]/t,e[3]/t]:[0,0,0,1]}function ds(e){let t=e[3]<0?-1:1,n=e[0]*t,r=e[1]*t,i=e[2]*t,a=e[3]*t,o=Math.hypot(n,r,i);if(o<1e-12)return[2*n,2*r,2*i];let s=2*Math.atan2(o,a)/o;return[n*s,r*s,i*s]}function fs(e){let t=Math.hypot(e[0],e[1],e[2]);if(t<1e-12)return us([e[0]/2,e[1]/2,e[2]/2,1]);let n=Math.sin(t/2)/t;return[e[0]*n,e[1]*n,e[2]*n,Math.cos(t/2)]}var ps=(e,t)=>ss(ss(e,[t[0],t[1],t[2],0]),cs(e)).slice(0,3);function ms(e,t){let n=1+e[0]*t[0]+e[1]*t[1]+e[2]*t[2];if(n>1e-9)return us([e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0],n]);let r=Math.abs(e[0])<.9?[0,e[2],-e[1]]:[-e[2],0,e[0]],i=Math.hypot(...r);return[r[0]/i,r[1]/i,r[2]/i,0]}var hs=(e,t)=>{let n=t*Math.PI/360,r=Math.sin(n);return[e[0]*r,e[1]*r,e[2]*r,Math.cos(n)]},gs=(e,t,n)=>ss(e,fs(ds(ss(cs(e),t)).map(e=>e*n))),_s={"y-bot-tpose":new URL(`/assets/y-bot-tpose-body-Dy1VKChZ.json`,``+import.meta.url),"x-bot-tpose":new URL(`/assets/x-bot-tpose-body-BusyR3eg.json`,``+import.meta.url)},vs=new Map;function ys(e){let t=e.protocol===`file:`?globalThis.process?.getBuiltinModule?.(`node:fs`):null;if(t)return JSON.parse(t.readFileSync(e,`utf8`));let n=new XMLHttpRequest;if(n.open(`GET`,e.href,!1),n.send(),n.status!==200)throw Error(`motion body fit ${e.pathname}: HTTP ${n.status}`);return JSON.parse(n.responseText)}function bs(e){return vs.has(e)||vs.set(e,ys(_s[e])),vs.get(e)}function xs(){return Promise.all(Object.entries(_s).map(async([e,t])=>{if(vs.has(e))return;let n=await fetch(t);if(!n.ok)throw Error(`motion body fit ${t.pathname}: HTTP ${n.status}`);let r=await n.json();vs.has(e)||vs.set(e,r)}))}var Ss=.1,Cs=new Map;function ws(e){let t=typeof Buffer<`u`?Buffer.from(e,`base64`):Uint8Array.from(atob(e),e=>e.charCodeAt(0));return new Int8Array(t.buffer,t.byteOffset,t.byteLength)}function Ts(e,t){let n=new Set([t,e.parent[t],...e.children[t]]);return/^(Left|Right)Arm$/.test(e.names[t])&&n.add(e.parent[e.parent[t]]),/^(Left|Right)UpLeg$/.test(e.names[t])&&n.add(e.index.Spine),n}function Es(e){if(!_s[e.model])return null;if(Cs.has(e.model))return Cs.get(e.model);let t=bs(e.model),n=Object.entries(t.grids).map(([n,r])=>{let i=r.dims.map(e=>(e-1)*t.step/2),a=r.min.map((e,t)=>e+i[t]);return{b:e.index[n],min:r.min,dims:r.dims,data:ws(r.data),centre:a,reach:G(i)}}),r=Object.fromEntries(Object.entries(t.radii).map(([t,n])=>[e.index[t],n])),i={step:t.step,grids:n,radii:r,skip:new Map(Object.keys(r).map(t=>[+t,Ts(e,+t)]))};return Cs.set(e.model,i),i}function Ds(e,t,n){let[r,i,a]=t.dims,o=e.step,s=(n[0]-t.min[0])/o,c=(n[1]-t.min[1])/o,l=(n[2]-t.min[2])/o;if(s<0||c<0||l<0||s>r-1||c>i-1||l>a-1)return Ss;let u=Math.min(r-2,Math.floor(s)),d=Math.min(i-2,Math.floor(c)),f=Math.min(a-2,Math.floor(l)),p=s-u,m=c-d,h=l-f,g=(e,n,r)=>t.data[((u+e)*i+d+n)*a+f+r],_=g(0,0,0)*(1-p)+g(1,0,0)*p,v=g(0,0,1)*(1-p)+g(1,0,1)*p,y=g(0,1,0)*(1-p)+g(1,1,0)*p,b=g(0,1,1)*(1-p)+g(1,1,1)*p;return((_*(1-m)+y*m)*(1-h)+(v*(1-m)+b*m)*h)/1e3}var Os=new WeakMap;function ks(e,t){let n=Os.get(t);return n||(n=e.grids.map(e=>V(t.P[e.b],J(t.R[e.b],e.centre))),Os.set(t,n)),n}function As(e,t,n,r=null){let i=Ss,a=-1,o=ks(e,t);return e.grids.forEach((s,c)=>{if(r?.has(s.b)||G(H(n,o[c]))-s.reach>i)return;let l=Ds(e,s,J(Y(t.R[s.b]),H(n,t.P[s.b])));l<i&&(i=l,a=s.b)}),{d:i,bone:a}}function js(e,t,n,r=null,i=.01){let a=[0,1,2].map(a=>{let o=[0,0,0];return o[a]=i,As(e,t,V(n,o),r).d-As(e,t,H(n,o),r).d}),o=G(a);return o>1e-9?U(a,1/o):null}var Ms=e=>/^(Left|Right)Arm$/.test(e)?.5:/^(Left|Right)UpLeg$/.test(e)?.3:0,Ns=(e,t)=>/Hand$/.test(e.names[t])?e.index[e.names[t].replace(/Hand$/,`HandMiddle1`)]:e.children[t][0];function Ps(e,t,n,r){let i=e.radii[r],a=Ns(t,r);if(!i||a===void 0)return[];let o=n.P[r],s=H(n.P[a],o),c=Ms(t.names[r]);return i.filter(([e])=>e>=c).map(([e,t])=>({p:V(o,U(s,e)),r:t,t:e}))}var Fs=/^(Spine\d?|Neck|Head)$/,Is=(e,t)=>e.children[t].find(t=>Fs.test(e.names[t]))??Ns(e,t),Ls=.25;function Rs(e,t,n,r,i,a=null){let o=As(e,n,r,a);if(o.d>=i||o.bone<0)return r;let s=n.P[o.bone],c=Is(t,o.bone),l=H(c===void 0?s:n.P[c],s),u=H(r,V(s,U(l,W(l,l)>1e-9?_o(W(H(r,s),l)/W(l,l),0,1):0))),d=G(u)>1e-4?U(u,1/G(u)):js(e,n,r,a);if(!d)return r;let f=new Set(e.grids.map(e=>e.b).filter(e=>e!==o.bone)),p=t=>As(e,n,V(r,U(d,t)),f).d>=i,m=0,h=.02;for(;!p(h)&&h<Ls;)m=h,h=Math.min(Ls,h*2);for(let e=0;e<10;e++){let e=(m+h)/2;p(e)?h=e:m=e}return V(r,U(d,h))}var zs=.03;function Bs(e){let t=Es(e);return t&&{body:t,skip:new Set(e.names.map((e,t)=>/(Arm|ForeArm|Hand|Neck|Head.*)$/.test(e)?t:-1).filter(e=>e>=0))}}function Vs(e,t,n,r,i,a){let o=0,s=Ms(t.names[r]);for(let[t,c]of e.radii[r]??[]){if(t<s)continue;let{d:l,bone:u}=As(e,n,V(i,U(H(a,i),t)),e.skip.get(r));u>=0&&(o=Math.max(o,c-l))}return o}function Hs(e,t,n,r){let i={depth:0,p:null,into:-1};for(let a of Ps(e,t,n,r)){let{d:t,bone:o}=As(e,n,a.p,e.skip.get(r)),s=a.r-t;o>=0&&s>i.depth&&(i={depth:s,p:a.p,into:o,r:a.r})}return i}var Us={twist:[-85,85],flex:[-70,70],dev:[-35,20]},Ws={twist:[-50,50],flex:[-40,40],dev:[-25,15]},Gs=.5,Ks=[0,0,-1],qs=72,Js=.02,Ys=400,Xs=.5,Zs=100/(180/Math.PI),Qs=180/Math.PI,$s=70,ec=30,tc=2;function nc(e,t=8,n=400){let r=0;for(let i of[`twist`,`flex`,`dev`]){let a=e[i],o=a>=0?Ws[i][1]:-Ws[i][0],s=a>=0?Us[i][1]:-Us[i][0],c=Math.abs(a);r+=c<=o?(c/o)**2:1+t*((Math.min(c,s)-o)/Math.max(1e-6,s-o))**2+(c>s?n*((c-s)/s)**2:0)}return r}function rc(e,t){let n=K(H(t,e)),r=Math.acos(_o(-n[1],-1,1))*Qs;return tc*(Math.max(0,r-$s)/ec)**2}function ic(e,t,n,r){let i=Do(q(t,Y(e)));i[3]<0&&(i=i.map(e=>-e));let a=2*Math.atan2(W([i[0],i[1],i[2]],n),i[3]),o=fs(U(n,a)),s=ds(ss(i,cs(o))),c=J(Oo(o),r),l=K(H(c,U(n,W(c,n)))),u=ho(n,l);return{twist:a*Qs,flex:W(s,l)*Qs,dev:W(s,u)*Qs,axF:l,axD:u}}function ac(e,t=0){let n=0;for(let[r,[i,a]]of Object.entries(Us)){let o=(e[r]-(i+a)/2)/((a-i)/2),s=Math.max(0,Math.abs(o)-1+t);n+=o*o+Ys*s*s}return n}function oc(e,t,n,r,i,a,o,s=0,c=!1){let l=e.index,u=l[`${n}Arm`],d=l[`${n}ForeArm`],f=l[`${n}Hand`],p=t.P[u],m=G(H(t.P[d],p)),h=G(H(t.P[f],t.P[d])),g=H(Vo(p,i,m,h,Ho(e,t)),p),_=G(g),v=U(g,1/Math.max(_,1e-9)),y=_o(_,Math.abs(m-h)+1e-4,(m+h)*.9995),b=(m*m-h*h+y*y)/(2*y),x=Math.sqrt(Math.max(m*m-b*b,0)),S=e=>H(e,U(v,W(e,v))),C=K(G(S(a))>1e-6?S(a):ho(v,Math.abs(v[1])<.9?[0,1,0]:[1,0,0])),w=ho(v,C),T=V(p,U(v,y)),E=e.restWorldRot,D=J(Y(E[d]),H(e.restWorldPos[f],e.restWorldPos[d])),O=J(Y(E[d]),o),k=q(Y(E[d]),E[f]),ee=J(Y(t.R[f]),Xo(e,t,n).l),A=e=>{let t=V(U(C,Math.cos(e)),U(w,Math.sin(e))),n=H(T,V(p,V(U(v,b),U(t,x)))),i=q(Eo(D,O,n,t),k),a=ic(i,r,K(n),J(i,ee)),o=Math.abs(Math.atan2(Math.sin(e),Math.cos(e)))/Zs,l=V(p,V(U(v,b),U(t,x)));return{pv:t,need:a,elbow:l,cost:(c?nc(a)+rc(p,l):ac(a,s))+Xs*(1-Math.cos(e))+Ys*Math.max(0,o-1)**2}},te=e=>G(S(e))>1e-6?Math.atan2(W(e,w),W(e,C)):0;return{at:A,angleOf:te,softmin:()=>{let e=Array.from({length:qs},(e,t)=>A(2*Math.PI*t/qs)),t=Math.min(...e.map(e=>e.cost)),n=e.reduce((e,n)=>V(e,U(n.pv,Math.exp(-(n.cost-t)/Js))),[0,0,0]);return G(n)>.001?te(n):2*Math.PI*e.findIndex(e=>e.cost===t)/qs},miss:Math.max(0,_-y)}}function sc(e,t,n,r,i,a,o,{toward:s,w:c=1,margin:l=0,comfort:u=!1}={}){let d=oc(e,t,n,r,i,a,o,l,u),f=s?d.angleOf(s):d.softmin(),p=d.at(c*Math.atan2(Math.sin(f),Math.cos(f)));return{pole:p.pv,need:p.need,cost:p.cost,miss:d.miss,elbow:p.elbow}}var cc=3,lc=1,uc=.005,dc=.15,fc=4,pc=(e,[t,n])=>Math.min(n,Math.max(t,e));function mc(e,t,n,r,i,a){let o=U(H(t.P[r],t.P[i]),1/G(H(t.P[r],t.P[i]))),s=q(t.R[i],q(Y(e.restWorldRot[i]),e.restWorldRot[r])),{axF:c,axD:l,...u}=ic(s,a,o,J(q(s,Y(t.R[r])),Xo(e,t,n).l)),d=Object.fromEntries(Object.entries(u).map(([e,t])=>[e,pc(t,Us[e])])),f=q(q(wo(V(U(c,d.flex),U(l,d.dev)),Math.hypot(d.flex,d.dev)),wo(o,d.twist)),s);return No(e,t,i,t.P[i].slice(),wo(o,Gs*d.twist)),No(e,t,r,t.P[r].slice(),q(f,Y(t.R[r]))),u}function hc(e,t,n){let r=e.index,i=r[`${n}Arm`],a=H(t.P[r[`${n}ForeArm`]],U(V(t.P[i],t.P[r[`${n}Hand`]]),.5));return G(a)>uc?a:Lo(e,t,i,Ks)}function gc(e,t,n,r,i,a,o){let s=e.index[`${n}Hand`],c=q(Y(t.R[s]),i.R),l=J(Y(t.R[s]),H(i.pos,t.P[s])),u=Oo(gs(Do(t.R[s]),Do(q(r.R,Y(c))),a)),d=t.P[s].slice(),f=e=>H(r.pos,J(e,l));return{goal:u,plane:hc(e,t,n),wristAt:o===`wrist`?()=>d:o===`palm`?f:e=>V(d,U(H(f(e),d),a))}}function _c(e,t,n,r,i,a,o){let s=e.index,c=s[`${n}Arm`],l=s[`${n}ForeArm`],u=s[`${n}Hand`],{w:d}=r,{goal:f,plane:p,wristAt:m}=gc(e,t,n,r.palm,r.measure(t),d,r.pin),h=sc(e,t,n,f,m(f),p,i,{toward:r.pole,w:d,comfort:r.comfort}),g=0,_=0,v={twist:0,flex:0,dev:0};for(let r=0;r<cc;r++){let a=m(r?t.R[u]:f);_=Go(e,t,n,a),g=Jo(e,t,c,l,u,a,h.pole,i,`elbow`),v=mc(e,t,n,u,l,f)}a[`hold_${o}`]={w:d,miss:Math.max(0,g),...v,swivel:xc(t,c,l,u,p),..._>145?{fold:_}:{},...r.second?{second:r.second}:{}},a[`arm_miss_${o}`]*=1-d}function vc(e,t,n,r){let{goal:i,plane:a,wristAt:o}=gc(e,t,n,r.palm,r.measure(t),r.w);return oc(e,t,n,i,o(i),a,Ks,0,r.comfort)}function yc(e,t,n,r,i,{shoulder:a=!1}={}){let{goal:o,plane:s,wristAt:c}=gc(e,t,n,r,i,1),l=c(o),u=sc(e,t,n,o,l,s,Ks,{margin:dc}),d=e.index,f=t.P[d[`${n}Arm`]],p=G(H(t.P[d[`${n}ForeArm`]],f)),m=G(H(t.P[d[`${n}Hand`]],t.P[d[`${n}ForeArm`]])),h=Math.max(0,zo(p,m,145)-G(H(l,f))),g=a?sc(e,t,n,o,l,s,Ks,{comfort:!0}):u;return(a?nc(g.need)+rc(f,g.elbow)+bc(e,t,n,f,g.elbow,l):u.cost)+lc*((u.miss*100)**2+(h*100)**2)}function bc(e,t,n,r,i,a){let o=Es(e),s=e.index;return o?fc*(Math.max(Vs(o,e,t,s[`${n}Arm`],r,i),Vs(o,e,t,s[`${n}ForeArm`],i,a))*100)**2:0}function xc(e,t,n,r,i){let a=K(H(e.P[r],e.P[t])),o=e=>H(e,U(a,W(e,a)));return ko(o(H(e.P[n],e.P[t])),o(i))}var Sc=[[`torso_lo`,`Spine`,`Spine2`,.12],[`torso_hi`,`Spine2`,`Neck`,.105],[`hips`,`LeftUpLeg`,`RightUpLeg`,.095],[`neck`,`Neck`,`Head`,.055],...[`Left`,`Right`].flatMap(e=>{let t=e===`Left`?`l`:`r`;return[[`thigh_${t}`,`${e}UpLeg`,`${e}Leg`,.07],[`shin_${t}`,`${e}Leg`,`${e}Foot`,.05],[`uarm_${t}`,`${e}Arm`,`${e}ForeArm`,.042],[`farm_${t}`,`${e}ForeArm`,`${e}Hand`,.033],[`hand_${t}`,`${e}Hand`,`${e}HandMiddle3`,.022]]})],Cc=(e,t,n=9)=>Array.from({length:n},(r,i)=>V(e,U(H(t,e),i/(n-1))));function wc(e,t){let n=J(Y(t.R),H(e,t.pos)),r=[0,t.half[1],0],i=[Math.abs(n[0]-r[0])-t.half[0],Math.abs(n[1]-r[1])-t.half[1],Math.abs(n[2]-r[2])-t.half[2]];return G([Math.max(i[0],0),Math.max(i[1],0),Math.max(i[2],0)])+Math.min(Math.max(i[0],i[1],i[2]),0)}function Tc(e,t,n,r){let i=1/0,a=H(r,n),o=W(a,a);for(let r of Cc(e,t)){let e=o<1e-12?0:_o(W(H(r,n),a)/o,0,1);i=Math.min(i,G(H(r,V(n,U(a,e)))))}return i}function Ec(e,t,n){let r=Io(t,e.index.Head,e.landmarks.headCentre),i=t.R[e.index.Head],a=J(Y(i),H(n,r)),o=e.landmarks.headRadii;return(1-G([a[0]/o[0],a[1]/o[1],a[2]/o[2]]))*Math.min(...o)}var Dc=e=>Math.round(e.restWorldPos[e.index.LeftFoot][1]*1e3)/1e3,Oc=(e,t,n,r)=>r?Io(t,n,J(Y(e.restWorldRot[n]),[0,-r,0])):t.P[n];function kc(e,t,n){let r=e.index,i=e.restWorldPos,a=e.landmarks.sole??{},o=r[`${n}Foot`],s=r[`${n}ToeBase`],c=r[`${n}Toe_End`]??s,l=[i[o][0],.005,i[o][2]-.045];return{heel:Io(t,o,J(Y(e.restWorldRot[o]),H(l,i[o]))),ball:Oc(e,t,s,a.ball),tip:Oc(e,t,c,a.tip)}}function Ac(e,t){let n=J(Y(t.R),H(e,t.pos));n[1]-=t.half[1];let r=n.map((e,n)=>Math.abs(e)-t.half[n]),i;if(Math.max(...r)<0){let e=r.indexOf(Math.max(...r));i=[0,0,0],i[e]=Math.sign(n[e])||1}else i=n.map((e,t)=>r[t]>0?Math.sign(e)*r[t]:0);let a=G(i);return J(t.R,a>1e-12?U(i,1/a):[0,1,0])}var jc=.05;function Mc(e){let t=e?.half;if(!t)return{kind:`box`};if(e.renderer===`sphere`){let e=(t[0]+t[1]+t[2])/3;return Math.max(...t)-Math.min(...t)<=jc*e?{kind:`sphere`,r:e}:{kind:`box`}}return e.renderer===`cylinder`?{kind:`cylinder`,r:Math.min(t[0],t[2]),h:2*t[1]}:{kind:`box`}}var Nc=(e,t)=>{let n=J(Y(e.R),H(t,e.pos));return n[1]-=e.half[1],n},Pc=e=>V(e.pos,J(e.R,[0,e.half[1],0]));function Fc(e,t){let n=Mc(e);if(n.kind===`sphere`)return G(H(t,Pc(e)))-n.r;if(n.kind===`cylinder`){let r=Nc(e,t),i=Math.hypot(r[0],r[2])-n.r,a=Math.abs(r[1])-n.h/2;return Math.hypot(Math.max(i,0),Math.max(a,0))+Math.min(Math.max(i,a),0)}return wc(t,e)}function Ic(e,t){let n=Mc(e);if(n.kind===`sphere`){let n=H(t,Pc(e)),r=G(n);return r>1e-12?U(n,1/r):J(e.R,[0,1,0])}if(n.kind===`cylinder`){let r=Nc(e,t),i=Math.hypot(r[0],r[2]),a=i-n.r,o=Math.abs(r[1])-n.h/2,s=i>1e-12?[r[0]/i,0,r[2]/i]:[1,0,0],c=[0,Math.sign(r[1])||1,0],l;l=a<=0&&o<=0?a>o?s:c:V(U(s,Math.max(a,0)),U(c,Math.max(o,0)));let u=G(l);return J(e.R,u>1e-12?U(l,1/u):s)}return Ac(t,e)}function Lc(e,t){return H(t,U(Ic(e,t),Fc(e,t)))}function Rc(e,t,n,r){let i=-1/0;for(let a of Cc(t,n))i=Math.max(i,r-Fc(e,a));return i}var zc=e=>e.flatMap(e=>[`${e}_l`,`${e}_r`]),Bc=new Set([`root`,...zc([`foot`,`knee`,`hand`,`elbow`])]),Vc=new Set(zc([`knee`,`elbow`])),Hc=new Set([`yaw`,`pitch`,`roll`,`spine_yaw`,`spine_pitch`,`spine_roll`,`head_yaw`,`head_pitch`,`head_roll`,`arm_rest`,`arm_hang`,...zc([`fyaw`,`fpitch`,`armw`,`wtwist`,`wflex`,`aswing`,`abend`])]),Uc=new Set(zc([`fingers`])),Wc=new Set([`arm_hang`]),Gc=[`relaxed`,`fist`,`grip`,`cigarette`,`point`,`spherical`],Kc=[`power`,`pinch`,`hook`,`palm`,`spherical`],qc={power:`grip`,pinch:`cigarette`,hook:`grip`,palm:`relaxed`,spherical:`spherical`},Jc={power:[0,0,.02],hook:[0,0,.02],pinch:[.025,0,.01],palm:[-.045,0,.015],spherical:[-.015,0,.035]},Yc=[[/^(armw)_[lr]$/,0,1,`0 FK, 1 IK to the hand target`],[/^arm_hang$/,0,1,`1 = a free FK forearm hangs plumb`],[/^w_.+_[lr]$/,0,1,`hand-target weight; a hand's sum <= 1`],[/^wtwist_[lr]$/,-85,85,`twist about the forearm, deg`],[/^wflex_[lr]$/,-70,70,`flex about the knuckle line, deg`],[/^fpitch_[lr]$/,-60,90,`toe-down pitch, deg: + lifts the heel (toes flat), - lifts the toes`],[/^(spine_pitch|head_pitch)$/,-120,120,`deg, + bends forward`],[/^(spine_roll|head_roll)$/,-90,90,`degrees`]],Xc=e=>Yc.find(([t])=>t.test(e))??null,Zc={yaw:`yaw 0 faces +Z and + turns toward +X`,fyaw:`foot heading, as yaw`,pole:`body-frame direction (root yaw): +z forward, +x its left, +y up`,foot:`ANKLE target, world m (standing 0.087 X Bot, 0.105 Y Bot)`,hand:`WRIST target, world m`,root:`hips joint, world m (standing 1.03 X Bot, 0.99 Y Bot)`},Qc={root:Zc.root,yaw:`deg; ${Zc.yaw}`,pitch:`degrees`,roll:`degrees`,spine_yaw:`degrees`,spine_pitch:`deg, + bends forward`,spine_roll:`degrees`,head_yaw:`degrees`,head_pitch:`degrees, + looks down`,head_roll:`degrees`,arm_rest:`FK arms down, deg, default 72`,arm_hang:`1 = a free FK forearm hangs plumb (standIdle and walks key it)`,foot:Zc.foot,fyaw:Zc.fyaw,fpitch:`toe-down pitch, degrees, + heel up`,knee:`knee pole, ${Zc.pole}`,armw:`0 = FK arm, 1 = IK to hand_* / the anchors`,hand:Zc.hand,elbow:`elbow pole, ${Zc.pole}`,wtwist:`wrist twist, degrees`,wflex:`wrist flex, degrees`,aswing:`FK arm swing, deg, + forward`,abend:`FK elbow bend, deg`,fingers:`{ preset: weight 0..1 }`},$c=e=>e.replace(/_[lr]$/,``),el=[[[`frames`,`when`,`range`,`f`,`from`,`within`,`during`,`at`],[`when`,`frames`,`at`,`f`]],[[`max`,`maxDist`,`distance`,`tolerance`,`limit`],[`tol`,`min`]]];function tl(e,t){for(let[n,r]of el){let i=n.includes(e)&&r.find(n=>t.includes(n)&&n!==e);if(i)return`; did you mean "${i}"?`}return il(e,t,Math.max(2,Math.floor(e.length/3)))}var nl=e=>Array.isArray(e)&&e.length===3&&e.every(Number.isFinite),Z=e=>JSON.stringify(e)?.slice(0,60);function rl(e,t){let n=Array.from({length:e.length+1},(e,n)=>[n,...Array(t.length).fill(0)]);for(let e=1;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++)n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+(e[r-1]===t[i-1]?0:1));return n[e.length][t.length]}function il(e,t,n=Math.max(3,Math.floor(e.length/3))){let r=null,i=1/0;for(let n of t){let t=rl(e,n);t<i&&(r=n,i=t)}return r&&i<=n?`; did you mean "${r}"?`:``}var al=.022,ol=.012,sl=.04,cl=.15,ll=12,ul=(e,t,n,r)=>e?.fix!==!1&&e?.fix?.grasp!==!1&&!!t?.prop&&(t.grasp!==void 0||t.at===void 0&&t.along===void 0&&dl(n,r));function dl(e,t){let n=Object.entries(e?.objects??{}).filter(([e,n])=>e===t||n.ancestors?.includes(t));return n.length===1&&Mc(n[0][1]).kind!==`box`}var fl=new WeakMap;function pl(e,t,n,r,i,a){fl.has(n)||fl.set(n,new Map);let o=fl.get(n),s=`${r}|${i.prop}|${a.pos.map(e=>e.toFixed(6)).join(`,`)}`;if(o.has(s))return o.get(s);let c=t.props[i.prop],l=n_[c.hand],u=Mo(e),d=E_(e,t,u,{prop:i.prop},!0),f=e=>J(Y(d.R),H(e,d.pos)),p=t=>f(u.P[e.index[`${l}${t}`]]),m=[[p(`Hand`),p(`HandMiddle1`),al],[p(`HandIndex1`),p(`HandPinky1`),ol]],h=ml(n,r),g=Object.entries(n.objects).filter(([e,t])=>e===r||t.ancestors?.includes(r)),_=[0,1,0],v=e=>{let t={pos:V(a.pos,U(_,e)),R:a.R},n=-1/0;for(let[,e]of g){let r={...e,...D_(t,O_(h,e))};for(let[e,t,i]of m)n=Math.max(n,Rc(r,e,t,i))}return n},y=v(0),b=c.hand===`l`?1:-1,x=y>-.002,S=0,C=x?cl:sl,w=x?b:-b;if(x||v(w*C)>-.002)for(let e=0;e<ll;e++){let e=(S+C)/2;v(w*e)>-.002===x?S=e:C=e}else S=0;let T={pos:V(a.pos,U(_,w*(x?C:S))),R:a.R};return o.set(s,T),T}function ml(e,t){let n=e.objects[t];return n?{pos:n.pos,R:n.R}:Object.values(e.objects).find(e=>e.ancestors?.[0]===t)?.ancestorPoses?.[0]??{pos:[0,0,0],R:[[1,0,0],[0,1,0],[0,0,1]]}}function hl(e,t){let n=Math.min(1,Math.max(0,(t-e)/4));return n*n*(3-2*n)}var gl=(e,t,n)=>({pos:V(e.pos,U(H(t.pos,e.pos),n)),R:t.R}),_l=[`schema`,`fps`,`frames`,`label`,`keys`,`anchors`,`props`,`fits`,`objects`,`generators`,`checks`,`fix`,`use`,`channels`,`detourRadius`,`search`,`goals`,`flow`,`idle`],vl=[`f`,`set`,`step`,`src`],yl=[`skill`,`args`,`f0`],bl={world:[`p`],body:[`p`],bone:[`bone`,`offset`],segment:[`from`,`to`,`t`,`tMin`,`offset`,`reach`],object:[`object`,`local`,`socket`,`grasp`],landmark:[`name`],prop:[`prop`,`point`,`offset`],person:[`person`,`bone`,`offset`]},xl=[`hand`,`origin`,`points`],Sl=[`side`,`anchor`,`effector`,`offset`,`orient`],Cl={hinge:[`pivot`,`axis`,`channel`],carry:[`prop`,`at`,`along`,`visible`,`level`,`grab`,`release`,`keys`,`fall`,`grasp`,`mass`,`spring`],switch:[`visible`,`level`],follow:[`follow`,`offset`,`aim`,`visible`,`level`],free:[`keys`,`fall`,`visible`,`level`,`spring`]},wl=[`length`,`stiffness`,`damping`],Tl=[`at`,`onto`,`bounce`,`tumble`,`v`],El=[`f`,`pos`,`rot`,`aim`,`roll`,`lean`],Dl=[`type`,`f0`,`steps`,`step`,`period`,`swing`,`halfWidth`,`lift`,`heading`,`turnDistance`,`pelvisHigh`,`pelvisLow`,`firstStep`,`armSwing`,`vary`],Ol=[`contacts`,`orient`,`below`,`clearance`,`appear`,`supports`,`allow`,`limits`,`mouthPoints`],kl={contacts:[`name`,`point`,`target`,`tol`,`when`],orient:[`name`,`from`,`to`,`along`,`minCos`,`when`],below:[`name`,`joint`,`ref`,`min`,`when`],clearance:[`name`,`part`,`object`,`min`,`frames`],appear:[`name`,`channel`,`joint`,`anchor`,`tol`],supports:[`object`,`part`,`tol`],allow:[`part`,`object`,`depth`]},Al=[`name`,`near`,`above`,`moved`,`still`,`speed`,`tol`,`by`,`at`,`mode`,`after`,`before`],jl=[`name`,`distance`,`position`,`frames`,`every`],Ml=[`joint`,`bone`,`prop`,`anchor`,`landmark`,`object`,`person`],Nl=[`essentials`,`spec`,`skills`,`anchors`,`props`,`objects`,`checks`,`goals`,`probes`,`channels`,`refs`,`fix`,`examples`],Pl={pelvis:`Hips`,hip:`Hips`,hips:`Hips`,root:`Hips`,chest:`Spine2`,upperchest:`Spine2`,torso:`Spine1`,belly:`Spine`,abdomen:`Spine`,neck:`Neck`,head:`Head`},Fl={hand:`Hand`,wrist:`Hand`,foot:`Foot`,ankle:`Foot`,toe:`ToeBase`,toes:`ToeBase`,ball:`ToeBase`,arm:`Arm`,upperarm:`Arm`,forearm:`ForeArm`,lowerarm:`ForeArm`,elbow:`ForeArm`,shoulder:`Shoulder`,clavicle:`Shoulder`,thigh:`UpLeg`,upleg:`UpLeg`,upperleg:`UpLeg`,leg:`Leg`,lowerleg:`Leg`,shin:`Leg`,calf:`Leg`,knee:`Leg`},Il={l:`Left`,left:`Left`,r:`Right`,right:`Right`},Ll=e=>e.toLowerCase().replace(/[\s_.-]+/g,``);function Rl(e,t){let n=t.toLowerCase();return e.names.find(e=>e.toLowerCase()===n)??null}function zl(e,t){let n=Ll(t);if(Pl[n])return Rl(e,Pl[n]);let r=t.toLowerCase().trim(),i=/^(l|r|left|right)[\s_.-]+(.+)$/.exec(r)??/^(left|right)(.+)$/.exec(r),a=/^(.+?)[\s_.-]+(l|r|left|right)$/.exec(r)??/^(.+?)(left|right)$/.exec(r),[o,s]=i?[i[1],i[2]]:a?[a[2],a[1]]:[];return o?Rl(e,`${Il[o]}${Fl[Ll(s)]??Ll(s)}`):null}function Bl(e,t){if(typeof t!=`string`||!t)return{bone:null,hint:``};if(e.index[t]!==void 0)return{bone:t,hint:``};let n=t.replace(/^mixamorig\d*:/i,``),r=Rl(e,t)??Rl(e,n)??zl(e,n);return r?{bone:r,hint:``}:{bone:null,hint:il(n,e.names)}}function Vl(e,t,n,r){return!t||t.index[r]!==void 0||(e(`${n} names unknown bone "${r}"${il(String(r),t.names)}`),!1)}function Hl(e,t,n,r,{groups:i=!1}={}){let a=Object.keys(t?.objects??{});if(!a.length||a.includes(r))return!0;let o=sg(t,r);return o.length&&i?!0:(o.length?e(`${n} names "${r}", a group (Empty) with no body of its own; its parts are ${o.join(`, `)}. Name one part`):t?.others?.[r]?e(`${n} names "${r}", a ${t.others[r].renderer??`record`} with no body (no size to stand on, hold or hit); name a scene body${il(String(r),a)}`):e(`${n} names object "${r}", which is not in the scene${il(String(r),[...new Set([...a,...a.flatMap(e=>t.objects[e].ancestors??[]),...Object.keys(t.others??{})])])}`),!1)}function Ul(e,t,n,r,i){let[a,o]=String(i).split(/:(.*)/s);if(a===`joint`)return Vl(t,n,r,o);if(a===`anchor`)return e.anchors?.[o]?!0:t(`${r} "${i}" names no anchor`);if(a===`prop`){let[n,a]=(o??``).split(`.`);return e.props?.[n]?.points?.[a]||a===`origin`?!0:t(`${r} "${i}" names no prop point`)}t(`${r} "${i}" must be joint:<Bone>, prop:<prop>.<point> or anchor:<name>`)}var Wl=new Set([`empty`,`plane`,`cutout`]);function Gl(e,t){let n=[];for(let r=t.get(e.parent);r&&!n.includes(r)&&!r.attach;r=t.get(r.parent))n.push(r);return n}var Kl=e=>({pos:[e.x??0,e.y??0,e.z??0],R:q(So(e.rotX??0),q(X(e.rot??0),Co(e.rotZ??0)))}),ql=new WeakMap;function Jl(e){let t=e?.objects??{};if(ql.has(t))return ql.get(t);let n={};for(let[e,r]of Object.entries(t))(r.ancestors??[]).forEach((t,i)=>{let a=r.ancestorPoses?.[i];n[t]??={pos:a?.pos??[0,0,0],R:a?.R??[[1,0,0],[0,1,0],[0,0,1]],ancestors:r.ancestors.slice(i+1),children:[]};let o=i?r.ancestors[i-1]:e;n[t].children.includes(o)||n[t].children.push(o)});return ql.set(t,n),n}function Yl(e=[]){let t={},n={},r=new Map(e.filter(Boolean).map(e=>[e.id,e]));for(let i of e){if(!i||i.hidden)continue;let e=mo(i),a=Gl(i,r);if(Wl.has(i.renderer)||!(e.width>0&&e.height>0&&e.depth>0)){n[i.id]={renderer:i.renderer,ancestors:a.map(e=>e.id),...i.grasp?{grasp:i.grasp}:{}};continue}t[i.id]={name:i.name,renderer:i.renderer,...Kl(i),half:[e.width/2,e.height/2,e.depth/2],ancestors:a.map(e=>e.id),...a.length?{ancestorPoses:a.map(Kl)}:{},...i.glow?{glow:!0}:{},...i.grasp?{grasp:i.grasp}:{}}}return{objects:t,groups:Jl({objects:t}),others:n}}var Xl={"x-bot-tpose":{model:`x-bot-tpose`,units:`cm`,mesh:`Beta_Surface`,bones:[{name:`Hips`,parent:-1,localPos:[-7727290721959434e-21,104.27487182617188,1.5543158054351807],localQuat:[.006458545995471647,0,0,.9999791433743129],worldPos:[-7727290721959434e-21,104.27487182617188,1.5543158054351807],worldQuat:[.006458545995471649,0,0,.9999791433743129]},{name:`Spine`,parent:0,localPos:[-42558306661763523e-26,10.182436647133528,-383026943495679e-29],localQuat:[-.0801557216468605,0,-2.4806808368112424e-7,.9967823535191669],worldPos:[-7727716305026052e-21,114.45645899708516,1.6858405330789255],worldQuat:[-.07371628519129939,1.6021591284630476e-9,-2.4806290981795794e-7,.9972792534177845]},{name:`Spine1`,parent:1,localPos:[0,10.00267477114727,3552713678800501e-30],localQuat:[6162975822039155e-48,-49630836753181624e-40,5211237859084076e-38,1],worldPos:[-2780995758607294e-21,124.35042288428505,.21513282040928483],worldQuat:[-.07371628519129939,1.6021591284630476e-9,-2.480629098179579e-7,.9972792534177845]},{name:`Spine2`,parent:2,localPos:[113754220886636e-28,9.322090642186126,2.823681128916178e-7],localQuat:[.01288561985057818,-4771173867766652e-25,-3.7024045453006494e-8,.9999169769541195],worldPos:[18291488873430703e-22,133.57119939581565,-1.1555073459065734],worldQuat:[-.06085960369636199,-4.799512607436978e-9,-2.849511007796114e-7,.9981463362843349]},{name:`Neck`,parent:3,localPos:[41474883340816403e-26,16.865321474300316,55067062021407764e-30],localQuat:[-693889390390723e-32,-8271806125530272e-39,5190558343770245e-38,1],worldPos:[11433183430736414e-21,150.31158623305856,-3.204535645093104],worldQuat:[-.060859603696361994,-4.799512607436981e-9,-2.8495110077961134e-7,.9981463362843349]},{name:`Head`,parent:4,localPos:[-1.0756747747233872e-7,9.341923497302815,2.841040809958507],localQuat:[-693889390390723e-32,-36734198463196485e-56,-10339757656912817e-40,1],worldPos:[1671650538423477e-20,159.92947501239226,-1.5195243864816557],worldQuat:[-.060859603696362,-4.7995126074369775e-9,-2.849511007796113e-7,.9981463362843349]},{name:`HeadTop_End`,parent:5,localPos:[9.856974393531148e-7,20.962781993760927,10.122935199433357],localQuat:[9020562075079394e-32,-4963083675318166e-39,-3143286327701505e-38,1],worldPos:[298931534294587e-19,181.96684091859,5.981578858112073],worldQuat:[-.060859603696361904,-4.799512607437009e-9,-2.8495110077961134e-7,.9981463362843349]},{name:`RightShoulder`,parent:3,localPos:[-4.569970073784302,11.195844421252815,-.8066318609761822],localQuat:[-.48443063216376725,.5709636753028516,-.52616363833282,-.4030871739493107],worldPos:[-4.569961889633833,144.58610943784936,-3.316387285708532],worldQuat:[.45900076979447035,-.5378833301202727,.5599368183567869,.4318223893631366]},{name:`RightArm`,parent:7,localPos:[39968028886505635e-31,10.838175719528936,-2842170943040401e-29],localQuat:[-.024616241704842487,.002562291621043601,-.10349841681885355,.9943216547083585],worldPos:[-15.162807207946486,144.06130443716168,-5.548485110836629],worldQuat:[.4999999123070338,-.5000002750229358,.49999979787788545,.5000000147920203]},{name:`RightForeArm`,parent:8,localPos:[-9.964063352185804e-9,27.841518023440628,0],localQuat:[-17109853453384572e-39,-8816207631167156e-54,2938735877055719e-54,1],worldPos:[-43.004325231382126,144.06132057494256,-5.548489180140211],worldQuat:[.4999999123070338,-.5000002750229358,.49999979787788545,.5000000147920203]},{name:`RightHand`,parent:9,localPos:[2285859917883215e-20,28.328838348366197,4472538876143517e-21],localQuat:[6229948061854065e-38,2350988701644575e-53,-19852334701272682e-39,1],worldPos:[-71.33316357974921,144.0613325226415,-5.548470451934339],worldQuat:[.4999999123070338,-.5000002750229358,.49999979787788545,.5000000147920203]},{name:`RightHandMiddle1`,parent:10,localPos:[-2368732377888705e-20,9.532501220730282,3985569264841615e-20],localQuat:[-9.781740202927786e-7,4908535656919963e-25,-.0005018059094885016,.9999998740949284],worldPos:[-80.86566480049744,144.061298192282,-5.5484955291275435],worldQuat:[.5002502631148101,-.4997497980010115,.4997483431213557,.5002513440251519]},{name:`RightHandMiddle2`,parent:11,localPos:[-8881784197001252e-30,3.700000000000017,0],localQuat:[3986107263256567e-37,1323489458050882e-38,.0008498714387871692,.9999996388592037],worldPos:[-84.56566293763908,144.0613075740096,-5.544782705328028],worldQuat:[-.4998253593741713,.5001747659318385,-.5001733119713432,-.4998264415205831]},{name:`RightHandMiddle3`,parent:12,localPos:[-25224267119483557e-29,2.9500000000000455,-1.5411302456413978e-8],localQuat:[-5680000760156732e-38,-3970467145889554e-38,-.00032184201183913403,.9999999482088584],worldPos:[-87.51566222254714,144.06131507131767,-5.54683672237727],worldQuat:[-.4999863107405839,.5000138752279871,-.5000124209192871,-.49998739241899415]},{name:`RightHandMiddle4`,parent:13,localPos:[1127986593019159e-28,2.9466287337241255,7.20586967872805e-9],localQuat:[1.5498268359238913e-7,.0009288141658670982,.00016639448508219264,.9999995548084492],worldPos:[-90.46229095218658,144.06132253675315,-5.546991694384452],worldQuat:[.49943854746932836,-.4996323747246579,.5005598653243383,.5003683130007397]},{name:`RightHandRing1`,parent:10,localPos:[-1.8651332219504173,9.103592315445724,.043069650068900955],localQuat:[6.963165823826897e-8,10850652509911485e-27,.0001558292973731088,.9999999878586124],worldPos:[-80.43675564821785,144.01826884807926,-7.413605017339948],worldQuat:[-.4999220263552031,.5000781487660197,-.5000777412794597,-.4999220592937387]},{name:`RightHandRing2`,parent:15,localPos:[-4440892098500626e-30,3.379273006312431,-2842170943040401e-29],localQuat:[75254050543037e-37,13234890125559426e-39,-.00022151509096650696,.9999999754655319],worldPos:[-83.81602849026015,144.01827033659325,-7.414658689507339],worldQuat:[.5000327889464959,-.4999673962237241,.4999669887298773,.5000328217947667]},{name:`RightHandRing3`,parent:16,localPos:[26290081223123707e-29,2.889684678650127,8202221124520293e-25],localQuat:[16000775075877487e-39,13234889885055366e-39,-.00011280510431914317,.9999999936375041],worldPos:[-86.70571314402952,144.01827160815185,-7.4142794883596075],worldQuat:[.5000891846393266,-.4999109867917636,.499910579294214,.5000892174416297]},{name:`RightHandRing4`,parent:17,localPos:[4716227408607665e-28,2.638815675202565,5682068149326369e-25],localQuat:[-1.339645129809642e-7,.00014607500499735936,-.0007992862081225936,.9999996699017618],worldPos:[-89.34452865122908,144.01827276927736,-7.41333786395688],worldQuat:[.5004155000832223,-.4994381238192544,.4995836834200939,.5005617154884825]},{name:`RightHandIndex1`,parent:10,localPos:[2.25983507131116,9.1082835183702,.5178621137028756],localQuat:[-6.059340578197898e-7,9953529057906979e-26,-.00016426752705445157,.9999999865079061],worldPos:[-80.4414477277744,143.54347484170384,-3.288636902648485],worldQuat:[.5000817363528871,-.4999184374449017,.49991735444845625,.5000824447930416]},{name:`RightHandIndex2`,parent:19,localPos:[-843769498715119e-29,3.7000000000000313,0],localQuat:[-47359322790488744e-39,-3970467069997446e-38,.00025564424489899254,.9999999673230096],worldPos:[-84.14144752826542,143.54348146979163,-3.2874218624291216],worldQuat:[-.4999539187402696,.5000462641269495,-.5000451813116483,-.49995462745726243]},{name:`RightHandIndex3`,parent:20,localPos:[-3423927807943983e-28,2.8500000000000227,-8893152880773414e-25],localQuat:[-13914829894769055e-38,-39704669556009313e-39,-8792197348428728e-20,.9999999961348633],worldPos:[-86.99144748059157,143.54348657664548,-3.287943125263367],worldQuat:[-.49999788186225497,.5000023052590155,-.5000012223814067,-.4999985904840416]},{name:`RightHandIndex4`,parent:21,localPos:[7900347043232614e-28,2.7721906128530236,5114202394906897e-25],localQuat:[8.659859370723384e-8,.0010026920012318767,8705832638285169e-20,.9999994935146673],worldPos:[-89.76363809337116,143.54349154251554,-3.2879626838817946],worldQuat:[.49945279532966436,-.4995441931072631,.5005458853548749,.5004561129854466]},{name:`RightHandThumb1`,parent:10,localPos:[2.6818519535315546,2.464805039121785,1.5739839631865493],localQuat:[.2532844925861686,.06161827244019283,-.22821025705768283,.9380672859078498],worldPos:[-73.79796992221794,142.48734898334772,-2.866619447484665],worldQuat:[.6789718782579114,-.19747746019729454,.5123797682139857,.48730566831705546]},{name:`RightHandThumb2`,parent:23,localPos:[-1887379141862766e-29,4.188985472990834,-2842170943040401e-29],localQuat:[-.002315749257559554,-.0011704489169351957,.009300110231568928,.9999533865657887],worldPos:[-77.01316043621617,140.61457222434876,-.9423386824772395],worldQuat:[.6765749035040036,-.20553967786615746,.5156358706838127,.4838589563451013]},{name:`RightHandThumb3`,parent:24,localPos:[-14210854715202004e-30,3.416271152352966,0],localQuat:[-.0016647383095556567,-.0008077810781858194,.006919747685379302,.9999743462849742],worldPos:[-79.66799955910238,139.08658379209294,.5702713693484767],worldQuat:[.6747462864925903,-.21146538352949726,.5180821304204447,.4812387625412099]},{name:`RightHandThumb4`,parent:25,localPos:[-13822276656583199e-30,2.5749773944199115,0],localQuat:[.005774853769703311,-.11750920454458612,-.048743708782553366,.9918579982867299],worldPos:[-81.68681626684736,137.9345819337196,1.6783234442112593],worldQuat:[.7432186106607572,-.23041213116196285,.41233882500284114,.47382807005935446]},{name:`RightHandPinky1`,parent:10,localPos:[-3.8062774279108913,8.076676225678526,.4867036950552688],localQuat:[4670719286902752e-21,2.4304698046602542e-9,.0005203629947084559,.9999998646002598],worldPos:[-79.40983953257197,143.5746349351307,-9.354749239786173],worldQuat:[.499741997111188,-.5002580522008165,.500262248259257,.49973743155597233]},{name:`RightHandPinky2`,parent:27,localPos:[-8881784197001252e-30,3.6000000000000654,0],localQuat:[4870027600139235e-37,529395781586262e-37,.0008462316753971022,.9999996419459117],worldPos:[-83.0098375822885,143.57460339401808,-9.358496377738998],worldQuat:[.49931848396687806,-.5006807705888573,.500684962782278,.49931391486245963]},{name:`RightHandPinky3`,parent:28,localPos:[-53290705182007514e-30,2.1000000000000085,-2.116385644512775e-8],localQuat:[1859605644060166e-37,-39704674301868344e-39,-.000496777829639297,.9999998766058863],worldPos:[-85.1098297375345,143.5745850175554,-9.364236374919699],worldQuat:[.49956714946047176,-.5004326584550336,.5004368529177667,.4995625824392057]},{name:`RightHandPinky4`,parent:29,localPos:[12789769243681803e-29,2.1157810760144855,1.4407362414203817e-8],localQuat:[-6.420659236909123e-8,.0015694812069815289,-4128528174330759e-20,.9999987675113715],worldPos:[-87.22560761141007,143.5745664664587,-9.367917366015948],worldQuat:[.4988017359417918,-.4996273949534528,.5011996406746996,.5003680791387806]},{name:`LeftShoulder`,parent:3,localPos:[4.570446071555214,11.195644630655181,-.80662723793772],localQuat:[.48442267749711376,.5709704717068556,-.5261616291252289,.40308972946685606],worldPos:[4.570454255590543,144.58590649477904,-3.316358019038552],worldQuat:[-.4589930047913493,-.5378899562605334,.5599354515710177,-.4318241616452356]},{name:`LeftArm`,parent:31,localPos:[-17763568394002505e-31,10.837705310376135,0],localQuat:[-.02460635908641656,-.002561394687342173,.10350452783474903,.9943212655210948],worldPos:[15.162823921302898,144.06131195632307,-5.548478497344785],worldQuat:[.5000007152647227,.4999994684527458,-.5000001196887698,.4999996965928613]},{name:`LeftForeArm`,parent:32,localPos:[8881784197001252e-30,27.841521654197066,-2842170943040401e-29],localQuat:[9612242362214153e-38,13234889800848425e-39,-2646977960169688e-38,1],worldPos:[43.00434557545168,144.06126546354233,-5.548455563844584],worldQuat:[.5000007152647227,.4999994684527458,-.5000001196887698,.4999996965928612]},{name:`LeftHand`,parent:33,localPos:[5438735050766752e-21,28.328834533709,-5.564248510836478e-7],localQuat:[-626962918533632e-37,-3970466940254537e-38,-26469779601696903e-39,1],worldPos:[71.333180109117,144.06121871342071,-5.548437667671921],worldQuat:[.5000007152647227,.4999994684527458,-.5000001196887698,.4999996965928613]},{name:`LeftHandThumb1`,parent:34,localPos:[-2.681731448380733,2.466144851985561,1.5761928025685847],localQuat:[.25309644676633125,-.06132323271522458,.2273527590163699,.9383455508133752],worldPos:[73.79932012001562,142.48502080725694,-2.866704767040701],worldQuat:[.6787362281261902,.19828588307841977,-.512706326258779,.48696207677299685]},{name:`LeftHandThumb2`,parent:35,localPos:[-6439293542825908e-30,4.18709445950184,2842170943040401e-29],localQuat:[-.002067032129087745,.0010427308040619535,-.008213407893731095,.9999635893478415],worldPos:[77.01712188965233,140.61296547844856,-.9502182343475976],worldQuat:[.6766109604816792,.2054209516609806,-.5155696739884216,.48392949077136155]},{name:`LeftHandThumb3`,parent:36,localPos:[5440092820663267e-30,3.4183883081631072,5684341886080802e-29],localQuat:[-.0015313589649970979,.0007452552330187441,-.006073119605284013,.9999801081784668],worldPos:[79.67313738956891,139.08416322654404,.5642862932655532],worldQuat:[.6749931166817439,.2106761779810745,-.5176795589715161,.48167179145825934]},{name:`LeftHandThumb4`,parent:37,localPos:[1482147737874584e-29,2.580581439610723,0],localQuat:[.005153407131366997,.12268277993699259,.04165153492193895,.9915581311958046],worldPos:[81.69402483309037,137.93008677758235,1.6794194947408763],worldQuat:[.7440625177876421,.2372081988172148,-.41152267473439397,.46984287609461295]},{name:`LeftHandIndex1`,parent:34,localPos:[-2.2598629283141953,9.109308911975873,.5180343214524328],localQuat:[6.665759936749852e-7,-29380348585960335e-27,-44076517660685066e-21,.9999999990284081],worldPos:[80.44248629452144,143.5431683499078,-3.28856742622205],worldQuat:[-.4999790098166289,-.5000211729545403,.5000224907507637,-.4999773245691765]},{name:`LeftHandIndex2`,parent:39,localPos:[-6217248937900877e-30,3.6999999999999886,-5684341886080802e-29],localQuat:[3.407213613716439e-7,3580919473408932e-26,.0001050981787351313,.9999999944771283],worldPos:[84.14248628039589,143.54315723870565,-3.2888905447059225],worldQuat:[.5000317287407754,.49996845295921,-.49997011163297345,.5000297028895362]},{name:`LeftHandIndex3`,parent:40,localPos:[-7172040739078511e-28,2.849999999999966,5684341886080802e-29],localQuat:[3.347505650683504e-7,-22176925334093855e-27,-6624910485486997e-20,.9999999978054721],worldPos:[86.99248625886426,143.54314673774508,-3.2885403736491297],worldQuat:[-.49999877255511554,-.5000014111400769,.5000034044318037,-.499996411845041]},{name:`LeftHandIndex4`,parent:41,localPos:[858424442640171e-27,2.7748656282368103,0],localQuat:[1.0594603907920247e-8,-.0003775632648206345,-13069537623522493e-21,.9999999286375816],worldPos:[89.76735188694607,143.54313465598005,-3.288567098859584],worldQuat:[.4998034244662043,.4998191246365437,-.5001986899385569,.5001786182186978]},{name:`LeftHandMiddle1`,parent:34,localPos:[-3660436011010404e-20,9.53340148931592,-3254047146583616e-20],localQuat:[4.084735851900896e-7,-12926721325528698e-27,-3164640698382836e-20,.9999999994991691],worldPos:[80.86658159844058,144.06123533397496,-5.548393210486787],worldQuat:[-.49998509605784175,-.5000150871851532,.5000161468752833,-.499983668904545]},{name:`LeftHandMiddle2`,parent:43,localPos:[-26645352591003757e-31,3.6999999999999744,-2842170943040401e-29],localQuat:[-1.6358384175735772e-7,-34673461654660564e-28,2119614093572879e-20,.9999999997753484],worldPos:[84.5665815912097,144.0612261326968,-5.548624346151146],worldQuat:[-.49999561254479435,-.500004571111091,.5000054672459868,-.49999434899615885]},{name:`LeftHandMiddle3`,parent:44,localPos:[-28697044740511046e-28,2.9500000006246694,-2842170943040401e-29],localQuat:[-4.275899279477681e-7,-884662274908745e-26,20689502181930057e-21,.9999999997858808],worldPos:[87.51658159123295,144.06121976164127,-5.548683572757025],worldQuat:[.5000057434864292,.4999944401365919,-.4999949087122563,.5000049075508173]},{name:`LeftHandMiddle4`,parent:45,localPos:[-8713030297258229e-27,2.952863459443819,-14210854715202004e-29],localQuat:[-2.6759425390821073e-8,-.0010241407152540845,279847572642705e-19,.9999994751761864],worldPos:[90.46944505000428,144.06121590958617,-5.548620670295296],worldQuat:[.499507394771273,.49946812318416767,-.5004927166472543,.5005307154158994]},{name:`LeftHandRing1`,parent:34,localPos:[1.865081040398466,9.104528720799948,.04302823471783768],localQuat:[6.248995762954407e-7,39451643110942306e-28,6313277301958232e-21,.9999999999798759],worldPos:[80.43771029434576,144.0181759602736,-7.413511224335965],worldQuat:[.5000041843415268,.49999599935162675,-.4999972754894557,.5000025407699983]},{name:`LeftHandRing2`,parent:47,localPos:[-4440892098500626e-30,3.1500000002318416,0],localQuat:[-19345585602378175e-38,0,4235164736267838e-37,1],worldPos:[83.58771029427925,144.01816676318134,-7.413468855985753],worldQuat:[.5000041843415268,.4999959993516267,-.4999972754894557,.5000025407699983]},{name:`LeftHandRing3`,parent:48,localPos:[2643289183090758e-21,2.9500000001810776,5.209859352817148e-7],localQuat:[-8757673760813274e-38,1323488980045867e-38,12839125457873287e-48,1],worldPos:[86.53771029421749,144.01815762904647,-7.413431820978903],worldQuat:[.5000041843415268,.4999959993516267,-.4999972754894557,.5000025407699983]},{name:`LeftHandRing4`,parent:49,localPos:[-23274330810174604e-21,2.644316435477009,-14607575451464072e-22],localQuat:[-2.7316933950438635e-7,.0004934373218353761,16047023509748673e-21,.9999998781310067],worldPos:[89.18202672913526,144.0181513691535,-7.413372979877784],worldQuat:[.5002587275852554,.5002347713372702,-.49974233369355947,.49976392320219065]},{name:`LeftHandPinky1`,parent:34,localPos:[3.806263215177876,8.077778818742132,.4868770149745387],localQuat:[-4975537953269548e-21,1.0178097892277194e-8,.0020448023965822897,.9999979093770162],worldPos:[79.41096125008677,143.57432960785403,-9.354694407950916],worldQuat:[.5010195873847003,.4989785133401168,-.498974180943756,.5010235354085267]},{name:`LeftHandPinky2`,parent:51,localPos:[-3552713678800501e-30,3.6000000000000796,2842170943040401e-29],localQuat:[6.285466836481913e-7,-13240964884135178e-26,-.00021066000242779323,.9999999778109838],worldPos:[83.01093113307373,143.5743594144743,-9.339968896109413],worldQuat:[.5009147763033496,.49908373336086237,-.499080029188825,.5009180955410079]},{name:`LeftHandPinky3`,parent:52,localPos:[23803181647963356e-29,2.1000000536000414,5684341886080802e-29],localQuat:[1.0560541723515637e-7,-70842344057535595e-28,-6708211165014274e-20,.9999999977499896],worldPos:[85.11091705114045,143.57437416212716,-9.332263779357556],worldQuat:[.500881348481691,.4991172819497667,-.4991136834189969,.5008845621759181]},{name:`LeftHandPinky4`,parent:53,localPos:[11048939541069558e-28,2.12553132909224,0],localQuat:[2.2034709579345264e-7,-.0007833987784531817,-.0002953855857226705,.9999996495167691],worldPos:[87.23643510003559,143.57438864025644,-9.324750154134009],worldQuat:[.5003428461990634,.49887255781562256,-.4996539623833923,.5011278531377935]},{name:`RightUpLeg`,parent:0,localPos:[-8.207789844904983,-6.771764137627812,-1.5122187689572422],localQuat:[2.7047671429134563e-9,.010356475588677583,.9999463702685825,2.6115275064568443e-7],worldPos:[-8.207797572195703,97.52320568879888,-.04524648166077205],worldQuat:[4.391377782486676e-9,.0038980599621582274,.9999924025353709,2.611298350175175e-7]},{name:`RightLeg`,parent:55,localPos:[6.19727558159866e-9,44.37146193723237,-16631140908884845e-29],localQuat:[-.03809137752293408,-816315213450579e-24,2.1414893185802513e-8,.9992742601300231],worldPos:[-8.207820750122902,53.15309218889458,.3006761286643062],worldQuat:[-4.658818794361865e-9,-.03419585714041286,.9994151506528081,2.396960478727042e-7]},{name:`RightFoot`,parent:56,localPos:[-5.538291603102152e-9,44.52781411684904,18207657603852567e-30],localQuat:[.45974006194132166,3725814189701004e-38,-1.2432846936543718e-7,.8880535318583977],worldPos:[-8.207842064194724,8.729415862750969,-2.742876350631811],worldQuat:[1.1031211398837241e-7,.4291034315577479,.903255359809859,3.3926052346823936e-7]},{name:`RightToeBase`,parent:57,localPos:[0,13.816866143314009,6217248937900877e-30],localQuat:[.335241516804437,7023902526244116e-39,-1.1130089220595614e-7,.9421322228915896],worldPos:[-8.207849224193675,.0007420744116171107,7.96768124078066],worldQuat:[1.6990321486208088e-7,.7070808667083169,.7071326947149592,3.8318019813577996e-7]},{name:`RightToe_End`,parent:58,localPos:[-17763568394002505e-31,9.278120542404253,4288670113483661e-30],localQuat:[-3388360082792521e-36,.01160806788231821,11912203416067455e-38,.9999326241102645],worldPos:[-8.207852022918948,6202649694084369e-20,17.245801758262132],worldQuat:[-.008208274430290369,.7070332309537893,.7070850529927397,-.0082074595446575]},{name:`LeftUpLeg`,parent:0,localPos:[8.207788043566438,-6.771802818529409,-1.5122137762205135],localQuat:[2.8191483378909245e-9,.01036795967915088,.9999462512615453,2.718950400523856e-7],worldPos:[8.207780316275715,97.52316694663398,-.04524198897490894],worldQuat:[4.575136162088223e-9,.00390954458172457,.9999923577013424,2.7187116164010067e-7]},{name:`LeftLeg`,parent:60,localPos:[6.468269475590205e-9,44.37138978410286,37414515929867775e-30],localQuat:[-.0381124510208252,-8172602612650612e-25,2.142781333519525e-8,.9992734566059407],worldPos:[8.207756184976574,53.15313355499844,.30169921260475335],worldQuat:[-4.888837197809569e-9,-.034205455626157316,.9994148221861352,2.504235506344471e-7]},{name:`LeftFoot`,parent:61,localPos:[-5.547779124981389e-9,44.52784595754781,-2220446049250313e-29],localQuat:[.4597486071334844,-3725832749974238e-39,-1.1668517803347452e-7,.8880491080108168],worldPos:[8.207733916824536,8.729483932050528,-2.742708742345943],worldQuat:[1.147816207643381e-7,.4291034480907216,.9032553519556492,3.412529433141002e-7]},{name:`LeftToeBase`,parent:62,localPos:[17763568394002505e-31,13.81686480841043,-17763568394002505e-31],localQuat:[.33524149798857344,10535853714492708e-39,-1.1452079069214378e-7,.94213222958689],worldPos:[8.207726760093172,.0008113791108694812,7.967848133811215],worldQuat:[1.7340034603185666e-7,.707080865528955,.7071326958942321,3.864673509538802e-7]},{name:`LeftToe_End`,parent:63,localPos:[0,9.278136754869934,-13125351500109517e-31],localQuat:[0,-.011869165745076847,18530151004086692e-38,.9999295589712888],worldPos:[8.207723964114914,.00013129905961646127,17.245984863756057],worldQuat:[.008393248559463194,.7070310534383599,.7070828826815805,.008392846428263363]}],landmarks:{mouth:[0,158.500185546875,11.717991638183594],headEllipsoid:{centre:[-95367431640625e-19,167.56204986572266,-.15480518341064453],radii:[8.804292678833008,13.326271057128906,12.424483299255371]},headJoint:[1671650538423477e-20,159.92947501239226,-1.5195243864816557],headTop:[298931534294587e-19,181.96684091859,5.981578858112073],sole:{ball:0,tip:-.7}}},"y-bot-tpose":{model:`y-bot-tpose`,units:`cm`,mesh:`Alpha_Surface`,bones:[{name:`Hips`,parent:-1,localPos:[-6757011760782916e-21,99.79193878173828,4844740033149719e-20],localQuat:[7615435492247396e-26,-17453292503320135e-22,4363323128594654e-20,.9999999990465473],worldPos:[-6757011760782916e-21,99.79193878173828,4844740033149719e-20],worldQuat:[7615435492247396e-26,-17453292503320135e-22,4363323128594654e-20,.9999999990465473]},{name:`Spine`,parent:0,localPos:[.0008597856133863019,9.923461876522225,-1.2273349078167588],localQuat:[-.06073022898235704,5303745488019905e-37,6119354919596912e-21,.9981542161661715],worldPos:[-8672608244745512e-21,109.71540069587908,-1.227286457407732],worldQuat:[-.060730228859120175,-4391963877518737e-21,4956605444176136e-20,.9981542149520963]},{name:`Spine1`,parent:1,localPos:[0,11.731977989043784,-3552713678800501e-30],localQuat:[.0001960924550491026,4662287733052689e-29,-9316072744031837e-21,.9999999807304797],worldPos:[-.0011632832276606084,121.36083978703566,-2.649627688070991],worldQuat:[-.06053449713743436,-494801144686156e-20,4026803743853935e-20,.9981661049195772]},{name:`Spine2`,parent:2,localPos:[1931491945550423e-26,13.458836780167971,6235012506294879e-28],localQuat:[.057711730916465316,21958232674411106e-22,3285013706200134e-21,.9983332890868721],worldPos:[-.0022371547694859653,134.72103871836885,-4.27608729015328],worldQuat:[-.002827710078055566,-2.2517339024978275e-7,4363254684471116e-20,.9999960010679366]},{name:`Neck`,parent:3,localPos:[2548122992670175e-20,15.027761372130044,.8779068542021755],localQuat:[.0028277058943183713,-8816242878226746e-54,-7234126583784003e-36,.9999960020316957],worldPos:[-.003523660156014883,149.7535246254643,-3.4831824403326026],worldQuat:[-4.186445695616128e-9,-1.017924801167934e-7,4363300912729469e-20,.999999999048075]},{name:`Head`,parent:4,localPos:[2562548663041439e-21,10.32183835340436,3.1424288991299827],localQuat:[12407709188295404e-40,13234889800848435e-39,-33812794736012347e-37,1],worldPos:[-.0044224830930743595,160.07536296607333,-.3407536277174854],worldQuat:[-4.1864456956161264e-9,-1.0179248011679337e-7,43633009127294685e-21,.999999999048075]},{name:`HeadTop_End`,parent:5,localPos:[.00015451594228192873,18.474670356296826,6.63639947863672],localQuat:[693889473108785e-32,-661744490042423e-38,-10158249377722142e-36,1],worldPos:[-.005881529143937624,178.55003332101543,6.295645696100038],worldQuat:[-4.186445688677232e-9,-1.0179248011679308e-7,4363300912729468e-20,.999999999048075]},{name:`LeftShoulder`,parent:3,localPos:[6.105824524896,9.10629188078309,.757062475638635],localQuat:[-.45383506682997793,-.5448493479758866,.5511388470821386,-.4397941465761588],worldPos:[6.10279217248512,143.83199925791556,-3.5705353792059826],worldQuat:[-.4525659925709384,-.5433084112379314,.5526580275773418,-.44109987213863294]},{name:`LeftArm`,parent:7,localPos:[4884981308350689e-30,12.92228632488431,2842170943040401e-29],localQuat:[-.010451820107802023,-.0010627185813176982,.10115046260752789,.9948156683526521],worldPos:[18.75785325853472,143.5671732022338,-6.171454434247386],worldQuat:[.49997802104022876,.5000219779933275,-.4999777974641308,.5000222015503447]},{name:`LeftForeArm`,parent:8,localPos:[3.059411390893274e-9,27.404682159441652,-2842170943040401e-29],localQuat:[-10173904404505293e-36,6815758221109549e-42,13234889800848457e-39,1],worldPos:[46.162535310990236,143.5695947084291,-6.171442183765884],worldQuat:[.49997802104022876,.5000219779933275,-.4999777974641308,.5000222015503447]},{name:`LeftHand`,parent:9,localPos:[-12820418092474029e-21,27.614463806173113,2.3361064904747764e-7],localQuat:[-3397640826470449e-36,-18680226235633534e-43,52939559203393736e-39,1],worldPos:[73.77699900937316,143.57203451753804,-6.171417016006557],worldQuat:[.49997802104022876,.5000219779933275,-.4999777974641308,.5000222015503447]},{name:`LeftHandRing1`,parent:10,localPos:[2.216630558205681,12.147010274148471,-.009996226470974534],localQuat:[5.56794949511021e-7,-3.067028835367668e-9,4777353976607745e-21,.9999999999884335],worldPos:[85.92400934395243,143.5831040665074,-8.388042142881478],worldQuat:[.49998068669282075,.5000193094968617,-.4999756886184537,.500024313263825]},{name:`LeftHandRing2`,parent:11,localPos:[0,3.601188659840844,0],localQuat:[-2306826384812874e-21,1861861504887997e-26,-8071095064110734e-21,.999999999964768],worldPos:[89.52519798990681,143.58341826103262,-8.388006124364832],worldQuat:[.4999754975118546,.5000244982373176,-.49997857087756026,.5000214312542258]},{name:`LeftHandRing3`,parent:12,localPos:[-7140954494389007e-28,3.3073120118204997,22737367544323206e-29],localQuat:[-32584970000852863e-37,-2067951531382572e-40,-6352747104407258e-37,1],worldPos:[92.83250998771065,143.5837220743585,-8.388026432414401],worldQuat:[.49997549751185466,.5000244982373176,-.49997857087756026,.5000214312542258]},{name:`LeftHandRing4`,parent:13,localPos:[-241726316367874e-19,3.660118102908669,16886514032421474e-21],localQuat:[8486035821629225e-21,.007396474405473809,.0007707649842267434,.9999723486255485],worldPos:[96.49262807680708,143.5840414103271,-8.388024734185503],worldQuat:[.5040493957792119,.5033194611486261,-.4958855340273986,.4966903097363882]},{name:`LeftHandMiddle1`,parent:10,localPos:[-18344155402694184e-21,12.77552795411546,-10320898695681535e-22],localQuat:[5.567949752588633e-7,-2.6633364343577455e-9,2.0800236288001427e-7,.9999999999998233],worldPos:[86.55252691351437,143.5731644085546,-6.171392959489538],worldQuat:[.49997840212413347,.5000215942797767,-.49997797319957754,.5000220284932966]},{name:`LeftHandMiddle2`,parent:15,localPos:[-3552713678800501e-30,3.61396789550858,-2842170943040401e-29],localQuat:[23697741078528623e-36,6203854594147698e-40,-26469779601696844e-39,1],worldPos:[90.16649479526663,143.5734797180353,-6.171389840137076],worldQuat:[.49997840212413347,.5000215942797767,-.49997797319957754,.5000220284932966]},{name:`LeftHandMiddle3`,parent:16,localPos:[28508498060020315e-21,3.4597625732240687,-8526512829121202e-29],localQuat:[1692147750009982e-35,20679515313825724e-41,264697796016969e-37,1],worldPos:[93.62625735534596,143.57378157349484,-6.171415362383127],worldQuat:[.49997840212413347,.5000215942797767,-.49997797319957754,.5000220284932966]},{name:`LeftHandMiddle4`,parent:17,localPos:[-30473889779614183e-21,3.680191040059995,-2842170943040401e-29],localQuat:[-133272714831852e-20,.004579424073341433,-.000654144096597114,.9999893004272004],worldPos:[97.30644838137125,143.57410266077613,-6.171381711981186],worldQuat:[.5019349111684311,.5026337814312043,-.4980094305837711,.4974004762403589]},{name:`LeftHandThumb1`,parent:10,localPos:[-3.002975029424964,3.7888090485209744,2.1671489778191813],localQuat:[.25189492500135036,-.05946403657250492,.2219235197808198,.940086659027326],worldPos:[77.56599819190912,141.40522033116738,-3.168440292478436],worldQuat:[.6772116616355364,.20343190021506413,-.5147394802435296,.484812432594653]},{name:`LeftHandThumb2`,parent:19,localPos:[-19984014443252818e-31,4.744970523440218,2842170943040401e-29],localQuat:[69460704858849485e-22,55796786860811154e-28,8.032883032279416e-7,.9999999999755533],worldPos:[81.24162844278966,139.28353174695044,-1.0464306132517085],worldQuat:[.6772151925776482,.20342778079987783,-.5147405038353289,.48480814210593404]},{name:`LeftHandThumb3`,parent:20,localPos:[-5984102102729594e-28,4.3821287009303775,5172751116333529e-27],localQuat:[7030691099565929e-33,7121429504040547e-33,-15407439555097887e-48,1],worldPos:[84.63615479208448,137.32403482337068,.9133179986734019],worldQuat:[.6772151925776482,.20342778079987775,-.5147405038353289,.48480814210593404]},{name:`LeftHandThumb4`,parent:21,localPos:[-51284654249972306e-22,3.459077859769903,4.03463474185628e-7],localQuat:[.009146816027813427,.1256374250101491,.07207247635857116,.9894125182879566],worldPos:[87.31565650284612,135.77728679427992,2.4602700847142343],worldQuat:[.7538118553684166,.20866722684171796,-.3911265183168664,.4850213622280347]},{name:`LeftHandIndex1`,parent:10,localPos:[-2.822044006965872,12.266617250897596,.23182516767607808],localQuat:[5.567949601161418e-7,-3.075281477739248e-9,487076476385117e-20,.9999999999879827],worldPos:[86.04363543486608,143.34129324170544,-3.34936752423002],worldQuat:[.49998073339592125,.5000192627891642,-.4999756419148924,.5000243599710406]},{name:`LeftHandIndex2`,parent:23,localPos:[-13322676295501878e-31,3.891967773631521,0],localQuat:[-30225470980600983e-37,0,-6214320207710297e-21,.999999999980691],worldPos:[89.93560319348254,143.34163280596658,-3.349327870283342],worldQuat:[.49997762610645813,.5000223698198841,-.4999787492167228,.5000212529526508]},{name:`LeftHandIndex3`,parent:24,localPos:[4071321058063404e-26,3.415161132822689,-11368683772161603e-29],localQuat:[46684518186119064e-39,-9183549615799121e-56,21175823681357537e-38,1],worldPos:[93.35076431329836,143.34193077006435,-3.3493355202090695],worldQuat:[.49997762610645813,.5000223698198841,-.4999787492167229,.5000212529526508]},{name:`LeftHandIndex4`,parent:25,localPos:[5.854722480158614e-7,3.0779876709090814,5684341886080802e-29],localQuat:[10393592226093013e-22,.004001602788212073,22779581052790166e-21,.9999919932955144],worldPos:[96.4287519724834,143.34219931663745,-3.3493430003052733],worldQuat:[.5019862492920715,.5020073437901309,-.4979631636001596,.4980272281710877]},{name:`LeftHandPinky1`,parent:10,localPos:[4.72583130478205,10.908194092064392,.22613216873591568],localQuat:[28521120612919424e-22,-3.0577730863769185e-9,.000141051374267014,.9999999900481878],worldPos:[84.68521515320175,143.3468662092345,-10.897243443373178],worldQuat:[.5000499694422342,.49995002290857044,-.49990869131728644,.5000912946652625]},{name:`LeftHandPinky2`,parent:27,localPos:[-5329070518200751e-30,4.136657059551979,2842170943040401e-29],localQuat:[-59544873416476465e-22,2.190560405006969e-9,-.0003678839387923365,.9999999323129735],worldPos:[88.82187203349876,143.3472081321215,-10.896074631422186],worldQuat:[.4998630353195086,.5001369272162459,-.5000896549937187,.49991032888321396]},{name:`LeftHandPinky3`,parent:28,localPos:[43876013933186186e-29,2.594834461051775,0],localQuat:[36591694282576963e-22,8409112616016821e-25,.00022980932036022433,.999999973587143],worldPos:[91.41670621645012,143.34745351466333,-10.897250657097295],worldQuat:[.49997978792115133,.5000202113293842,-.49997658739741363,.5000234114387793]},{name:`LeftHandPinky4`,parent:29,localPos:[-2948752353404416e-28,2.9238662720287607,-2842170943040401e-29],localQuat:[-10497831164166655e-22,.004099894588367042,-.0005750644579927158,.9999914300453439],worldPos:[94.34057247729058,143.3477086145383,-10.89723194250163],worldQuat:[.5017372856540723,.5023540149301887,-.4982094589732469,.49768210220741194]},{name:`RightShoulder`,parent:3,localPos:[-6.1056956701096174,9.10638358733786,.7570756312724551],localQuat:[.4538375688887134,-.5448472538987562,.5511399888422243,.43979272809263187],worldPos:[-6.1087279840345,143.8310253866605,-3.5705252284969617],worldQuat:[.45261579666489365,-.5432669079313696,.5526977464106563,.44105012013225253]},{name:`RightArm`,parent:31,localPos:[39968028886505635e-31,12.922286714484947,0],localQuat:[-.01045541384979725,.0010630628959740092,-.10114940861202837,.9948157373885607],worldPos:[-18.763745414580892,143.56389953844294,-6.171423447408117],worldQuat:[.5000215299672571,-.4999784691060287,.5000215360351153,.4999784630368383]},{name:`RightForeArm`,parent:32,localPos:[8.327427636345419e-9,27.404682159441318,-2842170943040401e-29],localQuat:[-3388329060809388e-36,-15146129380243438e-44,8271806125530284e-40,1],worldPos:[-46.16842747236397,143.56153906740224,-6.171423771692651],worldQuat:[.5000215299672571,-.49997846910602883,.5000215360351153,.4999784630368383]},{name:`RightHand`,parent:33,localPos:[12842842382454478e-21,27.614463806155165,15492399938921153e-21],localQuat:[-19727179218464944e-41,-7573064690121704e-44,0,1],worldPos:[-73.78289117474843,143.55914503465877,-6.17141126400836],worldQuat:[.5000215299672571,-.4999784691060287,.5000215360351153,.4999784630368383]},{name:`RightHandThumb1`,parent:34,localPos:[3.002974470681663,3.7888088905192205,2.1671490371761024],localQuat:[.25189499102226326,.05946427874712486,-.2219234615465524,.9400866397658112],worldPos:[-77.57151342274972,141.3916696607838,-3.168436839313407],worldQuat:[.6772291629398663,-.20337279117491877,.5147821060302558,.4847675236487542]},{name:`RightHandThumb2`,parent:35,localPos:[-68833827526759706e-31,4.744970470128291,2842170943040401e-29],localQuat:[8453832451066965e-21,-33376070678072775e-28,-3.9480215616198235e-7,.9999999999641884],worldPos:[-81.24677425676067,139.26933968812125,-1.0464288158806956],worldQuat:[.6772333413527709,-.20336817191604672,.5147836339017984,.48476200168592604]},{name:`RightHandThumb3`,parent:36,localPos:[-17763568394002505e-29,4.382135391768333,-4092726157978177e-27],localQuat:[-14347996972659013e-33,-5998687332454958e-33,-1387778780781447e-32,1],worldPos:[-84.64095942776746,137.30923516924733,.9133180789494266],worldQuat:[.6772333413527709,-.20336817191604672,.5147836339017984,.48476200168592604]},{name:`RightHandThumb4`,parent:37,localPos:[11177533225659175e-21,3.4590709023307085,-23241859054223823e-21],localQuat:[.00923206336161341,-.1271302153500302,-.0723276818427547,.989202397788438],worldPos:[-87.32019182850055,135.76203483248253,2.460268746809576],worldQuat:[.7545499013151971,-.2090649481886763,.389944180490974,.4846543407061524]},{name:`RightHandIndex1`,parent:34,localPos:[2.822042502024897,12.266617102415225,.23182522345669554],localQuat:[5.567922673046469e-7,-7.224337929733461e-9,-4743924457641052e-21,.9999999999885925],worldPos:[-86.04948829791044,143.32626324098368,-3.3493689108641775],worldQuat:[.5000241838181078,-.4999758222398485,.5000194389411731,.4999805530753941]},{name:`RightHandIndex2`,parent:39,localPos:[0,3.891967773619811,0],localQuat:[1695401251774016e-35,-4135903062840235e-40,602627167052741e-20,.9999999999818419],worldPos:[-89.94145605654246,143.32592367674323,-3.3493320316989923],worldQuat:[.5000211708188947,-.4999788355123435,.5000224519507367,.4999775398133359]},{name:`RightHandIndex3`,parent:40,localPos:[-51669779566054785e-28,3.4151611328221207,11368683772161603e-29],localQuat:[-13593959205239575e-36,0,0,1],worldPos:[-93.35661717635494,143.32562571266394,-3.349340831998884],worldQuat:[.5000211708188947,-.4999788355123435,.5000224519507367,.4999775398133359]},{name:`RightHandIndex4`,parent:41,localPos:[-12771572572845002e-22,3.0779876709101757,-2842170943040401e-29],localQuat:[-7290381402922513e-20,-.006709307422924062,.0013745331778991744,.9999765449936721],worldPos:[-96.4346048355366,143.3253571661075,-3.3493500406116747],worldQuat:[-.5026405594004304,.5040453607575476,-.49730671352060296,-.49596045712511533]},{name:`RightHandMiddle1`,parent:34,localPos:[16632154487439266e-21,12.775527954114011,-10320893863990932e-22],localQuat:[5.567949633221699e-7,-7.289108692409176e-9,-3.662527039828292e-7,.9999999999997777],worldPos:[-86.55841908156046,143.55804566121927,-6.171394786911078],worldQuat:[.5000219951158138,-.4999780112066047,.5000216276573223,.4999783641170999]},{name:`RightHandMiddle2`,parent:43,localPos:[8881784197001252e-31,3.6139678955093757,0],localQuat:[-33759614098155274e-37,-4135903062765133e-40,0,1],worldPos:[-90.17238696331393,143.55773035173834,-6.171392183522983],worldQuat:[.5000219951158138,-.4999780112066047,.5000216276573223,.4999783641170999]},{name:`RightHandMiddle3`,parent:44,localPos:[-29421479796454264e-21,3.4597625732165085,14210854715202004e-29],localQuat:[34003021678244415e-37,-8271806125530284e-40,-7940933880509075e-38,1],worldPos:[-93.63214952338268,143.55742849627876,-6.1714191126993185],worldQuat:[.5000219951158138,-.4999780112066047,.5000216276573223,.4999783641170999]},{name:`RightHandMiddle4`,parent:45,localPos:[28549065814509333e-21,3.680191040067001,-5684341886080802e-29],localQuat:[-5158123071926063e-20,-.006695195594000001,-.0017083442773867367,.9999761263426065],worldPos:[-97.31234054942114,143.557107408997,-6.171387912540353],worldQuat:[.504186145435319,-.5024851098604104,.49578202059538456,.49749897806327625]},{name:`RightHandRing1`,parent:34,localPos:[-2.216632303077052,12.147002761381543,-.009996270293299858],localQuat:[5.567954667309114e-7,-7.224304767843245e-9,-4803651127566965e-21,.9999999999883074],worldPos:[-85.92989472518438,143.5680950366908,-8.38804371451417],worldQuat:[.5000242136815972,-.49997579237346873,.5000194090805982,.49998058293828956]},{name:`RightHandRing2`,parent:47,localPos:[0,3.6011962892353893,-8526512829121202e-29],localQuat:[-5732183384702703e-36,0,8071083662125689e-21,.9999999999674287],worldPos:[-89.53109100054763,143.5677808414962,-8.388009160440863],worldQuat:[.5000201783188615,-.4999798280944457,.5000234444494263,.4999765472235214]},{name:`RightHandRing3`,parent:48,localPos:[-6055600465515454e-27,3.307312011785328,-11368683772161603e-29],localQuat:[32821615918857455e-37,-36734198463196485e-56,21175823681357546e-38,1],worldPos:[-92.83840299967426,143.56749228695628,-8.38803081342569],worldQuat:[.5000201783188615,-.4999798280944457,.5000234444494263,.4999765472235214]},{name:`RightHandRing4`,parent:49,localPos:[2417262415121968e-20,3.6601181029476635,-2842170943040401e-29],localQuat:[-6164489635359998e-20,-.007613221748708619,-.000300224892743606,.9999709720384515],worldPos:[-96.49852108877111,143.56717295098406,-8.388030603602541],worldQuat:[.5039317385023292,-.503652452411389,.49602123868179077,.49633651979941534]},{name:`RightHandPinky1`,parent:34,localPos:[-4.725833119502555,10.90819434071372,.2261320753251539],localQuat:[5.567949828639406e-7,-7.530380981813863e-9,-3132050030138696e-21,.99999999999494],worldPos:[-84.69106594001192,143.3320733953033,-10.897244515904388],worldQuat:[.5000233780731588,-.4999766283665967,.5000202446951756,.49997974695226793]},{name:`RightHandPinky2`,parent:51,localPos:[0,4.13665008553545,-2842170943040401e-29],localQuat:[1470867824118891e-37,8271806125977124e-40,10394374390791114e-21,.9999999999459783],worldPos:[-88.8277160097222,143.33171248313417,-10.897218653721097],worldQuat:[.5000181811018849,-.4999818257697831,.5000254416448413,.49997454952763204]},{name:`RightHandPinky3`,parent:52,localPos:[-3950617610826157e-27,2.5948410036845218,-8526512829121202e-29],localQuat:[6674018442413745e-36,1836709923259698e-55,-10428465638715964e-21,.9999999999456235],worldPos:[-91.42255700325643,143.33148608987582,-10.897256374372848],worldQuat:[.5000233951179858,-.49997661132017523,.5000202276502416,.4999797639985816]},{name:`RightHandPinky4`,parent:53,localPos:[4362732397567015e-27,2.923866272034857,5684341886080802e-29],localQuat:[-8226663950025322e-20,-.00849884034311731,.0022061069470672434,.9999614472754239],worldPos:[-94.34642326410449,143.33123099000105,-10.897237895108226],worldQuat:[-.5031095764062739,.5053508241180749,-.4968132089402998,-.4946493041680384]},{name:`LeftUpLeg`,parent:0,localPos:[9.123873709849553,-6.657188518716367,-.05540310527662988],localQuat:[20251728747483253e-21,-.006350177975401161,.9999754277247583,-.002969642442257367],worldPos:[9.12444806072654,93.13554649657034,-.05532280954860631],worldQuat:[18783520922709306e-21,-.006350171978846871,.999975297231096,-.00301328568169704]},{name:`LeftLeg`,parent:55,localPos:[-4618527782440651e-29,40.59943638074365,1170175067954915e-28],localQuat:[-.018114309191591866,.00018249364298742092,-.005920146666904975,.9998183786878614],worldPos:[9.369107731941927,52.540121711606496,-.5709414745281038],worldQuat:[-715314874584385e-19,-.02446331907456045,.9996964939479204,.00290876113461602]},{name:`LeftFoot`,parent:56,localPos:[-10658141036401503e-30,42.09902591219656,20872192862952943e-30],localQuat:[.5405498192560871,.01436647216366454,.024951033886733327,.8408192096329419],worldPos:[9.12441738143423,10.49219684921195,-2.6300976499043784],worldQuat:[-.01346031169880001,.5198601039256607,.853859207560786,-.022107600933591907]},{name:`LeftToeBase`,parent:57,localPos:[17763568394002505e-31,15.721559146548017,-1509903313490213e-29],localQuat:[.2276920621809942,-.032521469150786096,-.015365592016704316,.9730686396375217],worldPos:[9.497939603229476,3.2836504838127345,11.336461068911172],worldQuat:[.0016492651748272183,.7007886739142866,.7132730439227728,.01157925951782756]},{name:`LeftToe_End`,parent:58,localPos:[17763568394002505e-31,9.999999999999991,4.890746918562172e-9],localQuat:[3842630640765734e-25,-2181956872127079e-33,8673617379884037e-34,1],worldPos:[9.355871856763304,3.108427383452366,21.333916426176543],worldQuat:[.0016492651792767014,.700788674188371,.7132730436534856,.011579259517193808]},{name:`RightUpLeg`,parent:0,localPos:[-9.125032356625555,-6.655601347887028,-.05535274484958799],localQuat:[-17972283601838397e-21,-.006333801286546503,.9999752669985558,.0030574547301418053],worldPos:[-9.12445807483328,93.1355411499169,-.055336149820714026],worldQuat:[-19441205218510228e-21,-.006333807477113975,.9999753994199062,.00301381152055421]},{name:`RightLeg`,parent:60,localPos:[7105427357601002e-30,40.59943859177964,26645352591003757e-30],localQuat:[-.018147073530042527,-.00018249394989624574,.005920149654138874,.9998177845219228],worldPos:[-9.369160167563622,52.54009755727,-.5696263108436963],worldQuat:[7086285029500266e-20,-.024479715368387448,.9996960941175567,-.0029082503401009767]},{name:`RightFoot`,parent:61,localPos:[-24868995751603507e-30,42.09902387472938,-6217248937900877e-29],localQuat:[.5405636018310247,-.014366037304083883,-.024951225824318232,.8408103506008421],worldPos:[-9.12451164224619,10.492242047309674,-2.6301615125796047],worldQuat:[.013459958226241265,.5198600714589466,.8538592128932476,.02210837363015364]},{name:`RightToeBase`,parent:62,localPos:[3552713678800501e-30,15.721558809599616,26645352591003757e-31],localQuat:[.22770869920802236,.03211960072148292,.015257901862228916,.9730797891155923],worldPos:[-9.498060396707743,3.2836958492734345,11.33639620371245],worldQuat:[-.0013617607248561205,.700801240791512,.7132661380535977,-.011277536030161229]},{name:`RightToe_End`,parent:63,localPos:[3.1880595940947387e-9,9.999999999999998,5.687534443410414e-9],localQuat:[-3109963189751316e-25,-16439215440311446e-32,-17347234759768052e-34,1],worldPos:[-9.356269180688868,3.1086870931784847,21.33385924122101],worldQuat:[-.0013617607213487338,.7008012405696887,.7132661382715444,-.011277536030584614]}],landmarks:{mouth:[0,158.399150390625,12.493875312805176],headEllipsoid:{centre:[-16689300537109375e-21,167.32984161376953,.6807799339294434],radii:[8.005595684051514,13.133369445800781,12.374487400054932]},headJoint:[-.0044224830930743595,160.07536296607333,-.3407536277174854],headTop:[-.005881529143937624,178.55003332101543,6.295645696100038],sole:{ball:3.3,tip:2.6}}}},Zl=new Map;function Ql(e){return Xl[e]?(Zl.has(e)||Zl.set(e,jo(Xl[e])),Zl.get(e)):null}var $l=Sc.filter(e=>e[0].startsWith(`torso`)),eu=Sc.find(e=>e[0]===`hand_l`)[3],tu=.004;function nu(e,t,n){let r=H(n,t);return G(H(e,V(t,U(r,_o(W(H(e,t),r)/Math.max(W(r,r),1e-12),0,1)))))}function ru(e){let t=[];for(let n of[-1,1])for(let r of[0,2])for(let i of[-1,1])t.push(V(e.pos,J(e.R,[n*e.half[0],r*e.half[1],i*e.half[2]])));return t}function iu(e,t,n,r,i=()=>null){let a=e.index,o=Object.entries(t.ctx.spec.objects??{}).filter(([,e])=>C_(e)).map(([e])=>e);for(let e=0;e<t.frames.length;e++){let{s,diag:c}=t.frames[e],l=s.P,u=[];for(let[e,t]of Object.entries(c.props??{}))for(let[n,r]of Object.entries(t))Array.isArray(r)&&n!==`origin`&&u.push([`prop_${e}`,r,tu]);for(let[t,i,o,s]of $l){let c=new Map;for(let[e,t,n]of u)c.set(e,Math.max(c.get(e)??-1/0,s+n-nu(t,l[a[i]],l[a[o]])));for(let[i,a]of c)a>n.body&&r(`BODY`,`${i} into ${t}`,e,a,n.body)}let d=2*eu-Tc(l[a.LeftHand],l[a.LeftHandMiddle3],l[a.RightHand],l[a.RightHandMiddle3]),f=Math.max(i(`hand_l`,`hand_r`)??0,n.hands);if(d>f&&r(`SELF`,`hands overlap`,e,d,f),!o.length)continue;let p=t.objectsAt(e);for(let t of o){if(!p[t]?.half)continue;let i=ru(p[t]);for(let[a,s]of Object.entries(p)){if(o.includes(a)||!s.half||s.ignore)continue;let c=-Math.min(...i.map(e=>wc(e,s)));c>n.object&&r(`OBJECT`,`${t} into ${a}`,e,c,n.object)}}}}var au=[[/^Hips$/,`hips`],[/^(Spine|Spine1)$/,`torso_lo`],[/^Spine2$/,`torso_hi`],[/^Neck$/,`neck`],[/^Head/,`head`],[/Shoulder$/,`shoulder`],[/UpLeg$/,`thigh`],[/Leg$/,`shin`],[/(Foot|Toe)/,`foot`],[/ForeArm$/,`farm`],[/Arm$/,`uarm`],[/Hand$/,`hand`]];function ou(e,t){let n=e.names[t]??``,r=/^Left/.test(n)?`_l`:/^Right/.test(n)?`_r`:``,i=au.find(([e])=>e.test(n));return i?`${i[1]}${r}`:n}var su=[`Arm`,`ForeArm`,`Hand`].flatMap(e=>[`Left${e}`,`Right${e}`]);function cu(e,t,n,r,i){let a=Es(e);if(!a)return;let o=su.map(t=>e.index[t]);t.frames.forEach(({s:t},s)=>{for(let c of o){let o=Hs(a,e,t,c);if(o.into<0)continue;let l=ou(e,c),u=ou(e,o.into),d=Math.max(i(l,u)??0,n.skin);o.depth>d&&r(`BODY`,`${l} into ${u}`,s,o.depth,d)}})}var lu=.05,uu=new WeakMap;function du(e){let t=uu.get(e);return t||(t=Object.values(e).filter(e=>e.half&&!e.ignore).map(e=>({RT:Y(e.R),c:[e.pos[0]+e.R[0][1]*e.half[1],e.pos[1]+e.R[1][1]*e.half[1],e.pos[2]+e.R[2][1]*e.half[1]],half:e.half,up:[e.R[1][0],e.R[1][1],e.R[1][2]],r:G(e.half)})),uu.set(e,t)),t}function fu(e,t){if(Math.hypot(t[0]-e.c[0],t[2]-e.c[2])>e.r)return null;let n=J(e.RT,H(t,e.c)),r=-1/0,i=1/0;for(let t=0;t<3;t++){let a=e.up[t],o=e.half[t];if(Math.abs(a)<1e-9){if(Math.abs(n[t])>o)return null;continue}let s=(-o-n[t])/a,c=(o-n[t])/a;r=Math.max(r,Math.min(s,c)),i=Math.min(i,Math.max(s,c))}return r<=i?t[1]+i:null}function pu(e,t,n){let r=0;for(let i of du(e.objectsAt(t))){let e=fu(i,n);e!==null&&e<=n[1]+lu&&e>r&&(r=e)}return r}function mu(e,t,n){let r=kc(e.ctx.sk,e.frames[t].s,n),i={};for(let n of[`heel`,`ball`,`tip`])i[n]=pu(e,t,r[n]),r[n]=[r[n][0],r[n][1]-i[n],r[n][2]];return r.ground=i,r}var hu=[{id:`pelvis`,start:`Hips`,end:`Spine1`,mass:.142},{id:`torso`,start:`Spine1`,end:`Neck`,mass:.355},{id:`head`,start:`Neck`,end:`Head`,mass:.081},{id:`leftUpperArm`,start:`LeftArm`,end:`LeftForeArm`,mass:.028},{id:`leftForeArmHand`,start:`LeftForeArm`,end:`LeftHand`,mass:.022},{id:`rightUpperArm`,start:`RightArm`,end:`RightForeArm`,mass:.028},{id:`rightForeArmHand`,start:`RightForeArm`,end:`RightHand`,mass:.022},{id:`leftThigh`,start:`LeftUpLeg`,end:`LeftLeg`,mass:.1},{id:`leftShankFoot`,start:`LeftLeg`,end:`LeftFoot`,mass:.061},{id:`rightThigh`,start:`RightUpLeg`,end:`RightLeg`,mass:.1},{id:`rightShankFoot`,start:`RightLeg`,end:`RightFoot`,mass:.061}],gu=[`Hips`,`Spine1`,`Spine2`,`Head`];function _u(e,t){let n=e.index,r=[0,0,0],i=0;for(let{start:e,end:a,mass:o}of hu){let s=t.P[n[e]],c=t.P[n[a]];if(n[e]===void 0||n[a]===void 0||!s||!c)return null;for(let e=0;e<3;e++)r[e]+=o*(s[e]+c[e])/2;i+=o}return r.map(e=>e/i)}function vu(e,t){let n=_u(e,t);if(n)return n;let r=gu.filter(t=>e.index[t]!==void 0);return[0,1,2].map(n=>r.reduce((r,i)=>r+t.P[e.index[i]][n],0)/r.length)}var yu=(e,t,n)=>(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);function bu(e){let t=[...e].sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(t.length<3)return t;let n=e=>{let t=[];for(let n of e){for(;t.length>=2&&yu(t[t.length-2],t[t.length-1],n)<=1e-12;)t.pop();t.push(n)}return t.pop(),t};return[...n(t),...n([...t].reverse())]}function xu(e,t,n){let r=[n[0]-t[0],n[1]-t[1]],i=r[0]*r[0]+r[1]*r[1],a=i>0?Math.max(0,Math.min(1,((e[0]-t[0])*r[0]+(e[1]-t[1])*r[1])/i)):0;return[t[0]+a*r[0],t[1]+a*r[1]]}function Su(e,t){let n=bu(t),r=n[0],i=1/0;for(let t=0;t<(n.length>1?n.length:1);t++){let a=n.length>1?xu(e,n[t],n[(t+1)%n.length]):n[0],o=Math.hypot(a[0]-e[0],a[1]-e[1]);o<i&&(i=o,r=a)}return{margin:n.length>=3&&n.every((t,r)=>yu(t,n[(r+1)%n.length],e)>=0)?i:-i,near:r}}function Cu(e,t){let n=e.frames,r=n[t].s.P,i=e.ctx.sk.index,a=t>0&&t<n.length-1&&Math.hypot(n[t+1].s.P[i.Hips][0]-n[t-1].s.P[i.Hips][0],n[t+1].s.P[i.Hips][2]-n[t-1].s.P[i.Hips][2])/2>.006,o=[],s=[];for(let n of[`Left`,`Right`]){let r=mu(e,t,n);if(!(!a&&Math.min(r.heel[1],r.ball[1])>=.02))for(let e of[`heel`,`ball`,`tip`])o.push([r[e][0],r[e][2]]),s.push(r.ground[e])}if(!o.length)return`air`;let c=vu(e.ctx.sk,n[t].s),{margin:l,near:u}=Su([c[0],c[2]],o);return{margin:l,com:c,near:u,feet:o,ground:s,facing:wu(r,i)}}function wu(e,t){let n=e[t.LeftUpLeg][0]-e[t.RightUpLeg][0],r=e[t.LeftUpLeg][2]-e[t.RightUpLeg][2],i=Math.hypot(n,r)||1;return[-r/i,n/i]}function Tu(e){let t=[e.com[0]-e.near[0],e.com[2]-e.near[1]],[n,r]=e.facing,i=t[0]*n+t[1]*r,a=t[0]*r-t[1]*n,o=Math.abs(i)>=Math.abs(a)?i>=0?`ahead of`:`behind`:a>=0?`left of`:`right of`,s=Math.abs(t[0])>=Math.abs(t[1])?`${t[0]>=0?`+`:`-`}X`:`${t[1]>=0?`+`:`-`}Z`;return`${(-e.margin).toFixed(2)} m ${o} the feet (toward ${s})`}var Eu=[`Hips`,`Head`,`LeftHand`,`RightHand`,`LeftFoot`,`RightFoot`,`LeftLeg`,`RightLeg`,`LeftForeArm`,`RightForeArm`],Du=new Set([`Hips`,`Head`]),Ou=[[`knee_l`,`LeftUpLeg`,`LeftLeg`,`LeftFoot`],[`knee_r`,`RightUpLeg`,`RightLeg`,`RightFoot`],[`elbow_l`,`LeftArm`,`LeftForeArm`,`LeftHand`],[`elbow_r`,`RightArm`,`RightForeArm`,`RightHand`]],ku=2,Au=.75,ju=.05,Mu=e=>Math.round(e*100)/100;function Nu(e,t){let n=t.frames,r=n.length;return Eu.map(t=>{let i=n.map(n=>n.s.P[e.index[t]]),a=new Float64Array(r),o=new Float64Array(r),s=i.map(()=>[0,0,0]);for(let e=1;e<r;e++)a[e]=G(H(i[e],i[e-1]));for(let e=2;e<r;e++)s[e]=H(H(i[e],i[e-1]),H(i[e-1],i[e-2])),o[e]=G(s[e]);return{j:t,core:Du.has(t),v:a,a:o,A:s}})}function Pu({a:e,A:t},n){let r=0;for(let t of[n-3,n-2,n+2,n+3])t>=2&&t<e.length&&(r=Math.max(r,e[t]));let i=e[n]>0?[n-1,n+1].filter(t=>t>=2&&t<e.length).map(r=>W(t[r],t[n])/e[n]):[];return i.length?Math.max(r,Math.max(...i)+Math.min(0,...i)):r}var Fu=(e,t,n)=>e.a[t]>n&&e.a[t]>ku*Pu(e,t);function Iu(e,t,n,r){for(let i of Nu(e,t)){let e=i.core?n.accCore:n.accLimb;for(let t=2;t<i.a.length;t++)Fu(i,t,e)&&r(`POP`,`${i.j} accel ${(i.a[t]*100).toFixed(2)} cm/f^2 in one frame`,t,i.a[t],e)}}var Lu=[`hips`,`torso_lo`,`torso_hi`],Ru=.04;function zu(e,t,n){let{P:r}=e.frames[t].s,i=e.ctx.sk.index;return Sc.some(([e,t,n,a])=>Lu.includes(e)&&Math.min(r[i[t]][1],r[i[n]][1])-a<Ru)?!0:n.some(n=>{let a=e.objectsAt(t)[n.object],o=Sc.find(e=>e[0]===(n.part??`hips`));return a&&o&&Math.min(...Cc(r[i[o[1]]],r[i[o[2]]]).map(e=>wc(e,a)))-o[3]<(n.tol??.04)})}var Bu=(e,t=[])=>e.frames.map((n,r)=>zu(e,r,t)?null:Cu(e,r)),Vu=.06;function Hu(e,t){let{P:n}=e.frames[t].s,r=e.ctx.sk.index;return[`Left`,`Right`].some(i=>[`${i}Hand`,`${i}HandMiddle1`].some(i=>r[i]!==void 0&&n[r[i]][1]-pu(e,t,n[r[i]])<Vu))}function Uu(e,t=[]){let n=e.frames.length,r=[],i=e.frames.map((n,r)=>!zu(e,r,t)&&[`Left`,`Right`].every(t=>{let n=mu(e,r,t);return Math.min(n.heel[1],n.ball[1])>=.02})&&!Hu(e,r));for(let e=0;e<n;e++){if(!i[e])continue;let t=e;for(;t+1<n&&i[t+1];)t++;r.push([e,t]),e=t}return r}function Wu(e,t={}){let n=e.frames,r=n.length,i=e.ctx.sk.index,a=9.81/(e.fps??24)**2,o=e.f0??0,s=[],c=e=>n[Math.max(0,Math.min(r-1,e))].s.P[i.Hips][1];for(let[n,i]of Uu(e,t.supports)){let e=i-n+1;if(e<4)continue;let t=1-((n>0?c(n)-c(n-1):c(n+1)-c(n))-(i<r-1?c(i+1)-c(i):c(i)-c(i-1)))/e/a;if(!(t<=Au))for(let e=n;e<=i;e++)s.push({kind:`FLOAT`,msg:`no foot on the ground f${n+o}-f${i+o}, hips fall at ${Math.round(Math.max(0,1-t)*100)}% of g`,frame:e,value:+t.toFixed(4),limit:Au})}return s}var Gu=(e,t,[,n,r,i])=>ko(H(t.P[e.index[r]],t.P[e.index[n]]),H(t.P[e.index[i]],t.P[e.index[r]]));function Ku(e,t,n,r){let i=n?.limits??{},a=e=>Object.hasOwn(i,e),o=[],s=(e,t,n,r,i)=>o.push({kind:e,msg:t,frame:n,value:+r.toFixed(4),limit:i});for(let n of Nu(e,t)){let{j:e,core:t,v:i,a:o}=n,c=t?`speedCore`:`speedLimb`,l=t?`accCore`:`accLimb`;for(let t=1;t<i.length;t++)a(c)&&i[t]>r[c]&&s(`SPEED`,`${e} ${(i[t]*100).toFixed(1)} cm/frame`,t,i[t],r[c]),a(l)&&t>1&&o[t]>r[l]&&!Fu(n,t,r[l])&&s(`ACC`,`${e} accel ${(o[t]*100).toFixed(2)} cm/f^2`,t,o[t],r[l])}return a(`knee`)&&t.frames.forEach(({s:t},n)=>{for(let i of Ou.slice(0,2)){let a=Gu(e,t,i);a>r.knee&&s(`KNEE`,`${i[0]===`knee_l`?`Left`:`Right`} knee bent ${a.toFixed(0)}deg`,n,a,r.knee)}}),a(`balance`)&&Bu(t,n.supports).forEach((e,t)=>{e===`air`?s(`BALANCE`,`no foot on the ground`,t,0,0):e&&-e.margin>r.balance&&s(`BALANCE`,`centre of mass outside the feet`,t,-e.margin,r.balance)}),o}function qu(e,t,n={}){let r=t.f0??0,i=t.fps??24,a=(e,t)=>{let n=0;for(let t=1;t<e.length;t++)e[t]>e[n]&&(n=t);return[Math.round(e[n]*t*100)/100,n+r]},o=Object.fromEntries(Nu(e,t).map(({j:e,v:t,a:n})=>[e,{speed:a(t,i),accel:a(n,i*i)}]).filter(([,e])=>e.speed[0]>=ju)),s=Bu(t,n.supports).map(e=>e&&e!==`air`?e.margin:e),c=e=>{let t=s.map((t,n)=>e(t)?n+r:-1).filter(e=>e>=0);return t.length?[t[0],t[t.length-1]]:null},l=Uu(t,n.supports).slice(0,4).map(([e,t])=>[e+r,t+r]),u=null;s.forEach((e,t)=>{typeof e==`number`&&(!u||e<u[0])&&(u=[Mu(e),t+r])});let d=c(e=>typeof e==`number`&&e<0),f=Object.fromEntries(Ou.map(n=>{let i=[0,r];return t.frames.forEach(({s:t},a)=>{let o=Gu(e,t,n);o>i[0]&&(i=[o,a+r])}),[n[0],[Math.round(i[0]),i[1]]]}));return{units:`[value, frame]; speed m/s, accel m/s^2, balance m inside the feet (< 0 outside), bend deg (0 straight)`,peaks:o,balance:{min:u,...d?{outside:d}:{},...l.length?{air:l}:{}},bend:f}}function Ju(e,t,n,r){let i=e=>Object.hasOwn(n??{},e),a=new Float64Array(t.frames.length);for(let n of Nu(e,t)){let{core:e,v:t,a:o}=n,s=e?`speedCore`:`speedLimb`,c=e?`accCore`:`accLimb`;for(let e=1;e<t.length;e++)i(s)&&(a[e]=Math.max(a[e],t[e]/r[s])),!(e<2)&&(Fu(n,e,r[c])&&(a[e]=Math.max(a[e],Math.sqrt(o[e]/Math.max(r[c],ku*Pu(n,e))))),i(c)&&(a[e]=Math.max(a[e],Math.sqrt(o[e]/r[c]))))}return a}var Yu=[0,1,0],Xu=.7,Zu=.025,Qu=new Map;function $u(e,t){let n=`${e.model}:${t}`;if(Qu.has(n))return Qu.get(n);let r=Es(e),i=r?[]:null;for(let n of r?.grids??[]){if(n.b!==e.index[`${t}Foot`]&&n.b!==e.index[`${t}ToeBase`])continue;let[a,o,s]=n.dims,c=new Set;for(let e=0;e<a;e++)for(let t=0;t<o;t++)for(let a=0;a<s;a++){if(Math.abs(n.data[(e*o+t)*s+a]/1e3)>r.step/2)continue;let l=[n.min[0]+e*r.step,n.min[1]+t*r.step,n.min[2]+a*r.step],u=l.map(e=>Math.floor(e/Zu)).join();c.has(u)||(c.add(u),i.push([n.b,l]))}}return Qu.set(n,i),i}function ed(e,t,n){let r=$u(e,n);if(!r?.length){let r=kc(e,t,n),i=(e,t)=>U(V(e,t),.5);return[r.heel,i(r.heel,r.ball),r.ball,i(r.ball,r.tip),r.tip]}return r.map(([e,n])=>V(t.P[e],J(t.R[e],n)))}function td(e,t){let n={top:-1/0,side:-1/0,topAt:null,sideAt:null};for(let r of e){let e=-wc(r,t);if(e<=0)continue;let i=W(Ac(r,t),Yu)>Xu?`top`:`side`;e>n[i]&&(n[i]=e,n[`${i}At`]=r)}return n}function nd(e,t,n,r,i,a,o){for(let[s,c]of[[`Left`,`l`],[`Right`,`r`]]){let l=ed(e,t,s),u=`foot_${c}`;for(let[e,t,s,c]of r){if(l.every(e=>go(e,s)>c))continue;let r=td(l,t),d=a(u,e),f=d??i.allow,p=d??i.groundAllow;r.side>f?o(`COLLIDE`,`${u} x ${e}`,n,r.side,f):r.top>p&&o(`COLLIDE`,`${u} x ${e}`,n,r.top,p)}}}var rd={allow:.005,groundAllow:.01,reach:.01,slide:.0015,plantH:.012,speedCore:.04,speedLimb:.16,accCore:.015,accLimb:.05,flip:60,knee:150,headAllow:.003,self:0,body:.005,skin:.015,hands:.01,object:.005,grab:.03,balance:.08},id=20,ad=.01,od=(e,t,n)=>{for(let r of e??[])if(t.startsWith(r.part)&&(r.object===n||r.object.endsWith(`*`)&&n.startsWith(r.object.slice(0,-1))))return r.depth;return null};function sd(e,t,n={}){let r={...rd,...n.limits},i=[],a=e.index,o=t.frames,s=o.length,c=(e,t,n,r,a)=>i.push({kind:e,msg:t,frame:n,value:+r.toFixed(4),limit:a});for(let i=0;i<s;i++){let{s,diag:l}=o[i],u=t.objectsAt(i),d=Object.entries(u).filter(([,e])=>e.half&&!e.ignore).map(([e,t])=>[e,t,V(t.pos,J(t.R,[0,t.half[1],0])),G(t.half)]);for(let[e,t,o,l]of Sc){let u=s.P[a[t]],f=s.P[a[o]],p=U(V(u,f),.5),m=l+go(u,f)/2,h=null;for(let[t,a,o,s]of d){let d=od(n.allow,e,t)??r.allow;if(m-(go(p,o)-s)<=d)continue;h??=Cc(u,f);let g=l-Math.min(...h.map(e=>wc(e,a)));g>d&&c(`COLLIDE`,`${e} x ${t}`,i,g,d)}}nd(e,s,i,d,r,(e,t)=>od(n.allow,e,t),c);for(let t of[`Left`,`Right`]){let n=kc(e,s,t),a=Math.min(n.heel[1],n.ball[1],n.tip[1]);a<-r.groundAllow&&c(`GROUND`,`${t} sole below floor`,i,-a,r.groundAllow)}for(let[e,t]of Object.entries(l))/miss_[lr]$/.test(e)&&t>r.reach&&c(`REACH`,e,i,t,r.reach);let f=[];for(let e of[`Left`,`Right`])f.push(...Cc(s.P[a[`${e}Hand`]],s.P[a[`${e}HandMiddle3`]],5).map(t=>[`hand_${e[0].toLowerCase()}`,t,.022]));for(let[e,t]of Object.entries(l.props??{}))for(let[r,i]of Object.entries(t))Array.isArray(i)&&r!==`origin`&&!(n.mouthPoints??[]).includes(`${e}.${r}`)&&f.push([`prop_${e}`,i,.004]);for(let[t,n,a]of f){let o=Ec(e,s,n)+a;o>r.headAllow&&c(`FACE`,`${t} into head`,i,o,r.headAllow)}Tc(s.P[a.LeftLeg],s.P[a.LeftFoot],s.P[a.RightLeg],s.P[a.RightFoot])<.1+r.self&&c(`SELF`,`shins touch`,i,.1,.1),Tc(s.P[a.LeftUpLeg],s.P[a.LeftLeg],s.P[a.RightUpLeg],s.P[a.RightLeg])<.135+r.self&&c(`SELF`,`thighs overlap`,i,.135,.135);let p=K(H(s.P[a.Spine],s.P[a.Hips]))[1]<.5;for(let e of[`Left`,`Right`]){let t=s.P[a[`${e}UpLeg`]],n=s.P[a[`${e}Leg`]],r=s.P[a[`${e}Foot`]],o=ko(H(n,t),H(r,n)),l=H(s.P[a[`${e}ToeBase`]],r);if(p){let e=K(H(r,n));l=H(l,U(e,W(l,e)))}else l[1]=0;let u=H(n,[(t[0]+r[0])/2,(t[1]+r[1])/2,(t[2]+r[2])/2]);o>3&&W(u,l)<-.002&&c(`KNEE`,`${e} knee bends backward`,i,o,0),o>160+ad&&c(`KNEE`,`${e} knee folds ${o.toFixed(0)}deg`,i,o,160);let d=ko(H(s.P[a[`${e}ForeArm`]],s.P[a[`${e}Arm`]]),H(s.P[a[`${e}Hand`]],s.P[a[`${e}ForeArm`]]));d>150+ad&&c(`ELBOW`,`${e} elbow folds ${d.toFixed(0)}deg`,i,d,150)}}let l=(e,t)=>od(n.allow,e,t);iu(e,t,r,c,l),cu(e,t,r,c,l);for(let e of[`Left`,`Right`]){let n=o.map((n,r)=>mu(t,r,e));for(let t=1;t<s;t++){let i=n[t-1],a=n[t];for(let n of[`heel`,`ball`]){let o=a[n][1]<r.plantH&&i[n][1]<r.plantH&&Math.abs(a[n][1]-i[n][1])<5e-4,s=Math.hypot(a[n][0]-i[n][0],a[n][2]-i[n][2]);o&&s>r.slide&&c(`SLIDE`,`${e} ${n} slides`,t,s,r.slide)}}}for(let t=0;t<e.names.length;t++){let n=e.parent[t];if(n<0)continue;let r=go(e.restWorldPos[t],e.restWorldPos[n]),i=Math.max(...o.map(e=>Math.abs(go(e.s.P[t],e.s.P[n])-r)));i>.001&&c(`LENGTH`,`${e.names[n]}-${e.names[t]}`,0,i,.001)}return Iu(e,t,r,c),cd(e,o,r,c),i}function cd(e,t,n,r){let i=e.index,a=Math.sin(id*Math.PI/180);for(let e of[`Left`,`Right`])for(let[o,s,c]of[[`${e}UpLeg`,`${e}Leg`,`${e}Foot`],[`${e}Arm`,`${e}ForeArm`,`${e}Hand`]]){let e=null,l=0;for(let u=0;u<t.length;u++){let d=t[u].s.P,f=H(d[i[s]],d[i[o]]),p=H(d[i[c]],d[i[s]]),m=ho(f,p);if(G(m)<a*G(f)*G(p))continue;let h=K(m),g=e?ko(h,e):0,_=u-l;g/_>n.flip&&r(`FLIP`,`${s} bend plane jumps ${g.toFixed(0)}deg${_>1?` over ${_} frames`:``}`,u,g/_,n.flip),e=h,l=u}}}function ld(e,t){let n=Math.max(0,Math.min(e.frames-1,t))*e.names.length,r=t=>{let r=e.names.indexOf(t),i=(n+r)*3;return[e.P[i],e.P[i+1],e.P[i+2]]};return Sc.map(([e,t,n,i])=>[e,r(t),r(n),i])}function ud(e,t,n={}){let r=Object.entries(t.ctx?.scene?.people??{}),i=[];if(!r.length)return i;let a=e.index,o=t.f0??0,s={...rd,...n.limits}.allow;return t.frames.forEach(({s:e},t)=>{let c=t+o,l=Sc.map(([t,n,r,i])=>[t,e.P[a[n]],e.P[a[r]],i]);for(let[o,u]of r){if(!Sc.every(([,e,t])=>u.names.includes(e)&&u.names.includes(t)))continue;let r=ld(u,c),d=r.find(e=>e[0]===`hips`)[1];if(!(go(e.P[a.Hips],d)>2.2))for(let[e,a,c,u]of l){let l=Math.max(...r.map(([,e,t,n])=>u+n-Tc(a,c,e,t))),d=od(n.allow,e,`person:${o}`)??s;l>d&&i.push({kind:`PERSON`,msg:`${e} x person:${o}`,frame:t,value:+l.toFixed(4),limit:d})}}}),i}var dd=new WeakMap,fd=e=>Math.round(e*1e5)/1e5;function pd(e,t){let n=JSON.stringify(t),r=dd.get(e);if(r?.key===n)return r.value;let i=Ql(e.rig),a=e.bones.length,o=e.frameCount,s=i.names,c=s.length,l=s.map(t=>e.bones.indexOf(t)),u=X(t.yaw),d=new Float64Array(o*c*3);for(let n=0;n<o;n++){let r=Fo(i,l.map(t=>t<0?[0,0,0,1]:Array.from(e.rot.subarray((n*a+t)*4,(n*a+t)*4+4))),Array.from(e.hips.subarray(n*3,n*3+3)));for(let e=0;e<c;e++)d.set(V(t.position,J(u,r.P[e])).map(fd),(n*c+e)*3)}let f={rig:e.rig,frames:o,names:s,P:d};return dd.set(e,{key:n,value:f}),f}function md(e,t,n){let r={};for(let i of e??[]){if(!i||i.id===t||i.hidden)continue;let e=n(i.id);e?.schema!==`cozyclay.take.v3`||!e.frameCount||!Ql(e.rig)||(r[i.id]={name:i.subject||i.name||i.id,...pd(e,{position:[i.x??0,i.y??0,i.z??0],yaw:i.rot??0})})}return r}function hd(e,t,n,r){let i=e?.people?.[t];if(!i)return null;let a=i.names.indexOf(Bl(Ql(i.rig),n).bone??``);if(a<0)return null;let o=(Math.max(0,Math.min(i.frames-1,Math.round(r)))*i.names.length+a)*3;return[i.P[o],i.P[o+1],i.P[o+2]]}var gd=e=>Object.entries(e?.people??{}).map(([e,t])=>`${e} (${t.name})`).join(`, `)||`none: no other character has an installed take`;function _d(e,t,n){let r=new Map,i=(t,n)=>{let i=e?.people?.[t],a=i&&Bl(Ql(i.rig),n).bone;a&&r.set(t,new Set([...r.get(t)??[],a]))},a=(e,t)=>{if(typeof e==`string`){let n=/^person:([^.]+)(?:\.(.+))?$/.exec(e);n&&(n[2]||t===`from`)&&i(n[1],n[2]??`Hips`)}else if(Array.isArray(e))e.forEach(e=>a(e));else if(e&&typeof e==`object`){e.kind===`person`&&i(e.person,e.bone);for(let[t,n]of Object.entries(e))a(n,t)}};if(a(t),n?.fixed?.person?.frames>0){let t=n.ctx.sk.index.Hips,r=n.f0??0,a=Sc.flatMap(([,e,t])=>[e,t]);for(let[o,s]of Object.entries(e?.people??{})){let e=s.names.indexOf(Sc.find(e=>e[0]===`hips`)[1]),c=s.names.length;if(e>=0&&n.frames.some(({s:n},i)=>{let a=(Math.max(0,Math.min(s.frames-1,i+r))*c+e)*3,o=n.P[t];return Math.hypot(o[0]-s.P[a],o[1]-s.P[a+1],o[2]-s.P[a+2])<=2.2}))for(let e of a)s.names.includes(e)&&i(o,e)}}return r.size?Object.fromEntries([...r].map(([t,n])=>{let r=e.people[t],i=[...n],a=r.names.length,o=[];for(let e=0;e<r.frames;e++)for(let t of i){let n=(e*a+r.names.indexOf(t))*3;o.push(r.P[n],r.P[n+1],r.P[n+2])}return[t,{name:r.name,rig:r.rig,frames:r.frames,names:i,P:o}]})):null}var vd=.045,yd=[[1,0,0],[0,1,0],[0,0,1]],bd=(e,t)=>H(e,U(t,W(e,t)));function xd(e){if(!e)return-1;let t=[0,1,2].reduce((t,n)=>e[n]>e[t]?n:t,0);return[0,1,2].filter(e=>e!==t).every(t=>e[t]<vd)?t:-1}var Sd=(e,t)=>e===`cylinder`&&!!t&&t[1]<vd&&Math.min(t[0],t[2])>=vd&&Math.abs(t[0]-t[2])<.1*t[0],Cd=(e,t)=>e?.objects?.[t]?.grasp??e?.others?.[t]?.grasp??null;function wd(e,t){let n=[],r=(t,r)=>Object.entries(Cd(e,t)??{}).forEach(([e,i])=>n.push({...i,name:r+e,owner:t}));r(t,``);for(let i of sg(e,t)){i!==t&&r(i,`${i}.`);let{half:a,renderer:o}=e.objects[i],s=xd(a);s>=0?n.push({name:i,owner:i,at:[0,a[1],0],axis:yd[s],radius:Math.min(...a.filter((e,t)=>t!==s))}):Sd(o,a)&&n.push({name:i,owner:i,at:[0,a[1],0],rim:a[0],normal:yd[1]})}return n}var Td=(e,t,n)=>wd(e,t).find(e=>e.name===n);function Ed(e,t){let n=e=>e?K(J(t.R,e)):void 0;return{p:V(t.pos,J(t.R,e.at??[0,0,0])),axis:n(e.axis),from:n(e.from),thumb:n(e.thumb),radius:e.radius,...e.rim?{rim:e.rim,normal:n(e.normal)}:{}}}function Dd(e,t){let n=bd(H(t,e.p),e.normal),r=G(n)>1e-6?K(n):K(bd(Math.abs(e.normal[1])<.9?[0,1,0]:[1,0,0],e.normal));return{p:V(e.p,U(r,e.rim)),axis:K(ho(e.normal,r))}}function Od(e,t){let n;for(let r of e){let e=J(Y(r.R),H(t,V(r.pos,J(r.R,[0,r.half[1],0])))),i=[0,1,2].map(t=>Math.abs(e[t])-r.half[t]),a=[0,1,2].reduce((e,t)=>i[t]>i[e]?t:e,0),o=Math.max(...i);(!n||o<n.gap)&&(n={gap:o,n:U([r.R[0][a],r.R[1][a],r.R[2][a]],e[a]<0?-1:1)})}return n?.n}function kd(e,t){let n=H(t,e.p);return e.rim?Math.hypot(W(n,e.normal),G(bd(n,e.normal))-e.rim):G(e.axis?bd(n,e.axis):n)}function Ad(e,t,n,r,i=0){let a=e===`Right`,o=e=>a?e:U(e,-1);if(t.axis&&n!==`palm`&&!(t.from&&G(bd(t.axis,t.from))<.001)){if(t.from){let e=o(t.from),n=K(bd(t.axis,e)),i=n=>t.thumb?W(n,t.thumb):W(ho(n,e),r),a=i(n)>=i(U(n,-1))?n:U(n,-1);return Md(ho(a,e),a,e)}let e=jd(r,t.axis),n=J(X(i),[a?1:-1,0,0]),s=Math.abs(e[1]),c=t.thumb??bd(V(U([0,1,0],1-s),U(n,s)),e),l=K(bd(t.axis,e)),u=W(l,c)>=0?l:U(l,-1);return Md(e,u,ho(e,u))}let s=o(t.from??U(r,-1)),c=jd(r,s);return Md(c,ho(s,c),s)}function jd(e,t){let n=bd(e,t);return K(G(n)>.001?n:bd(Math.abs(t[1])<.9?[0,1,0]:[1,0,0],t))}var Md=(e,t,n)=>[[e[0],t[0],n[0]],[e[1],t[1],n[1]],[e[2],t[2],n[2]]];function Nd(e,t){let n=n_[t],r=e.restWorldPos,i=e.index;return G(H(r[i[`${n}ForeArm`]],r[i[`${n}Arm`]]))+G(H(r[i[`${n}Hand`]],r[i[`${n}ForeArm`]]))}var Pd=new Set([`body`]);function Fd(e,t,n,r,i,a){let o=e.spec.anchors?.[t];if(!o)throw Error(`MOTION_SPEC_INVALID: unknown anchor "${t}"`);let s=Vd(e,o,t,n,r,i,a),c=Pd.has(o.kind)&&e.keepOut;return c?Rs(c.body,e.sk,n,Rs(c.body,e.sk,n,s,zs,c.skip),zs,c.skip):s}var Id=[`r`,`l`],Ld={l:`left`,r:`right`};function Rd(e,t,n,{s:r,diag:i,c:a},o){let s=i.frame,c=()=>e.restingAt?.(t.object,s)??e.objectsAt(s)[t.object]??Jl(e.scene)[t.object],l=e.objectPose&&s!==void 0?e.objectHand(t.object,s):null;if(o&&l&&Id.indexOf(l)>Id.indexOf(o))throw Error(`MOTION_SPEC_INVALID: anchor "${n}" is on "${t.object}", which the ${Ld[l]} hand holds at f${s}; the right arm is solved before the left, so the right hand cannot follow it. Carry "${t.object}" in the right hand (a right-hand prop) and put the left hand on it, or give the right hand another anchor`);let u=!e.objectPose||s===void 0||l===o?c():Bd(e,n,t.object,s,()=>e.objectPose(t.object,s,{s:r,diag:i,c:a}));if(!u)throw Error(`MOTION_SPEC_INVALID: anchor "${n}" names unknown object "${t.object}"`);return u}var zd=16;function Bd(e,t,n,r,i){if((e.nest??0)>=zd)throw Error(`MOTION_SPEC_INVALID: anchor "${t}" on "${n}" at f${r} reads a pose that needs this frame solved again (an anchor and carry loop); anchor the hand on a point that does not ride on the hand it moves`);e.nest=(e.nest??0)+1;try{return i()}finally{e.nest--}}function Vd(e,t,n,r,i,a,o){let{sk:s}=e,c=s.index;switch(t.kind){case`world`:return t.p.slice();case`body`:return V(a.root??r.P[c.Hips],J(X(a.yaw??0),t.p));case`bone`:return V(r.P[c[t.bone]],t.offset??[0,0,0]);case`segment`:{let e=r.P[c[t.from]],n=r.P[c[t.to]],i=t.offset??[0,0,0],a=t=>V(V(e,U(H(n,e),t)),i);if(!t.reach)return a(t.t??.5);let o=r.P[c[`${n_[t.reach]}Arm`]],l=.95*Nd(s,t.reach);for(let e=t.t??.45;e>=(t.tMin??.15);e-=.01)if(G(H(a(e),o))<=l)return a(e);return a(t.tMin??.15)}case`object`:{if(t.grasp&&t.local===void 0)return Ud(e,n,r,i,a,o).p;let s=Rd(e,t,n,{s:r,diag:i,c:a},o);return V(s.pos,J(s.R,t.local??[0,0,0]))}case`landmark`:return Io(r,c.Head,s.landmarks[t.name]??(()=>{throw Error(`MOTION_SPEC_INVALID: unknown landmark "${t.name}"`)})());case`prop`:{let r=Hd(e,t,n,i?.frame)??i.props?.[t.prop]?.[t.point];if(!r)throw Error(`MOTION_SPEC_INVALID: anchor "${n}" needs prop ${t.prop}.${t.point}, which is held by an arm solved later`);return V(r,t.offset??[0,0,0])}case`person`:{let r=hd(e.scene,t.person,t.bone,i?.frame??0);if(!r)throw Error(`MOTION_SPEC_INVALID: anchor "${n}" names person "${t.person}" bone "${t.bone}", which the scene does not have (people: ${gd(e.scene)})`);return V(r,t.offset??[0,0,0])}default:throw Error(`MOTION_SPEC_INVALID: anchor "${n}" has unknown kind "${t.kind}"`)}}function Hd(e,t,n,r){let i=e.spec.props?.[t.prop]?.hand;if(!i||r===void 0||!e.solvedAt||!e.carrySpan)return null;let a=null;for(let[t,n]of Object.entries(e.spec.objects??{})){if(!b_(n)||e.spec.props?.[n.prop]?.hand!==i)continue;let[o,s]=e.carrySpan(n);if(r>=o&&r<=s)return null;let c=r<o?o:s;(!a||Math.abs(r-c)<Math.abs(r-a.at))&&(a={id:t,at:c})}if(!a)return null;let o=Bd(e,n,a.id,a.at,()=>e.solvedAt(a.at).diag.props?.[t.prop]?.[t.point]),s=e.objectPose(a.id,a.at),c=e.objectPose(a.id,r);return o&&s&&c?V(c.pos,J(c.R,J(Y(s.R),H(o,s.pos)))):null}function Ud(e,t,n,r,i,a){let o=e.spec.anchors[t],s={s:n,diag:r,c:i},c=n=>Rd(e,{...o,object:n},t,s,a),l=o.local&&(e=>V(e.pos,J(e.R,o.local)))(c(o.object));if(e.sockets??=new Map,!e.sockets.has(t)){let r=wd(e.scene,o.object),i=e.sk.index,s=l??n.P[i[a?`${n_[a]}Arm`:`Hips`]],u=o.socket?Td(e.scene,o.object,o.socket):r.map(e=>({k:e,d:kd(Ed(e,c(e.owner)),s)})).sort((e,t)=>e.d-t.d)[0]?.k;e.sockets.set(t,u??null)}let u=e.sockets.get(t),d=u?Ed(u,c(u.owner)):{p:l??c(o.object).pos};if(u?.rim)d=Wd(e,t,a,u,c(u.owner),d,l??n.P[e.sk.index[a?`${n_[a]}Arm`:`Hips`]]);else if(l)d.p=l;else if(d.axis&&d.radius>0){let t=Math.abs(Jc[o.grasp]?.[2]??0),r=d.radius-t,i=n.P[e.sk.index[`${n_[a]??`Right`}Arm`]],s=H(i,d.p),c=H(s,U(d.axis,W(s,d.axis)));r>1e-4&&G(c)>1e-6&&(d.p=V(d.p,U(K(c),r)))}return!d.axis&&!d.from&&(d.from=Od(sg(e.scene,o.object).map(t=>({...c(t),half:e.scene.objects[t].half})),d.p)),d}function Wd(e,t,n,r,i,a,o){e.rims??=new Map;let s=(n?null:[...e.rims.keys()].find(e=>e.startsWith(`${t}|`)&&!e.endsWith(`|`)))??`${t}|${n??``}`;if(!e.rims.has(s)){let t=Dd(a,o),n=e=>J(Y(i.R),e);e.rims.set(s,{at:n(H(t.p,i.pos)),axis:n(t.axis)})}return Ed(e.rims.get(s),i)}function Gd(e,t,n,r){let{sk:i}=e;for(let[a,o]of Object.entries(e.spec.props??{})){if(o.hand!==t)continue;let e=Xo(i,n,n_[t]),s=U(o.origin.map(e=>n.P[i.index[e]]).reduce((e,t)=>V(e,t),[0,0,0]),1/o.origin.length),c={};for(let[t,[n,r,i]]of Object.entries(o.points??{}))c[t]=V(s,V(U(e.d,n),V(U(e.l,r),U(e.n,i))));c.origin=s,c.axes=e,(r.props??={})[a]=c}}var Kd={joint:`joint:<Bone>`,bone:`bone:<Bone>`,prop:`prop:<prop>.<point>`,anchor:`anchor:<name>`,landmark:`landmark:mouth`,object:`object:<id>[.center|.top|.base|.rim]`,person:`person:<id>.<Bone>`};function qd(e){let t=/^([a-z]+):(.+)$/s.exec(String(e));if(!t)return null;let[,n,r]=t;if(n===`prop`){let[e,t]=r.split(`.`);return{kind:n,name:e,point:t??``}}if(n===`object`){let e=/^(.+)\.(center|top|base|rim)$/s.exec(r);return{kind:n,name:e?e[1]:r,point:e?e[2]:null}}if(n===`person`){let e=r.lastIndexOf(`.`);return{kind:n,name:e>0?r.slice(0,e):r,point:e>0?r.slice(e+1):``}}return{kind:n,name:r,point:null}}function Jd(e,t){let n=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];for(let t of e)for(let e of[-1,1])for(let i of[0,2])for(let a of[-1,1]){let o=V(t.pos,J(t.R,[e*t.half[0],i*t.half[1],a*t.half[2]]));for(let e=0;e<3;e++)n[e]=Math.min(n[e],o[e]),r[e]=Math.max(r[e],o[e])}let i=[(n[0]+r[0])/2,(n[1]+r[1])/2,(n[2]+r[2])/2];return t===`top`?[i[0],r[1],i[2]]:t===`base`?[i[0],n[1],i[2]]:i}function Yd(e){let t=(e??[]).map(e=>({o:V(e.pos,J(e.R,[0,2*e.half[1],0])),n:[e.R[0][1],e.R[1][1],e.R[2][1]],r:Math.min(e.half[0],e.half[2])}));return t.length?t.reduce((e,t)=>t.o[1]>e.o[1]?t:e):null}function Xd(e,t){let n=H(t,e.o),r=n[0]*e.n[0]+n[1]*e.n[1]+n[2]*e.n[2],i=H(n,e.n.map(e=>e*r)),a=G(i);return a>1e-6?V(e.o,i.map(t=>t*e.r/a)):e.o}function Zd(e,t,n){let r=e.frames?.[t-(e.f0??0)],i=qd(n);if(!r||!i)return null;let{s:a,diag:o,c:s}=r,c=e.ctx.sk;switch(i.kind){case`joint`:case`bone`:{let{bone:e}=Bl(c,i.name);return e?a.P[c.index[e]].slice():null}case`prop`:{let e=o.props?.[i.name]?.[i.point];return Array.isArray(e)?e.slice():null}case`anchor`:return e.ctx.spec.anchors?.[i.name]?Fd(e.ctx,i.name,a,{...o,frame:t},s):null;case`landmark`:return c.landmarks?.[i.name]?Io(a,c.index.Head,c.landmarks[i.name]):null;case`object`:{let n=Dg(e,i.name,t);return n?i.point===`rim`?Yd(n).o.slice():Jd(n,i.point):null}case`person`:return hd(e.ctx.scene,i.name,i.point,t);default:return null}}function Qd(e,t,n,r){let i=e=>{let t=qd(e);return t?.kind===`object`&&t.point===null?t:null},a=i(r)?[n,i(r)]:i(n)?[r,i(n)]:null;if(a){let n=Zd(e,t,a[0]),r=Dg(e,a[1].name,t);return n&&r?Math.max(0,Math.min(...r.map(e=>wc(n,e)))):null}let o=[n,r].map(e=>{let t=qd(e);return t?.kind===`object`&&t.point===`rim`?t:null});if(o[0]||o[1]){let[i,a]=o[0]?[o[0],r]:[o[1],n],s=Zd(e,t,a),c=Yd(Dg(e,i.name,t));return s&&c?G(H(s,Xd(c,s))):null}let s=Zd(e,t,n),c=Zd(e,t,r);return s&&c?G(H(s,c)):null}function $d(e,{sk:t,scene:n},r,i=Ml){if(typeof r!=`string`||!r)return[];let a=r.replace(/\.(center|top|base|rim)$/,``),[o,s]=r.split(`.`),c=t&&(i.includes(`joint`)||i.includes(`bone`))?Bl(t,r).bone:null;return[i.includes(`object`)&&(n?.objects?.[a]||sg(n,a).length)&&`object:${r}`,c&&`${i.includes(`joint`)?`joint`:`bone`}:${c}`,i.includes(`anchor`)&&e.anchors?.[r]&&`anchor:${r}`,i.includes(`prop`)&&e.props?.[o]&&(s===`origin`||e.props[o].points?.[s])&&`prop:${r}`,i.includes(`landmark`)&&r===`mouth`&&`landmark:mouth`].filter(Boolean)}function ef(e,t,n,r){let i=$d(e,t,n,r);return i.length?`; did you mean ${i.map(e=>`"${e}"`).join(` or `)}?`:``}function tf(e,t,{sk:n,scene:r},i,a,o=Ml){let s=qd(a),c=`${i} "${a}"`;if(!s||!o.includes(s.kind))return t(`${c} must be ${o.map(e=>Kd[e]).join(`, `)}${s?``:ef(e,{sk:n,scene:r},a,o)}`),!1;if(s.kind===`joint`||s.kind===`bone`){let{bone:e,hint:r}=n?Bl(n,s.name):{bone:s.name};return e||t(`${c}: unknown bone${r}`),!!e}if(s.kind===`prop`){let n=!!(e.props?.[s.name]&&(s.point===`origin`||e.props[s.name].points?.[s.point]));return n||t(`${c}: spec.props has no point ${s.name}.${s.point}`),n}if(s.kind===`anchor`)return e.anchors?.[s.name]||t(`${c}: no anchor "${s.name}" in spec.anchors${il(s.name,Object.keys(e.anchors??{}))}`),!!e.anchors?.[s.name];if(s.kind===`landmark`)return s.name!==`mouth`&&t(`${c}: the only landmark is "mouth"`),s.name===`mouth`;if(s.kind===`person`){let e=!!hd(r,s.name,s.point,0);return e||t(`${c}: no person "${s.name}" with joint "${s.point}" (people with an installed take: ${gd(r)})`),e}return Hl(t,r,c,s.name,{groups:!0})}var nf=[0,1,0];function rf(e,t,n=`up`,r){if(Array.isArray(n))return K(n);if(n===`face`){let{sk:n}=e.ctx;return K(Lo(n,e.frames[t-(e.f0??0)].s,n.index.Head,[0,0,1]))}let i=n===`up`?null:Zd(e,t,n),a=i?H(i,r):nf;return G(a)>1e-9?K(a):nf}function af(e,t,n){let r=e.f0??0,i=Math.max(r,Math.min(r+e.frames.length-1,n)),a=Zd(e,i,t.follow);if(!a)return null;let o=Oo(ms(nf,rf(e,i,t.aim,a)));return{pos:V(a,J(o,t.offset??[0,0,0])),R:o}}var of={spine:1,chest:2.5,head:3.5,aswing:3,abend:5,wrist:9.5,hand:0},sf=6,cf=6,lf=24,uf=[1.5,3],df=.5,ff=.2,pf=.15,mf={frames:8,min:6,frac:.08,max:3},hf=/^(aswing|abend|wflex)_[lr]$/,gf=/^use\[\d+\] (?!standIdle$)|\bwalk(To)? (start|step \d+|end)$/,_f=e=>gf.test(e?.src??``);function vf(e){let t=/^(spine|chest|head)_(yaw|pitch|roll)$|^(aswing|abend|wflex|wtwist)_[lr]$|^(hand|armw|elbow)_[lr]$/.exec(e);return t?t[1]??(t[4]?`hand`:t[3]===`wflex`||t[3]===`wtwist`?`wrist`:t[3]):null}function yf(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);let n=Math.imul(t>>>0^t>>>0>>>15,t>>>0|1);return n^=n+Math.imul(n^n>>>7,n|61),((n^n>>>14)>>>0)/4294967296*2-1}function bf(e,t,n){let r=e.length;for(let e=1;e<r;e++)t[e]=Math.min(t[e],t[e-1]+n(e-1));for(let e=r-2;e>=0;e--)t[e]=Math.min(t[e],t[e+1]+n(e));return t.some(e=>e>0)?{max:Math.max(...t),at(n){if(n<=e[0])return t[0];if(n>=e[r-1])return t[r-1];let i=0;for(;n>e[i+1];)i++;return t[i]+(t[i+1]-t[i])*(n-e[i])/(e[i+1]-e[i])}}:null}function xf(e,t,n,r,i=null){let a=vf(e);if(!a||!of[a]||!(n>0)||t.length<2)return null;let o=t.map(e=>e.f),s=o.length;return bf(o,o.map((e,r)=>_f(t[r])||_f(t[r+1])||i&&[o[r-1],e,o[r+1]].some(e=>e!==void 0&&i[e]<2)?0:of[a]*Math.min(1,(r<s-1?o[r+1]-e:lf)/lf)*n),e=>(t[e].value===t[e+1].value?df:ff)*(o[e+1]-o[e]))}function Sf(e,t,n,r,i=null){let a=new Map,o=[],s=(e,t)=>JSON.stringify(e)===JSON.stringify(t);for(let t of e){for(let e of t)(!a.has(e.f)||_f(e))&&a.set(e.f,e);for(let e=1;e<t.length;e++)s(t[e-1].value,t[e].value)||o.push([t[e-1].f,t[e].f,t.weight])}let c=[...a.values()].sort((e,t)=>e.f-t.f);if(!(n>0)||c.length<2)return null;let l=c.map(e=>e.f),u=l.length,d=l.map((e,a)=>{if(e===0||_f(c[a])||_f(c[a+1])||i&&[l[a-1],e,l[a+1]].some(e=>e!==void 0&&i[e]<2))return 0;let o=yf(`${r}|${e}`),s=Math.min(a<u-1?l[a+1]-e:lf,a>0?e-l[a-1]:lf);return(o<0?`l`:`r`)!==t||s<cf?0:Math.min(uf[0]+(uf[1]-uf[0])*Math.abs(o),s/3)*Math.min(1,n)}),f=e=>o.filter(([t,n])=>t<l[e+1]&&n>l[e]),p=e=>l[e+1]-l[e];return bf(l,d,e=>(f(e).length?f(e).some(e=>e[2])?0:pf:df)*p(e))}var Cf=e=>e<=0||e>=1?0:64*(e*(1-e))**3;function wf(e,t,n,r,i,a=()=>!0){if(!hf.test(e)||!(r>0))return null;let o=[],s=t.map(e=>e.f);for(let c=1;c<s.length;c++){let l=n[c]-n[c-1],u=s[c+1];if(Math.abs(l)<1||_f(t[c])||_f(t[c-1])||u!==void 0&&n[c+1]!==n[c])continue;let d=Math.min(mf.frames,.5*(s[c]-s[c-1]),u===void 0?1/0:.5*(u-s[c])),f=Math.sign(l)*Math.min(mf.max*(d/mf.frames)**2,mf.frac*Math.abs(l))*Math.min(1,r);/^abend/.test(e)&&n[c]+f<0&&(f=Math.min(0,-n[c])),d>=mf.min&&Math.abs(f)>.001&&s[c]+.75*d<=i&&a(s[c]-d/4,s[c]+.75*d)&&o.push([s[c]-d/4,d,f])}return o.length?e=>{let t=0;for(let[n,r,i]of o)t+=i*Cf((e-n)/r);return t}:null}function Tf(e,t){let n=Array(t).fill(1/0);for(let r=0,i=-1/0;r<t;r++)e.some(e=>e[r]>.001)&&(i=r),n[r]=r-i;for(let r=t-1,i=1/0;r>=0;r--)e.some(e=>e[r]>.001)&&(i=r),n[r]=Math.min(n[r],i-r);return n}function Ef(e){let t={l:[],r:[]},n=Math.round(e?.frames??0);for(let r of Object.values(e?.objects??{})){let i=e.props?.[r?.prop]?.hand;Number.isFinite(r?.grab)&&t[i]&&t[i].push([r.grab,Number.isFinite(r.release)?r.release:n])}for(let n of e?.goals??[]){let e=Array.isArray(n?.at)?n.at:null;if(e?.length&&[`near`,`above`,`still`].some(e=>n[e]!==void 0)&&/hand/i.test(JSON.stringify(n)))for(let n of[`l`,`r`])t[n].push([e[0],e[e.length-1]])}return t}function Df(e,t,n,r=sf){let i=new Uint8Array(n);for(let[t,r]of e)for(let e=Math.max(0,Math.floor(t));e<=Math.min(n-1,Math.ceil(r));e++)i[e]=1;for(let e of t)for(let t=0;t<n;t++)e[t]>.001&&(i[t]=1);return Tf([i],n).map(e=>Math.max(0,e-r))}function Of(e,t){let n=t.length,r=Array(n).fill(0);for(let i=1;i<n-1;i++){let n=e[i]-e[i-1],a=e[i+1]-e[i],o=(t[i]-t[i-1])/n,s=(t[i+1]-t[i])/a;if(o*s>0){let e=2*a+n,t=a+2*n;r[i]=(e+t)/(e/o+t/s)}}return r}function kf(e,t,n,r){if(e.length===1||r<=e[0])return t[0];if(r>=e[e.length-1])return t[t.length-1];let i=0;for(;r>e[i+1];)i++;let a=e[i+1]-e[i],o=(r-e[i])/a,s=o*o,c=s*o;return(2*c-3*s+1)*t[i]+(c-2*s+o)*a*n[i]+(-2*c+3*s)*t[i+1]+(c-s)*a*n[i+1]}var Af=/^(spine|chest|head)_(yaw|pitch|roll)$|^(aswing|abend)_[lr]$/,jf={spine:0,head:2,arms:3},Mf=5,Nf=/^(hand|armw|elbow|aswing|abend|wflex|wtwist)_[lr]$/,Pf=.15,Ff=6,If=e=>/^(spine|chest|head)_/.test(e)?[`l`,`r`]:/^(aswing|abend|wflex|wtwist)_([lr])$/.test(e)?[e.slice(-1)]:[],Lf=e=>/^(spine|chest)_/.test(e)?`spine`:/^head_/.test(e)?`head`:/^(aswing|abend)_[lr]$/.test(e)?`arms`:null;function Rf(e,t=``,n={l:[],r:[]}){if(e===!1)return{smooth:!1,lag:{spine:0,head:0,arms:0},overlap:0,headLead:0,seed:t,hands:n};let r=e??{},i=r.lag===!1?0:r.lag,a=typeof i==`number`?{spine:i,head:i,arms:i}:{...jf,...i??{}},o=r.overlap===!1?0:typeof r.overlap==`number`?r.overlap:1,s=r.headLead===!1?0:typeof r.headLead==`number`?Math.round(r.headLead):Mf;return{smooth:r.smooth!==!1,lag:a,overlap:o,headLead:s,seed:t,hands:n}}function zf(e,t){let n=t.length,r=Array(n).fill(0);for(let i=1;i<n-1;i++)t[i]!==t[i-1]&&t[i]!==t[i+1]&&(r[i]=(t[i+1]-t[i-1])/(e[i+1]-e[i-1]));for(let i=0;i<n-1;i++){let n=e[i+1]-e[i],a=Math.min(t[i],t[i+1]),o=Math.max(t[i],t[i+1]),s=Math.min(Ff,Pf*(o-a));for(let c=0;c<12;c++){let c=0;for(let s=1;s<16;s++){let l=kf([e[i],e[i+1]],[t[i],t[i+1]],[r[i],r[i+1]],e[i]+n*s/16);c=Math.max(c,l-o,a-l)}if(c<=s+1e-9)break;r[i]*=.7,r[i+1]*=.7}}return r}var Bf=e=>Array.isArray(e)?`vec`:e&&typeof e==`object`?`map`:`num`;function Vf(e,t,n=Rf()){let r=new Map;for(let t of[...e].sort((e,t)=>e.f-t.f))for(let[e,n]of Object.entries(t.set??{}))r.has(e)||r.set(e,[]),r.get(e).push({f:t.f,value:n,step:t.step?.includes(e),src:t.src});let i=n.overlap??0,a=[...r];if(i>0)for(let[e,t]of r)/^spine_/.test(e)&&a.push([e.replace(`spine`,`chest`),t]);let o=new Map,s=new Map,c={},l={};if(i>0){for(let[e,t]of a)/^w_.+_[lr]$/.test(e)&&o.set(e,p(e,t));for(let e of[`l`,`r`])c[e]=Df(n.hands?.[e]??[],[...o].filter(([t])=>t.endsWith(`_${e}`)).map(([,e])=>e.frames),t);for(let e of[`l`,`r`])l[e]=Sf([...r].filter(([t])=>Nf.test(t)&&t.endsWith(`_${e}`)).map(([e,t])=>Object.assign([...t],{weight:/^armw_/.test(e)})),e,i,n.seed??``,c[e]);for(let[e,t]of a)/^armw_[lr]$/.test(e)&&o.set(e,p(e,t))}let u=e=>{let n=If(e).filter(e=>o.has(`armw_${e}`)),r=n.join(``);return n.length?(s.has(r)||s.set(r,Tf(n.map(e=>o.get(`armw_${e}`).frames),t)),s.get(r)):null},d={},f={};for(let[e,t]of a){let n=o.get(e)??p(e,t,u(e));d[e]=n.frames,n.plain&&(f[e]=n.plain)}for(let[e,t]of Object.entries(f)){let n=If(e).map(e=>d[`armw_${e}`]).filter(Boolean);n.length&&(d[e]=d[e].map((e,r)=>{let i=Math.min(1,4*Math.max(0,...n.map(e=>e[r])));return e+(t[r]-e)*i*(2-i)}))}return d;function p(e,r,a=null){let o=[...new Map(r.map(e=>[e.f,e])).values()],s=Bf(o[0].value),c=s===`vec`?o[0].value.length:0,u=s===`num`?[o.map(e=>e.value)]:s===`vec`?Array.from({length:c},(e,t)=>o.map(e=>e.value[t])):[...new Set(o.flatMap(e=>Object.keys(e.value)))].map(e=>({name:e,y:o.map(t=>t.value[e]??0)})),d=o.map(e=>e.f),f=n.smooth&&Af.test(e),p=n.lag[Lf(e)]??0,m=s===`num`?xf(e,o,i,n.seed??``,a):null,h=Nf.test(e)?l[e.slice(-1)]:null,g=p+(m?.max??0),_=e=>m?Math.min(m.at(e),a?df*a[Math.round(e)]:1/0):0,v=(e,n)=>Math.min(1,(t-1-e)/(2*n)),y=e=>h?e-h.at(e)*v(e,h.max):e,b=e=>y(e)-(g>0?(p+_(e))*v(e,g):0),x=(e,n)=>{if(!a)return!0;for(let r=Math.max(0,Math.floor(e));r<=Math.min(t-1,Math.ceil(n+g));r++)if(a[r]<2)return!1;return!0},S=(n,r=!0)=>{let a=f&&r?zf(d,n):Of(d,n),c=r&&s===`num`?wf(e,o,n,i,t-1,x):null;return e=>{let t=r?b(e):y(e);for(let e=1;e<o.length;e++)if(o[e].step&&t>=d[e-1]&&t<d[e])return n[e-1];return kf(d,n,a,t)+(c?c(t):0)}},C=Array(t);if(s===`num`){let e=S(u[0]);for(let n=0;n<t;n++)C[n]=e(n)}else if(s===`vec`){let e=u.map(S);for(let n=0;n<t;n++)C[n]=e.map(e=>e(n))}else{let e=u.map(({name:e,y:t})=>[e,S(t)]);for(let n=0;n<t;n++)C[n]=Object.fromEntries(e.map(([e,t])=>[e,t(n)]))}if(!(s===`num`&&(f||g>0)&&If(e).length))return{frames:C};let w=S(u[0],!1);return{frames:C,plain:Array.from({length:t},(e,t)=>w(t))}}}var Hf=(e,t)=>Object.fromEntries(Object.entries(e).map(([e,n])=>[e,n[t]])),Uf=24,Wf=360/Uf,Gf=.2,Kf=12,qf=8,Jf=e=>Math.round(e*1e5)/1e5,Yf=(e,t)=>2*Math.acos(Math.min(1,Math.abs(ls(e,t)))),Xf=(e,t,n)=>e.lean>0&&e.aim&&n>0?V(e.pos,U(H(K(e.aim),ps(t,[0,1,0])),n)):e.pos;function Zf(e,t){let n=K(ho(e,Math.abs(e[1])<.9?[0,1,0]:[1,0,0])),r=ho(e,n),i=[e];for(let a of[t/2,t])for(let t=0;t<qf;t++){let o=2*Math.PI*t/qf,s=Math.min(a,45)*Math.PI/180,c=V(U(n,Math.cos(o)),U(r,Math.sin(o)));i.push(K(V(U(e,Math.cos(s)),U(c,Math.sin(s)))))}return i}function Qf(e){let t=e[0].map(e=>({total:e.cost,from:-1})),n=[t];for(let r=1;r<e.length;r++)t=e[r].map(t=>{let i={total:1/0,from:-1};return e[r-1].forEach((e,a)=>{let o=n[r-1][a].total+Gf*Yf(e.q,t.q)**2;o<i.total&&(i={total:o,from:a})}),{total:i.total+t.cost,from:i.from}}),n.push(t);let r=[];for(let i=e.length-1,a=t.reduce((e,n,r)=>n.total<t[e].total?r:e,0);i>=0;a=n[i][a].from,i--)r[i]=a;return r}function $f(e,t,n){let r=(Math.sqrt(5)-1)/2,i=t,a=n,o=a-r*(a-i),s=i+r*(a-i),c=e(o),l=e(s);for(let t=0;t<Kf;t++)c<l?(a=s,s=o,l=c,o=a-r*(a-i),c=e(o)):(i=o,o=s,c=l,s=i+r*(a-i),l=e(s));return(i+a)/2}function ep(e,t,n){let r=e.map((e,r)=>{if(e.aim===void 0)return{fixed:us(e.rot)};let i=us(t(r)),a=e=>{let t=ss(ms(K(ps(i,[0,1,0])),e),i);return n=>ss(hs(e,n),t)};if(e.lean>0&&n)return{leans:Zf(K(e.aim),e.lean).map(a),roll:e.roll};let o=a(K(e.aim));return e.roll!==void 0||!n?{fixed:e.roll?o(e.roll):o(0)}:{rolled:o}}),i=e=>e.roll===void 0?Array.from({length:Uf},(e,t)=>t*Wf-180):[e.roll],a=r.map((e,t)=>e.fixed?[{q:e.fixed,cost:0,r:0}]:e.leans?e.leans.flatMap(r=>i(e).map(i=>{let a=r(i);return{q:a,cost:n(t,a),r:i,rolled:r,fixedRoll:e.roll!==void 0}})):Array.from({length:Uf},(r,i)=>{let a=i*Wf-180,o=e.rolled(a);return{q:o,cost:n(t,o),r:a}})),o=Qf(a),s=a.map((e,t)=>e[o[t]]);for(let[e,t]of r.entries())t.leans&&(r[e]=s[e].fixedRoll?{fixed:s[e].q}:{rolled:s[e].rolled});let c=[],l=null;for(let[t,i]of r.entries()){if(e[t].aim===void 0){c.push(e[t].rot),l=i.fixed;continue}let r=(i.fixed??i.rolled($f(e=>{let r=i.rolled(e),a=[s[t-1],s[t+1]].filter(Boolean);return n(t,r)+a.reduce((e,t)=>e+Gf*Yf(t.q,r)**2,0)},s[t].r-Wf/2,s[t].r+Wf/2))).map(Jf);l&&ls(r,l)<0&&(r=r.map(e=>-e)),c.push(r),l=us(r)}return c}var tp=.25,np=.3;function rp(e,t,n){if(!(t>0&&t<=np))return e;let r=!1,i=e.keys.map(e=>!e.aim||e.lean!==void 0||e.roll!==void 0||!(go(V(e.pos,U(K(e.aim),t)),n(e.f))<tp)?e:(r=!0,{...e,lean:45,leaned:!0}));return r?{...e,keys:i}:e}var ip=1e3,ap=4,op=.03,sp=.6,cp=.05,lp=45,up=2,dp=.05,fp=10,pp=400,mp=16,hp=4,gp=Array.from({length:72},(e,t)=>2*Math.PI*t/72-Math.PI);function _p(e,t){let n=t.length,r=Array.from(t);for(let t=0;t<n;t++)for(let i=t+1;i<=Math.min(t+2,n-1);i++){let a=e[i][t-i+2]/e[t][2];for(let r=t;r<=Math.min(t+2,n-1);r++)e[i][r-i+2]-=a*e[t][r-t+2];r[i]-=a*r[t]}for(let t=n-1;t>=0;t--){for(let i=t+1;i<=Math.min(t+2,n-1);i++)r[t]-=e[t][i-t+2]*r[i];r[t]/=e[t][2]}return r}function vp(e,t,n,r=null){let i=n.length,a=n.slice();for(let e=1;e<i;e++)a[e]=a[e-1]+Math.atan2(Math.sin(a[e]-a[e-1]),Math.cos(a[e]-a[e-1]));for(let n=0;n<ap&&i>2;n++){let n=a.map(()=>new Float64Array(5)),o=new Float64Array(i);a.forEach((t,r)=>{let i=e(r,t),a=e(r,t+op),s=e(r,t-op);n[r][2]=Math.max(cp,(a+s-2*i)/(op*op)),o[r]=-(a-s)/(2*op)});let s=a.map((e,n)=>t(n,e)),c=a.map((e,n)=>U(H(t(n,e+op),t(n,e-op)),1/(2*op)));for(let e=0;e+2<i;e++){let t=[1,-2,1],i=V(H(s[e],U(s[e+1],2)),s[e+2]),a=r?2*ip*r[e]:2*ip;for(let r=0;r<3;r++){o[e+r]-=a*t[r]*W(i,c[e+r]);for(let i=0;i<3;i++)n[e+r][i-r+2]+=a*t[r]*t[i]*W(c[e+r],c[e+i])}}let l=_p(n,o);a.forEach((e,t)=>{a[t]=e+Math.max(-.6,Math.min(sp,l[t]))})}return a}function yp(e,t,n){let r=e.map((e,t)=>n(t,e)),i=e=>e>=0&&e+1<r.length?G(H(r[e+1],r[e])):0;return e.slice(1).map((e,t)=>t).filter(n=>i(n)>dp&&i(n)>up*Math.max(i(n-1),i(n+1))&&ko(t(n,e[n]),t(n+1,e[n+1]))>lp)}function bp(e,t,n,r){let i=r.length,a=lp*Math.PI/180,o=[],s=[];for(let i=0;i<n;i++)o.push(r.map(t=>e(i,t))),s.push(r.map(e=>t(i,e)));let c=o[0].slice(),l=[];for(let e=1;e<n;e++){let t=Array(i),n=new Int32Array(i);for(let r=0;r<i;r++){let l=1/0;for(let t=0;t<i;t++){let i=Math.acos(Math.max(-1,Math.min(1,W(s[e-1][t],s[e][r])))),o=c[t]+fp*i*i+(i>a?pp*(i-a)**2:0);o<l&&(l=o,n[r]=t)}t[r]=l+o[e][r]}l.push(n),c=t}let u=Array(n);u[n-1]=c.indexOf(Math.min(...c));for(let e=n-1;e>0;e--)u[e-1]=l[e-1][u[e]];return u.map(e=>r[e])}function xp(e,t,n,r,i=gp){let a=vp(e,t,n);if(!yp(a,r,t).length)return a;let o=bp(e,r,a.length,i),s=vp(e,t,o),c=yp(s,r,t);if(!c.length)return s;let l=vp(e,t,o,new Float64Array(Math.max(0,s.length-2)).map((e,t)=>c.some(e=>e>=t-hp&&e<=t+1+hp)?mp:1));return yp(l,r,t).length?a:l}function Sp(e){return e.map((t,n)=>{let r=0,i=0;for(let t=Math.max(0,n-6);t<=Math.min(e.length-1,n+6);t++){let a=Math.exp(-((t-n)**2)/8);r+=a*e[t],i+=a}return r/i})}function Cp(e,t,n,r){let i=n.map(n=>{let{s:i,held:a}=r(n);return vc(e,i,t,a)}),a=xp((e,t)=>i[e].at(t).cost,(e,t)=>i[e].at(t).elbow,i.map(e=>e.softmin()),(e,t)=>i[e].at(t).pv);return new Map(n.map((e,t)=>[e,i[t].at(a[t]).pv]))}var wp=36,Tp=.05,Ep=.3,Dp=3,Op=10,kp=36,Ap=1,jp=100,Mp=Sc.filter(e=>e[0].startsWith(`torso`)),Np=Object.fromEntries(Sc.map(e=>[e[0],e[3]])),Pp=(e,t,n)=>[[e[0],t[0],n[0]],[e[1],t[1],n[1]],[e[2],t[2],n[2]]],Fp=(e,t)=>[e[0][t],e[1][t],e[2][t]];function Ip(e,t,n,r){let i=H(t,e),a=H(r,n),o=H(e,n),s=W(i,i),c=W(a,a),l=W(a,o);if(s<1e-12||c<1e-12)return G(o);let u=W(i,o),d=W(i,a),f=s*c-d*d,p=f>1e-12?_o((d*l-u*c)/f,0,1):0,m=(d*p+l)/c;return m<0?(m=0,p=_o(-u/s,0,1)):m>1&&(m=1,p=_o((d-u)/s,0,1)),G(H(V(e,U(i,p)),V(n,U(a,m))))}function Lp(e,t,n){let r=e.index,i=Xo(e,t,n);return{pos:U(V(t.P[r[`${n}HandIndex2`]],t.P[r[`${n}HandMiddle2`]]),.5),R:Pp(i.d,i.l,i.n)}}function Rp(e,t,n,r,i,a){let o=t.objects[n];if(t.props[o.prop].hand!==`r`)return null;let s=Object.entries(t.anchors??{}).reduce((e,[t,n])=>e+(n.kind===`prop`&&n.prop===o.prop?Math.max(0,i[`w_${t}_l`]??0):0),0);if(!(s>1e-4))return null;let c=Lp(e,r,n_.r).R,l=Fp(c,0),u=K(ho(a,H(l,U(a,W(l,a))))),d=e=>H(e,U(u,2*W(e,u))),f=Pp(d(l),d(Fp(c,1)),U(d(Fp(c,2)),-1)),p=Lp(e,r,n_.l),m=e.index,h=m.LeftHand,g=r.P[h],_=q(Y(r.R[h]),p.R),v=J(Y(r.R[h]),H(p.pos,g)),y=(t.fits??[]).some(e=>e.side===`l`&&t.anchors?.[e.anchor]?.kind===`prop`&&t.anchors[e.anchor].prop===o.prop&&i[`w_${e.anchor}_l`]>1e-4)?`palm`:`wrist`,b=e=>q(wo(a,e*180/Math.PI),f),x=e=>q(b(e),Y(_)),S=e=>y===`wrist`?V(g,J(x(e),v)):H(p.pos,J(x(e),v)),C=e=>y===`wrist`?g:S(e),w=J(Y(r.R[h]),H(r.P[m.LeftHandMiddle3],g)),T=r.P[m.LeftArm],E=hc(e,r,n_.l),D=t.fix===!1||t.fix?.self===!1?null:Es(e),O={uarm_l:m.LeftArm,farm_l:m.LeftForeArm,hand_l:m.LeftHand},k=(t,n,i)=>D?Vs(D,e,r,O[i],t,n):Math.max(0,...Mp.map(([,e,a,o])=>Np[i]+o-Ip(t,n,r.P[m[e]],r.P[m[a]]))),ee=new Map,A=t=>{if(ee.has(t))return ee.get(t);let n=C(t),i=oc(e,r,n_.l,x(t),n,E,Ks),a=e=>{let t=i.at(e);return{pv:t.pv,elbow:t.elbow,cost:t.cost+Ap*((100*k(T,t.elbow,`uarm_l`))**2+(100*k(t.elbow,n,`farm_l`))**2)}},o={th:0,cost:1/0};for(let e=0;e<kp;e++){let t=2*Math.PI*e/kp-Math.PI,n=a(t).cost;n<o.cost&&(o={th:t,cost:n})}let s=V(n,J(x(t),w)),c=k(n,s,`hand_l`),l=Math.max(0,c-rd.body),u=2*Np.hand_l-Ip(n,s,r.P[m.RightHand],r.P[m.RightHandMiddle3]),d=Math.max(0,u-rd.hands),f=Ap*((100*c)**2+(100*i.miss)**2)+(l>0?jp*(100*l)**2:0)+(d>0?jp*(100*d)**2:0),p={at:a,best:{th:o.th,pole:a(o.th).pv,cost:o.cost+f}};return ee.set(t,p),p},te=e=>A(e).best.cost+Ep*(1-Math.cos(e));return{id:n,weight:s,pin:y,at:p.pos,rolled:b,arm:A,cost:te,point:S,softmin:()=>{let e=Array.from({length:wp},(e,t)=>{let n=2*Math.PI*t/wp-Math.PI;return[n,te(n)]}),t=Math.min(...e.map(e=>e[1])),n=e.reduce((e,[n,r])=>{let i=Math.exp(-(r-t)/Tp);return[e[0]+i*Math.cos(n),e[1]+i*Math.sin(n)]},[0,0]);return Math.atan2(n[1],n[0])},measure:t=>Lp(e,t,n_.l)}}var zp=(e,t)=>Math.exp(-Math.max(0,e.cost(t)-Dp)/Op),Bp=(e,t,n,r,i)=>({w:t*Math.min(1,e.weight)*r,second:e.id,pin:e.pin,pole:i,palm:{pos:e.at,R:e.rolled(n)},measure:e.measure}),Vp=.045,Hp=4,Up=8,Wp=[30,10],Gp=2,Kp=4,qp=2,Jp=.1,Yp=1.5,Xp=20,Zp=4,Qp=8,$p=400,em=[`the fingers' line`,`the palm normal`,`the knuckle line`],tm=(e,t)=>[e[0][t],e[1][t],e[2][t]],nm=e=>{let t=Y(e.R);return{pos:U(J(t,e.pos),-1),R:t}},rm=e=>Math.round(e*100)/100;function im(e,t,n){let r=Do(e),i=Do(t);return ls(r,i)<0&&(i=i.map(e=>-e)),Oo(gs(r,i,n))}function am(e,[t,n],[r,i]){let a=e>=0?n:-t,o=e>=0?i:-r,s=Math.abs(e);if(s<=a)return(s/a)**2;let c=(Math.min(s,o)-a)/Math.max(1e-6,o-a);return 1+Qp*c*c+(s>o?$p*((s-o)/o)**2:0)}function om(e,t,n,r,i){let{goal:a,plane:o,wristAt:s}=gc(e,t,n,r,i,1),c=s(a),l=oc(e,t,n,a,c,o,Ks),u=l.at(l.softmin()),d=e.index,f=t.P[d[`${n}Arm`]],p=G(H(t.P[d[`${n}ForeArm`]],f)),m=G(H(t.P[d[`${n}Hand`]],t.P[d[`${n}ForeArm`]])),h=Math.max(0,zo(p,m,145)-G(H(c,f))),g=Es(e),_=g?Math.max(Vs(g,e,t,d[`${n}Arm`],f,u.elbow),Vs(g,e,t,d[`${n}ForeArm`],u.elbow,c),Vs(g,e,t,d[`${n}Hand`],c,r.pos)):0;return[`twist`,`flex`,`dev`].reduce((e,t)=>e+am(u.need[t],Ws[t],Us[t]),0)+Xp*((l.miss*100)**2+(h*100)**2)+Zp*(_*100)**2}function sm(e,t,n,r,i,a,o){if(r.aim===void 0)return o({pos:r.pos,R:Oo(r.rot)});let s=Do(D_(i,a).R),c=K(r.aim),l=ss(ms(K(ps(s,[0,1,0])),c),s),u=e=>({pos:r.pos,R:Oo(ss(hs(c,e),l))});if(r.roll!==void 0)return o(u(r.roll));let d=null;for(let r=0;r<Hp;r++){let o=u(360/Hp*r-180),s=yc(e,t,n,D_(o,nm(a)),i);(!d||s<d.strain)&&(d={p:o,strain:s})}return o(d.p)}function cm(e,t){let n=Object.entries(e?.objects??{}).filter(([e,n])=>(e===t||n.ancestors?.includes(t))&&n.half);if(!n.length)return!1;let r=n.map(([,e])=>e.half).reduce((e,t)=>t[0]*t[1]*t[2]>e[0]*e[1]*e[2]?t:e),i=[0,1,2].reduce((e,t)=>r[t]>r[e]?t:e,0);return[0,1,2].filter(e=>e!==i).every(e=>r[e]<Vp)}var lm=(e,t)=>e.length<=t?e:Array.from({length:t},(n,r)=>e[Math.round(r*(e.length-1)/(t-1))]);function um(e,t){let n=ds(Do(q(Y(e),t)));return`today's grip turned ${Math.round(2*G(n)*180/Math.PI)} deg, mostly about ${em[[0,1,2].reduce((e,t)=>Math.abs(n[t])>Math.abs(n[e])?t:e,0)]}`}function dm({sk:e,o:t,side:n,grab:r,rest:i,plain:a,palmOf:o,map:s=e=>e}){let c=new Map,l=e=>{let t=Math.round(e);if(!c.has(t)){let e=a(t);c.set(t,{s:e,now:o(e)})}return c.get(t)},{s:u,now:d}=l(r),f=[...t.keys].sort((e,t)=>e.f-t.f),p=lm(f,Up),m=e=>O_({pos:d.pos,R:e},i),h=(t,r,i)=>{let{s:a,now:o}=l(r);return om(e,a,n,D_(i,nm(t)),o)},g=t=>om(e,u,n,D_(i,nm(t)),d),_=t=>{let r=m(t);return g(r)+p.reduce((t,i)=>{let{s:a,now:o}=l(s(i.f));return t+sm(e,a,n,i,o,r,e=>h(r,s(i.f),e))},0)},v=r=>{let a=m(r),o=Math.round(s(f[0].f)),c=Math.round(s(f[f.length-1].f)),u=Im(t,s,e=>Do(D_(l(e).now,a).R),(t,r,i,o)=>{let{s,now:c}=l(t);return yc(e,s,n,D_({pos:r,R:Oo(i)},nm(a)),c,o)},2*(i?.half?.[1]??0)),d=g(a),p=d;for(let e=o;e<=c;e+=Kp){let t=h(a,e,zm(u,e));d+=t,p=Math.max(p,t)}return{A:a,cost:d,worst:p}},y={name:`today`,R:d.R,...v(d.R)};if(y.worst<=Yp)return{offset:y.A,name:`today`,cost:rm(y.cost),today:rm(y.cost)};let b={R:d.R,rough:_(d.R)};for(let e of Wp)for(let t=0,n=!0;n&&t<Gp;t++){n=!1;for(let t of[0,1,2])for(let r of[1,-1]){let i=q(wo(tm(b.R,t),r*e),b.R),a=_(i);a<b.rough-1e-6&&(b={R:i,rough:a},n=!0)}}let x=b.R===d.R?y:{name:um(d.R,b.R),...v(b.R)},S=x.cost<y.cost-Math.max(qp,Jp*y.cost)?x:y;return{offset:S.A,name:S.name,cost:rm(S.cost),today:rm(y.cost)}}var fm=3,pm=12,mm=.05,hm=.3,gm=180/Math.PI,_m=40,vm=1,ym=.3,bm=[-40,-40/2,0,_m/2,_m];function xm(e){let t=Math.min(...e.map(e=>e[1])),n=e.map(([e,n])=>[e,Math.exp(-(n-t)/ym)]);return n.reduce((e,[t,n])=>e+t*n,0)/n.reduce((e,[,t])=>e+t,0)}function Sm(e){let t=Array.from({length:pm},(t,n)=>{let r=2*Math.PI*n/pm-Math.PI;return[r,e(r)]}),n=Math.min(...t.map(e=>e[1])),r=t.reduce((e,[t,r])=>{let i=Math.exp(-(r-n)/mm);return[e[0]+i*Math.cos(t),e[1]+i*Math.sin(t)]},[0,0]);return Math.atan2(r[1],r[0])}var Cm=({d:e,l:t,n})=>[[e[0],t[0],n[0]],[e[1],t[1],n[1]],[e[2],t[2],n[2]]],wm=(e,t)=>e.anchors?.[t]?.kind===`object`&&!!e.anchors[t].grasp,Tm=(e,t)=>(e.keys??[]).some(e=>(!e.src||e.src.startsWith(`keys[`))&&(e.set?.[`wtwist_${t}`]!==void 0||e.set?.[`wflex_${t}`]!==void 0));function Em(e,t,n,r){let i=new Set(sg(t,n));return(e.fits??[]).some(a=>{if(a.side!==r||!wm(e,a.anchor))return!1;let o=e.anchors[a.anchor].object;return o===n||i.has(o)||sg(t,o).some(e=>i.has(e))})}function Dm(e,t,n){let{spec:r,scene:i}=e;if(!e.objectHand||!(r.fits??[]).some(e=>e.side===t&&wm(r,e.anchor)))return null;for(let[a,o]of Object.entries(r.objects??{}))if(o?.prop&&e.objectHand(a,n)===t&&Em(r,i,a,t))return{id:a,grab:e.carrySpan(o)[0],keyed:!!o.keys?.length};return null}function Om(e,t,n,r,i,a,o,s,c,l=null,u=void 0){let d=t.index,f=d[`${r}Arm`],p=d[`${r}ForeArm`],m=d[`${r}Hand`],h=n.R[p],g=l?.w??Ud(e,s.fit.anchor,n,o,a,i),_=c(n),v=K(H(n.P[m],n.P[p])),y=l?.type??e.spec.anchors[s.fit.anchor].grasp,b=Ad(r,g,y,v,a.yaw),x=(e=>({pos:c(e),R:Cm(Xo(t,e,r))}))(n),S=e=>{let i=gc(t,n,r,{pos:_,R:e},x,1,`palm`);return sc(t,n,r,i.goal,i.wristAt(i.goal),i.plane,Ks).cost},C=(e,t)=>[e[0][t],e[1][t],e[2][t]],w=e=>q(wo(C(b,1),e*gm),b),{R:T,roll:E,tilt:D}=km(e,s.fit.anchor,i,u,()=>{let e=g.axis&&!g.from&&y!==`palm`?Sm(e=>S(w(e))+hm*(1-Math.cos(e))):0,t=w(e),n=e=>q(wo(C(t,2),e),t),r=g.axis&&y!==`palm`?xm(bm.map(e=>[e,S(n(e))+vm*(e/_m)**2])):0;return{R:n(r),roll:e,tilt:r}}),{goal:O,plane:k,wristAt:ee}=gc(t,n,r,{pos:_,R:T},x,s.w,`palm`),A=sc(t,n,r,O,ee(O),k,Ks,{w:s.w}),te={twist:0,flex:0,dev:0};for(let e=0;e<fm;e++)Jo(t,n,f,p,m,ee(e?n.R[m]:O),A.pole,Ks,`elbow`),te=mc(t,n,r,m,p,O);o[`grip_${i}`]={w:s.w,socket:!0,...te,roll:E*gm,tilt:D},o[`socket_${i}`]={rel:q(Y(h),n.R[m])}}function km(e,t,n,r,i){let a=`w_${t}_${n}`,o=t=>e.weightAt?.(a,t)??0;if(!e.weightAt||!Number.isInteger(r))return i();let s=r,c;for(;s>0&&o(s-1)>.001;)s--;for(c=s;c<e.frameCount-1&&o(c)<.999&&o(c+1)>.001;c++);let l=`${a}:${s}`;if(e.graspPlans??=new Map,r>=c){let t=i();return r===c&&e.graspPlans.set(l,t),t}return e.graspPlans.has(l)||(e.graspPlans.set(l,null),(e.hold?.plainFrame??e.solvedAt)(c)),e.graspPlans.get(l)??i()}function Am(e,t,n,r,i,a){let o=`${i}:${a.grab}`;e.socketTurns??=new Map,e.socketTurns.has(o)||(e.socketTurns.set(o,null),e.socketTurns.set(o,(e.hold?.plainFrame??e.solvedAt)(a.grab)?.diag?.[`socket_${i}`]?.rel??null));let s=e.socketTurns.get(o);if(!s)return;let c=t.index,l=c[`${r}ForeArm`],u=c[`${r}Hand`];mc(t,n,r,u,l,q(n.R[l],s))}var jm=12,Mm={m:.01,deg:5},Nm=e=>e*e*(3-2*e),Pm=(e,t)=>{let n=t=>e.timeMap?Math.round(e.timeMap(t)):t;return[n(t.grab??0),t.release===void 0?e.frameCount-1:n(t.release)]},Fm=e=>{let t=Y(e.R);return{pos:U(J(t,e.pos),-1),R:t}};function Im(e,t,n,r,i=0){let a=[...e.keys].sort((e,t)=>e.f-t.f),o=a.map(e=>t(e.f)),s=[],c=ep(a,e=>n(o[e]),r&&((e,t)=>r(o[e],Xf(a[e],t,i),t,a[e].lean?{shoulder:!0}:void 0))),l=a.map((e,t)=>Xf(e,us(c[t]),i).slice());for(let e of c){let t=us(e);s.push(s.length&&ls(s[s.length-1],t)<0?t.map(e=>-e):t)}let u=a.length-1,d=e=>U(ds(ss(cs(s[e]),s[e+1])),1/(o[e+1]-o[e])),f=(e,t)=>e===0||e===u?[0,0,0]:U(V(U(t(e),o[e]-o[e-1]),U(t(e-1),o[e+1]-o[e])),1/(o[e+1]-o[e-1]));return{t:o,p:l,q:s,m:l.map((e,t)=>f(t,e=>U(H(l[e+1],l[e]),1/(o[e+1]-o[e])))),w:s.map((e,t)=>f(t,d)),rots:c}}var Lm=new WeakMap;function Rm(e,t){Lm.has(e)||Lm.set(e,new Map);let n=Lm.get(e),r=e.timeMap,i=e.baked,a=n.get(t);if(!a||a.map!==r||a.baked!==i){let a=e.ctx.hold,o=new Map,s=e=>{let t=Math.round(e);return o.has(t)||o.set(t,a.plainFrame(t).s),o.get(t)};n.set(t,{map:r,baked:i,curve:Im(a.entry?.(t)??e.ctx.spec.objects[t],e=>r?r(e):e,e=>Do(a.carryOn(t,s(e)).R),(e,n,r,i)=>a.strainOn(t,s(e),{pos:n,R:Oo(r)},i),2*(e.ctx.scene?.objects?.[t]?.half?.[1]??0))})}return n.get(t).curve}function zm({t:e,p:t,q:n,m:r,w:i},a){let o=e.length;if(o===1||a<=e[0])return{pos:t[0].slice(),R:Oo(n[0])};if(a>=e[o-1])return{pos:t[o-1].slice(),R:Oo(n[o-1])};let s=0;for(;a>e[s+1];)s++;let c=e[s+1]-e[s],l=(a-e[s])/c,u=l*l,d=u*l,f=2*d-3*u+1,p=d-2*u+l,m=-2*d+3*u,h=d-u,g=V(V(U(t[s],f),U(r[s],c*p)),V(U(t[s+1],m),U(r[s+1],c*h))),_=ss(cs(n[s]),n[s+1]),v=V(V(U(ds(_),m),U(i[s],c*p)),U(ps(_,i[s+1]),c*h));return{pos:g,R:Oo(ss(n[s],fs(v)))}}function Bm(e,[t,n],r){let i=e.t[0],a=e.t[e.t.length-1];if(r<t||r>n)return 0;if(r>=i&&r<=a)return 1;let o=r<i?Math.min(8,i-t):8,s=r<i?i-r:r-a;return o>0&&s<o?Nm(1-s/o):0}var Vm=e=>Object.entries(e.objects??{}).filter(([,e])=>b_(e)&&e.keys?.length);function Hm(e,t,n,r){let{sk:i,spec:a,scene:o}=e,s=Vm(a);if(!s.length)return null;let c=new Set(s.map(([e])=>e).filter(e=>ul(a,a.objects[e],o,e)).map(e=>a.objects[e])),l=new WeakMap,u=e=>t.timeMap?Math.round(t.timeMap(e)):e,d=e=>{l.has(t)||l.set(t,new Map);let r=l.get(t);if(!r.has(e)){let t=2*(o?.objects?.[e]?.half?.[1]??0);r.set(e,rp(a.objects[e],t,e=>Io(n(u(e)).s,i.index.Head,i.landmarks.mouth)))}return r.get(e)},f=(e,t)=>E_(i,a,t,{prop:e.prop},c.has(e)),p=new WeakMap,m=new Set,h=(t,n)=>e.restingAt?.(t,n)??o?.objects?.[t]??Jl(o)[t],g=new WeakMap,_=e=>t.timeMap?Math.round(t.timeMap(e)):e,v=e=>{g.has(t)||g.set(t,new Map);let r=g.get(t),s=a.objects[e],c=a.props?.[s.prop]?.hand,l=Pm(t,s)[0],u=t.baked??{};if(r.has(e))return r.get(e);if(r.set(e,null),!(c&&s.at===void 0&&s.along===void 0&&(s.grab!==void 0||!o?.objects?.[e])&&cm(o,e)&&!(a.fits??[]).some(e=>e.side===c&&e.orient===!1)&&!Em(a,o,e,c)&&![`wtwist`,`wflex`].some(e=>Math.abs(u[`${e}_${c}`]?.[l]??0)>.001)&&_(Math.min(...s.keys.map(e=>e.f)))<=l))return null;m.add(e);try{r.set(e,dm({sk:i,o:d(e),side:n_[c],grab:l,rest:h(e,l),plain:e=>n(e).s,palmOf:e=>f(s,e),map:_}))}finally{m.delete(e)}return r.get(e)},y=r=>{p.has(t.baked)||p.set(t.baked,new Map);let s=p.get(t.baked),l=a.objects[r];if(s.has(r))return s.get(r);let u=v(r);if(u&&u.name!==`today`){let e=c.has(l)?pl(i,a,o,r,l,u.offset):u.offset;return s.set(r,e),s.set(`${r}|taken`,u.offset),e}let d=o?.objects?.[r]??Jl(o)[r],h=!o?.objects?.[r]&&!!d,g=l.at===void 0&&l.along===void 0&&(h||l.grab!==void 0);m.add(r);let _;try{_=g?n(Pm(t,l)[0]).s:Mo(i)}finally{m.delete(r)}let y=O_(f(l,_),g?e.restingAt?.(r,Pm(t,l)[0])??{pos:d.pos,R:d.R}:E_(i,a,_,l)),b=g&&c.has(l)?pl(i,a,o,r,l,y):y;return s.set(r,b),s.set(`${r}|taken`,y),b},b=(e,n)=>{let r=y(e),i=p.get(t.baked)?.get(`${e}|taken`);return i&&i!==r&&n!==void 0?gl(i,r,hl(Pm(t,a.objects[e])[0],n)):r},x=(e,t)=>D_(f(a.objects[e],t),y(e)),S=(e,t,n,r)=>{let o=a.objects[e];return yc(i,t,n_[a.props[o.prop].hand],D_(n,Fm(y(e))),f(o,t),r)},C=(e,n,r)=>{let i=Rm(t,e),a=Bm(i,Pm(t,n),r);return a>0?{w:a,palm:D_(zm(i,r),Fm(b(e,r))),measure:e=>f(n,e),comfort:d(e).keys.some(e=>e.lean>0)}:null},w=new WeakMap,T=(e,r)=>{w.has(t.baked)||w.set(t.baked,new Map);let o=w.get(t.baked),s=o.get(e);if(s&&s.map===t.timeMap)return s.plan;let[c,l]=Pm(t,r),u=[];for(let n=Math.max(0,c);n<=Math.min(t.frameCount-1,l);n++)Bm(Rm(t,e),[c,l],n)>0&&u.push(n);let d=Cp(i,n_[a.props[r.prop].hand],u,t=>({s:n(t).s,held:C(e,r,t)}));return o.set(e,{map:t.timeMap,plan:d}),d},E=!1,D=(e,t,n)=>{let r=x(e,t).R;return Rp(i,a,e,t,n,[r[0][1],r[1][1],r[2][1]])},O=new WeakMap,k=(e,n)=>{O.has(t.baked)||O.set(t.baked,new Map);let i=O.get(t.baked),a=i.get(e);if(a&&a.map===t.timeMap)return a.plan;let[o,s]=Pm(t,n),c=new Map;E=!0;let l=[],u=()=>{let e=vp((e,t)=>l[e].grip.cost(t),(e,t)=>l[e].grip.point(t),l.map(e=>e.grip.softmin())),t=Sp(l.map((t,n)=>zp(t.grip,e[n]))),n=t=>l[t].grip.arm(e[t]),r=vp((e,t)=>n(e).at(t).cost,(e,t)=>n(e).at(t).elbow,l.map((e,t)=>n(t).best.th));l.forEach((i,a)=>c.set(i.f,{roll:e[a],gate:t[a],pole:n(a).at(r[a]).pv})),l=[]};for(let n=Math.max(0,o);n<=Math.min(t.frameCount-1,s);n++){let i=Bm(Rm(t,e),[o,s],n)>0?r(n):null,a=i&&D(e,i.s,i.c);a?l.push({f:n,grip:a}):l.length&&u()}return l.length&&u(),E=!1,i.set(e,{map:t.timeMap,plan:c}),c},ee=(e,n,r)=>{let i=v(e);if(!i||i.name===`today`)return null;let a=Rm(t,e),o=a.t[0],s=a.t[a.t.length-1],[c,l]=Pm(t,n);if(r>=o&&r<=s)return null;let u=D_(zm(a,r<o?o:s),Fm(i.offset)),d=e=>f(n,e),p=T(e,n).get(Math.round(r<o?o:s));if(r<c||r>l){let e=Nm(Math.max(0,1-(r<c?c-r:r-l)/jm));return e>.001?{w:e,palm:u,measure:d,pole:p}:null}let m=C(e,n,r);return{w:1,palm:m?{pos:V(U(u.pos,1-m.w),U(m.palm.pos,m.w)),R:im(u.R,m.palm.R,m.w)}:u,measure:d,pole:p}},A=new WeakMap,te=(e,r,i)=>{A.has(t.baked)||A.set(t.baked,new Map);let a=A.get(t.baked),o=a.get(e);if(o&&o.map===t.timeMap)return o.off;m.add(e);let s;try{s=f(r,n(Math.max(Pm(t,r)[0],Math.round(Rm(t,e).t[0]))).s)}finally{m.delete(e)}let c=O_(s,i).R,l=Math.acos(Math.min(1,Math.max(-1,(c[0][0]+c[1][1]+c[2][2]-1)/2)))*180/Math.PI,u=Math.hypot(...H(i.pos,s.pos))>Mm.m||l>Mm.deg;return a.set(e,{map:t.timeMap,off:u}),u},ne=(e,n,r)=>{let i=Rm(t,e),[a,o]=Pm(t,n),s=Math.max(a,Math.round(i.t[0]));if(!(r<s&&r>=s-jm)||s-a>=8||s>o)return null;let c=D_(zm(i,s),Fm(y(e)));if(!te(e,n,c))return null;let l=Nm(1-(s-r)/jm);return l>.001?{w:l,palm:c,measure:e=>f(n,e),pole:T(e,n).get(s)}:null},re=(e,n,r)=>{let i=Rm(t,e),a=i.t[i.t.length-1],o=Pm(t,n)[1];return r>o&&r-a<8?{curve:i,release:o,w:Nm(1-(r-a)/8)}:null},ie=(e,t,n)=>{let r=re(e,t,n);return r&&{w:r.w,palm:D_(zm(r.curve,r.release),Fm(y(e))),measure:e=>f(t,e),pole:T(e,t).get(r.release)}};return{lead:(e,n,r,i)=>{for(let[o,c]of s){let s=a.props?.[c.prop]?.hand===e?ee(o,c,n)??ne(o,c,n)??ie(o,c,n):null;if(s)return s;let l=a.props?.[c.prop]?.hand===e?C(o,c,n):null;if(l)return{...l,pole:T(o,c).get(n)};let u=e===`l`&&r&&!E?re(o,c,n):null,d=e===`l`&&r&&!E?Bm(Rm(t,o),Pm(t,c),n)||(u?.w??0):0,f=d>0?D(o,r,i):null,p=f&&k(o,c).get(u?u.release:n),m=p?.roll??f?.softmin();if(f)return Bp(f,d,m,p?.gate??zp(f,m),p?.pole??f.arm(m).best.pole)}return null},attach:y,attachAt:b,attaching:e=>m.has(e),plainFrame:n,entry:d,carryOn:x,strainOn:S,span:e=>Pm(t,a.objects[e]),firstKey:e=>{let n=Math.min(...a.objects[e].keys.map(e=>e.f));return t.timeMap?Math.round(t.timeMap(n)):n},grips:()=>s.map(([e,t])=>{let n=v(e);return n&&{id:e,hand:a.props[t.prop].hand,name:n.name,cost:n.cost,today:n.today}}).filter(Boolean)}}var Um=[0,0,0];function Wm(e,t,n,r){return Array.isArray(e?.v)?e.v:e?.v===`hand`&&n?U(H(t.pos,n.pos),r):Um}var Gm=e=>e.some(e=>e!==0),Km=(e,t,n)=>(t+Math.sqrt(t*t+2*n*Math.max(0,e)))/n,qm=(e,t,n)=>{let r=Math.min(t,n);return[e[0]*r,0,e[2]*r]};function Jm(e,t,n,r,i=[]){let a=e(t),o=a.top+a.h,s=e=>({pos:V(t.pos,qm(n,Km(o-e,n[1],r),1/0)),R:t.R});for(let t of[...new Set(i)].filter(e=>e<=o).sort((e,t)=>t-e)){let n=e(s(t));if(Math.abs(n.top-t)<1e-9)return n}return e(s(0))}var Ym=.3,Xm=.5,Zm=15,Qm=1,$m=6*Math.PI,eh=3,th=[0,-1,0],nh=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]],rh=e=>e*180/Math.PI;function ih(e){let t=e.filter(e=>e.half[0]*e.half[1]*e.half[2]>1e-12);if(!t.length)return null;let n=0,r=[0,0,0],i=[];for(let e of t){let t=e.half[0]*e.half[1]*e.half[2];n+=t,r=V(r,U(V(e.pos,J(e.R,[0,e.half[1],0])),t));for(let t of[-1,1])for(let n of[0,2])for(let r of[-1,1])i.push(V(e.pos,J(e.R,[t*e.half[0],n*e.half[1],r*e.half[2]])))}return{com:U(r,1/n),lo:[0,1,2].map(e=>Math.min(...i.map(t=>t[e]))),hi:[0,1,2].map(e=>Math.max(...i.map(t=>t[e])))}}var ah=e=>[0,1,2,3,4,5,6,7].map(t=>[t&1?e.hi[0]:e.lo[0],t&2?e.hi[1]:e.lo[1],t&4?e.hi[2]:e.lo[2]]),oh=(e,t)=>V(e.pos,J(e.R,t)),sh=(e,t)=>Math.min(...ah(e).map(e=>oh(t,e)[1])),ch=(e,t,n)=>({pos:[t.pos[0],t.pos[1]+n-sh(e,t),t.pos[2]],R:t.R}),lh=(e,t,n)=>({pos:V(t,J(n,H(e.pos,t))),R:q(n,e.R)}),uh=e=>nh.reduce((t,n,r)=>W(J(e,n),th)>W(J(e,nh[t]),th)?r:t,0),dh=(e,t)=>{let n=t>>1;return nh[t][n]>0?e.hi[n]:e.lo[n]},fh=(e,t)=>Math.abs(dh(e,t)-e.com[t>>1]);function ph(e,t,n){let r=q(t,[[e[0][0],e[1][0],e[2][0]],[e[0][1],e[1][1],e[2][1]],[e[0][2],e[1][2],e[2][2]]]),i=Math.acos(_o((r[0][0]+r[1][1]+r[2][2]-1)/2,-1,1));if(i*n<Qm)return[0,0,0];let a=K([r[2][1]-r[1][2],r[0][2]-r[2][0],r[1][0]-r[0][1]]),o=Math.min($m,i*n);return G(a)>0?U(a,o):[0,0,0]}function mh(e,t,n,r,i,a=[0,0,0]){let o=G(n),s=oh(t,e.com),c=!a.some(e=>e!==0),l=r=>{let i=o>0?q(wo(n,rh(o*r)),t.R):t.R,l=c?[0,-.5*Ah*r*r,0]:[a[0]*r,a[1]*r-.5*Ah*r*r,a[2]*r];return{pos:H(V(s,l),J(i,e.com)),R:i}},u=Math.max(0,sh(e,t)-r);if(o===0)return{tl:c?Math.sqrt(2*u/Ah):Km(u,a[1],Ah),at:l};let d=1/(i*8),f=(c?Math.sqrt(2*(u+G(H(e.hi,e.lo)))/Ah):Km(u+G(H(e.hi,e.lo)),a[1],Ah))+d,p=0,m=d;for(;m<f&&sh(e,l(m))>r;)p=m,m+=d;for(let t=0;t<24&&m-p>1e-7;t++){let t=(p+m)/2;sh(e,l(t))>r?p=t:m=t}return{tl:m,at:l}}var hh=(e,t)=>.12+.9*Math.sqrt(Math.max(e,1e-4)/Ah)*Math.sqrt(t/90);function gh(e,t,n,r,i=[0,0,0]){let a=[],o=ch(e,t,n),s=0,c=(t,r,i)=>{let c=hh(oh(o,e.com)[1]-n,i);a.push({from:o,pivot:t,axis:r,angle:i,time:c}),o=ch(e,lh(o,t,wo(r,i)),n),s+=c},l=uh(o.R),u=e=>rh(Math.acos(_o(W(J(o.R,nh[e]),th),-1,1))),d=u(l);if(d>Xm){let t=[0,1,2,3,4,5].filter(e=>e>>1!=l>>1).reduce((e,t)=>u(t)<u(e)?t:e,l===0||l===1?2:0);d>rh(Math.atan2(fh(e,t),fh(e,l)))&&(l=t);let r=ah(e).map(e=>oh(o,e)).filter(e=>e[1]<=n+1e-4),i=J(o.R,nh[l]);c(U(r.reduce(V,[0,0,0]),1/r.length),K(ho(i,th)),u(l))}let f=d>Xm||G(i)>0?r:0;for(let t=0;t<eh;t++){let t=oh(o,e.com),r=t[1]-n,a=null;for(let n=0;n<6;n++){if(n>>1==l>>1)continue;let s=J(o.R,nh[n]),c=oh(o,nh[n].map((t,r)=>t?dh(e,n):r===l>>1?dh(e,l):e.com[r])),u=-W(H(t,c),s),d=fh(e,n);if(!(u<0||d<r*.8))continue;let f=u<0||rh(Math.atan2(u,r))<Zm?0:Math.hypot(r,u)-r,p=W(s,i);(!a||f<a.cost-1e-9||Math.abs(f-a.cost)<=1e-9&&p>a.side)&&(a={j:n,out:s,edge:c,cost:f,side:p})}if(!a||a.cost>f)break;f-=a.cost;let s=ah(e).map(e=>oh(o,e)).filter(e=>e[1]<=n+1e-4&&W(H(e,a.edge),a.out)>=-1e-4);c(s.length?U(s.reduce(V,[0,0,0]),1/s.length):[a.edge[0],n,a.edge[2]],K(ho(a.out,th)),90),l=a.j}return{steps:a,rest:o,time:s}}function _h(e,t){let n=t;for(let t of e.steps){if(n<t.time){let e=n/t.time;return lh(t.from,t.pivot,wo(t.axis,t.angle*e*e))}n-=t.time}return e.rest}var vh=(e,t)=>G(t)**2*((e.hi[0]-e.lo[0])**2+(e.hi[1]-e.lo[1])**2+(e.hi[2]-e.lo[2])**2)/(24*Ah),yh={length:{min:.05,max:2},stiffness:{min:0,max:500},damping:{min:0,max:1,default:.5}},bh=9.81,xh=Math.PI/3,Sh=.05,Ch=e=>e>xh?xh:e<-xh?-xh:e,wh=()=>({th:[0,0],w:[0,0],p1:null,p2:null});function Th(e,t,{fps:n,stiffness:r,damping:i,length:a}){let o=1/n,s=r,c=2*i*Math.sqrt(r),l=a>Sh?a:Sh,u=0,d=0;if(e.p1&&e.p2){let r=n*n;u=(t[0]-2*e.p1[0]+e.p2[0])*r,d=(t[2]-2*e.p1[2]+e.p2[2])*r}let f=(e.w[0]+(-s*e.th[0]-u/l)*o)/(1+c*o),p=(e.w[1]+(-s*e.th[1]-d/l)*o)/(1+c*o);return{th:[e.th[0]+f*o,e.th[1]+p*o],w:[f,p],p1:[t[0],t[1],t[2]],p2:e.p1}}function Eh(e,t,n=Sh){let r=Math.max(Sh,e?.length??n);return{fps:t,stiffness:e?.stiffness??bh/r,damping:e?.damping??yh.damping.default,length:r}}var Dh=e=>[Ch(e.th[0]),Ch(e.th[1])];function Oh(e,t){if(t[0]===0&&t[1]===0)return e;let n=fs([-t[1],0,t[0]]);return{...e,pos:e.pos,R:Oo(us(ss(n,Do(e.R))))}}function kh(e){if(!e.length)return Sh;let t=0;for(let n=0;n<3;n++){let r=e.map(e=>e[n]);t=Math.max(t,Math.max(...r)-Math.min(...r))}return Math.max(Sh,t/2)}var Ah=9.8,jh=.03,Mh=.25,Nh=[`prop`,`follow`,`pivot`,`axis`,`channel`],Ph=e=>!!e&&typeof e==`object`&&!Array.isArray(e)&&Nh.every(t=>e[t]===void 0)&&(e.keys!==void 0||e.fall!==void 0),Fh=e=>e?.fall===void 0?[]:Array.isArray(e.fall)?e.fall:[e.fall],Ih=(e,t)=>e?.objects?.[t]??Jl(e)[t]??null,Lh=(e,t)=>Object.keys(e?.objects??{}).filter(n=>n===t||e.objects[n].ancestors?.includes(t));function Rh(e){let t=[];for(let n of[-1,1])for(let r of[0,2])for(let i of[-1,1])t.push(V(e.pos,J(e.R,[n*e.half[0],r*e.half[1],i*e.half[2]])));return t}var zh=e=>Math.max(...Rh(e).map(e=>e[1])),Bh=(e,t)=>{let n=J(Y(e.R),H([t[0],e.pos[1]+e.half[1],t[2]],e.pos));return Math.abs(n[0])<=e.half[0]&&Math.abs(n[2])<=e.half[2]};function Vh(e,t){let n=new Set;for(let[r,i]of Object.entries(t?.objects??{}))[r,...i.ancestors??[]].some(t=>C_(e.objects?.[t]))&&n.add(r);return n}function Hh(e,t,n){let r=Ih(e,t);return Lh(e,t).map(t=>({id:t,...D_(n,O_(r,e.objects[t])),half:e.objects[t].half}))}function Uh(e,t,n,r,i=null){let a=Hh(t,n,r),o=new Set(a.map(e=>e.id)),s=Vh(e,t);if(!a.length)return{support:null,top:0,h:0};let c=Math.min(...a.flatMap(e=>Rh(e).map(e=>e[1]))),l=a.flatMap(Rh).reduce((e,t)=>V(e,t),[0,0,0]).map(e=>e/(a.length*8)),u=(i?Lh(t,i):Object.keys(t.objects)).filter(e=>!o.has(e)&&!s.has(e)),d=null;for(let e of u){let n=t.objects[e],r=zh(n);Bh(n,l)&&r<=c+.005&&(!d||r>d.top)&&(d={support:e,top:r})}if(!d&&i)for(let e of u){let n=zh(t.objects[e]);n<=c+.005&&(!d||n>d.top)&&(d={support:e,top:n})}return d??={support:null,top:0},{...d,h:Math.max(0,c-d.top)}}var Wh=new WeakMap;function Gh(e,t){Wh.has(e)||Wh.set(e,new Map);let n=Wh.get(e);return n.has(t)||n.set(t,ih(Hh(e,t,{pos:[0,0,0],R:bo()}))),n.get(t)}function Kh(e,t,n,r,i,a,o,s=null){let c=Wm(a,r,s,o),l=Gm(c),u=r=>Uh(e,t,n,r,a.onto??null),d=l?Jm(u,r,c,Ah,Object.values(t.objects).map(zh)):u(r),f=a.tumble===!1?null:Gh(t,n);if(f){let e=s?ph(s.R,r.R,o):[0,0,0],t=mh(f,r,e,d.top,o,c),n=gh(f,t.at(t.tl),d.top,Ym*d.h+vh(f,e),[-e[2],0,e[0]]);if(n.steps.length||e.some(e=>e)||l)return{t0:i,land:i+t.tl*o,end:i+(t.tl+n.time)*o,h:d.h,support:d.support,top:d.top,at:e=>{let a=(e-i)/o;return a<=0?r:a<=t.tl?t.at(a):_h(n,a-t.tl)},rest:n.rest}}let p=d.h,m=l?Km(p,c[1],Ah):Math.sqrt(2*p/Ah),h=qm(c,1/0,m),g=Math.min(.6,Math.max(0,a.bounce??Mh)),_=Math.min(g*Ah*m,Math.sqrt(2*Ah*jh)),v=2*_/Ah,y={pos:[r.pos[0]+h[0],r.pos[1]-p,r.pos[2]+h[2]],R:r.R};return{t0:i,land:i+m*o,end:i+(m+v)*o,h:p,support:d.support,top:d.top,at:e=>{let t=(e-i)/o;if(t<=0)return r;let n=t<=m?(l?c[1]*t:0)-.5*Ah*t*t:t<=m+v?-p+_*(t-m)-.5*Ah*(t-m)**2:-p,a=qm(c,t,m);return{pos:[r.pos[0]+a[0],r.pos[1]+(l?n:Math.min(0,n)),r.pos[2]+a[2]],R:r.R}},rest:y}}function qh(e,t,n=-1/0,r=1/0){let i=b_(e)?[]:[...e.keys??[]].sort((e,t)=>e.f-t.f),a=Fh(e).map(e=>({...e,t:t(e.at)})).filter(e=>e.t>=n&&e.t<r).sort((e,t)=>e.t-t.t),o=[],s=[],c=0;for(let e of i){for(;c<a.length&&a[c].t<t(e.f);)s.length&&o.push({run:s}),s=[],o.push({fall:a[c++]});s.push(e)}for(s.length&&o.push({run:s});c<a.length;)o.push({fall:a[c++]});return o}function Jh(e,t,n,r,i=!0){let a=n,o=!1;for(let n of e)if(n.run){let{t:e}=n.curve;if(t<e[0])return{pose:a,landed:o};if(t<=e[e.length-1])return{pose:zm(n.curve,t),landed:!1};a=zm(n.curve,e[e.length-1]),o=!1}else{if(t<n.fall.t)return{pose:a,landed:o};let e=i?n.plan??=r(a,n.fall):r(a,n.fall);if(t<e.end)return{pose:e.at(t),landed:t>=e.land};a=e.rest,o=!0}return{pose:a,landed:o}}var Yh=(e,t,n,r,i=!0)=>Jh(e,t,n,r,i).pose,Xh=new WeakMap;function Zh(e,t,n,r,i){Xh.has(e.scene)||Xh.set(e.scene,new Map);let a=Xh.get(e.scene),o=`${t}|${i}|${e.grab}|${e.release}`,s=a.get(o);if(s&&s.map===r&&s.o===n&&s.spec===e.spec)return s.events;let c=Ih(e.scene,t),l=r??(e=>e),[u,d]=i===`before`?[-1/0,e.grab]:i===`after`?[e.release,1/0]:[-1/0,1/0],f=qh(n,l,u,d);for(let e of f)e.run&&(e.curve=Im({keys:e.run},l,()=>Do(c.R),null));return a.set(o,{map:r,o:n,spec:e.spec,events:f}),f}var Qh=(e,t)=>(n,r)=>Kh(e.spec,e.scene,t,n,r.t,r,e.spec.fps??30);function $h(e,t,n){let r=Ih(e.scene,t),i=e.spec.objects?.[t];return!r||!i?null:Yh(Zh(e,t,i,e.timeMap,`all`),n,{pos:r.pos,R:r.R},Qh(e,t))}var eg=new WeakMap;function tg(e,t,n){let r=$h(e,t,n),i=e.spec.objects?.[t];if(!r||!i?.spring)return r;eg.has(e.spec)||eg.set(e.spec,new Map);let a=eg.get(e.spec),o=a.get(t);(!o||o.map!==e.timeMap||o.o!==i)&&a.set(t,o={map:e.timeMap,o:i,states:[],length:kh(Lh(e.scene,t).flatMap(t=>Rh(e.scene.objects[t])))});let s=Eh(i.spring,e.spec.fps??30,o.length);for(let i=o.states.length;i<=n;i++){let a=Th(i?o.states[i-1]:wh(),(i===n?r:$h(e,t,i)).pos,s);o.states[i]=ng(e,t,i)?{...a,th:[0,0],w:[0,0]}:a}return Oh(r,Dh(o.states[n]))}function ng(e,t,n){let r=Ih(e.scene,t);return Jh(Zh(e,t,e.spec.objects[t],e.timeMap,`all`),n,{pos:r.pos,R:r.R},Qh(e,t)).landed}function rg(e,t,n,r,i){let a=Ih(e.scene,t);return!a||!Fh(n).length?a&&{pos:a.pos,R:a.R}:Yh(Zh({...e,grab:i},t,n,e.timeMap,`before`),r,{pos:a.pos,R:a.R},Qh(e,t))}function ig(e,t,n,r,i,a,o=null){return ag(e,t,n,r,i,a,o)?.pose??null}function ag(e,t,n,r,i,a,o=null){let s=Fh(n).length?Zh({...e,release:i},t,n,e.timeMap,`after`):[];return s.length?Jh(s,r,a,(n,r)=>Kh(e.spec,e.scene,t,n,r.t,r,e.spec.fps??30,r.t<=i+1?o:null),!1):null}function og(e,t,n){let r=e.timeMap??(e=>e);return Fh(t).some(e=>r(e.at)>=n)}function sg(e,t){let n=e?.objects??{};return Object.keys(n).filter(e=>e===t||n[e].ancestors?.includes(t))}function cg(e,t){return b_(e)&&t>=(e.grab??0)&&(e.release===void 0||t<=e.release)}function lg(e,t){return e?.objects?.[t]??Jl(e)[t]??null}function ug(e,t,n){return[n,...t?.objects?.[n]?.ancestors??Jl(t)[n]?.ancestors??[]].find(t=>C_(e.objects?.[t]))??null}function dg(e,t){let n=t=>e.timeMap?Math.round(e.timeMap(t)):t;return[n(t.grab??0),t.release===void 0?e.frameCount-1:n(t.release)]}var fg=(e,t,n)=>n.at===void 0&&n.along===void 0&&(!e?.objects?.[t]&&!!Jl(e)[t]||n.grab!==void 0),pg=new WeakMap,mg=new WeakMap,hg=new WeakMap,gg=e=>({spec:e.ctx.spec,scene:e.ctx.scene,timeMap:e.timeMap});function _g(e,t,n){let{spec:r,scene:i}=e.ctx,a=ug(r,i,t),o=r.objects?.[a];if(!b_(o))return null;let s=rg(gg(e),a,o,n,dg(e,o)[0]);return s&&(a===t?s:D_(s,O_(lg(i,a),lg(i,t))))}function vg(e,t){hg.has(e)||hg.set(e,new Map);let n=hg.get(e);if(n.has(t))return n.get(t);let{spec:r,scene:i}=e.ctx,a=r.objects?.[t],o=lg(i,t),s=sg(i,t),c=null;if(b_(a)&&a.release!==void 0&&o&&s.length){let n=dg(e,a)[1];if(n<e.frameCount-1&&!og(gg(e),a,n)){let l=xg(e,t,a,n),u=s.flatMap(e=>Rh({...D_(l,O_(o,i.objects[e])),half:i.objects[e].half})),d=Math.min(...u.map(e=>e[1])),f=u.reduce((e,t)=>V(e,t),[0,0,0]).map(e=>e/u.length);for(let[a,o]of Object.entries(i.objects)){let l=s.includes(a)?null:ug(r,i,a),u=r.objects?.[l];if(!l||l===t||b_(u)||x_(u))continue;let p={...kg(e,a,n),half:o.half},m=zh(p);Bh(p,f)&&m<=d+.005&&(!c||m>c.top)&&(c={mover:l,top:m})}}}return n.set(t,c?.mover??null),c?.mover??null}function yg(e,t){let n=e.frames[t-(e.f0??0)];if(n)return n;pg.has(e)||pg.set(e,new Map);let r=pg.get(e);return r.has(t)||r.set(t,dS(e.ctx,Hf(e.baked,t),t)),r.get(t)}function bg(e,t,n,r,i){let{sk:a,spec:o,scene:s}=e.ctx;if(!fg(s,t,n))return E_(a,o,i,n);let c=ul(o,n,s,t);if(n.keys?.length&&e.ctx.hold){if(e.ctx.hold.attaching(t))return lg(s,t);let l=D_(E_(a,o,i,{prop:n.prop},c),e.ctx.hold.attachAt(t,r)),u=dg(e,n)[0];return c?gl(_g(e,t,u)??lg(s,t),l,hl(u,r)):l}let l=e=>E_(a,o,e,{prop:n.prop},c),u=dg(e,n)[0],d=O_(l(u===r?i:yg(e,u).s),_g(e,t,u)??lg(s,t));return c?gl(D_(l(i),d),D_(l(i),pl(a,o,s,t,n,d)),hl(u,r)):D_(l(i),d)}function xg(e,t,n,r){let i=yg(e,r);mg.has(i)||mg.set(i,new Map);let a=mg.get(i);return a.has(t)||a.set(t,bg(e,t,n,r,i.s)),a.get(t)}function Sg(e,t,n,r=null){let i=e.ctx.spec.objects?.[t];if(i?.spring&&Ph(i))return tg(gg(e),t,n);let a=Eg(e,t,n,r);return i?.spring&&a&&b_(i)?Oh(a,wg(e,t,i,n,r?a:null)):a}var Cg=new WeakMap;function wg(e,t,n,r,i){Cg.has(e)||Cg.set(e,new Map);let a=Cg.get(e),o=e.f0??0,s=e.fps??e.ctx.spec.fps??30,{scene:c}=e.ctx;a.has(t)||a.set(t,{states:[],keys:[],length:kh(sg(c,t).flatMap(e=>Rh(c.objects[e])))});let l=a.get(t),u=Eh(n.spring,s,l.length),d=dg(e,n)[1],f=i?r-1:r,p=0;for(;p<=f&&p<l.states.length&&l.keys[p]===(e.frames[p-o]??null);)p+=1;l.states.length=p,l.keys.length=p;let m=(r,i,a)=>{let o=i>d?ag(...Tg(e,t,n,i,d)):null,s=Th(r,(a??o?.pose??Eg(e,t,i)).pos,u);return o?.landed?{...s,th:[0,0],w:[0,0]}:s};for(;p<=f;p++)l.states[p]=m(p?l.states[p-1]:wh(),p,null),l.keys[p]=e.frames[p-o]??null;let h=f>=0?l.states[f]:wh();return Dh(i?m(h,r,i):h)}var Tg=(e,t,n,r,i)=>[gg(e),t,n,r,i,xg(e,t,n,i),i>0?xg(e,t,n,i-1):null];function Eg(e,t,n,r=null){let{spec:i,scene:a}=e.ctx,o=C_(i.objects?.[t])?i.objects[t]:void 0,s=lg(a,t);if(x_(o))return af(r?{...e,f0:n,frames:[r]}:e,o,n);if(b_(o)&&(s||!fg(a,t,o))){let[i,a]=dg(e,o),c=Math.max(i,Math.min(n,a));if(n<i&&s)return _g(e,t,n);let l=n>a?ig(...Tg(e,t,o,n,a)):null;if(l)return l;let u=n>a?vg(e,t):null;if(u){let r=xg(e,t,o,a);return D_(Sg(e,u,n),O_(Sg(e,u,a),r))}return r&&c===n?bg(e,t,o,n,r.s):xg(e,t,o,c)}if(!s)return null;if(Ph(o))return $h(gg(e),t,n);if(o&&a.objects[t])return e.ctx.objectsAt(n)[t];if(o){let r=sg(a,t)[0],i=e.ctx.objectsAt(n)[r];return D_(i,O_(a.objects[r],s))}return{pos:s.pos,R:s.R}}function Dg(e,t,n){let r=e.frames?.[n-(e.f0??0)],i=e.ctx.scene,a=sg(i,t);return!r||!a.length?null:a.map(t=>{let r=kg(e,t,n);return{id:t,pos:r.pos,R:r.R,half:i.objects[t].half}})}function Og(e,t,n){let{spec:r,scene:i,sk:a}=e.ctx,o=r.objects?.[ug(r,i,t)];if(b_(o)){let[t,i]=dg(e,o);return n>=t&&n<=i?r.props?.[o.prop]?.hand??null:null}if(!x_(o))return null;let[s,c=``]=String(o.follow).split(/:(.*)/s);if(s===`prop`)return r.props?.[c.split(`.`)[0]]?.hand??null;let l=(s===`joint`||s===`bone`)&&/^(Left|Right)(Arm|ForeArm|Hand)/.exec(Bl(a,c).bone??``);return l?l[1]===`Left`?`l`:`r`:null}function kg(e,t,n,r=null){let{spec:i,scene:a}=e.ctx,o=lg(a,t),s=ug(i,a,t),c=i.objects?.[s];if(!o)return null;if(b_(c)||x_(c)||Ph(c)){let t=Sg(e,s,n,r);return t&&D_(t,O_(lg(a,s),o))}return s?a.objects[t]?e.ctx.objectsAt(n)[t]??o:s===t?Sg(e,t,n):D_(Sg(e,s,n),O_(lg(a,s),o)):{pos:o.pos,R:o.R}}var Ag=.009,jg=8,Mg=70,Ng=5,Pg=15,Fg=.014,Ig=[`Index`,`Middle`,`Ring`,`Pinky`],Lg=.6,Rg=e=>{let t=Math.min(1,Math.max(0,(e-Lg)/.30000000000000004));return t*t*(3-2*t)};function zg(e,t){let n=-1/0;for(let r=0;r+1<e.length;r++)for(let i of t)n=Math.max(n,Rc(i,e[r],e[r+1],Ag));return n}function Bg(e,t,n,r,i){if(r<=0||zg(e,i)>=-.002)return 0;let a=r=>{let i=wo(n,r);return e.map(e=>V(t,J(i,H(e,t))))};if(zg(a(r),i)<-.002)return null;let o=0,s=r;for(let e=0;e<jg;e++){let e=(o+s)/2;zg(a(e),i)>=-.002?s=e:o=e}return s}function Vg(e,t,n,r,i){if(zg(e,i)<-.002)return 0;let a=r=>{let i=wo(n,-r);return e.map(e=>V(t,J(i,H(e,t))))};if(zg(a(r),i)>=-.002)return zg(a(r),i)<zg(e,i)?r:0;let o=0,s=r;for(let e=0;e<jg;e++){let e=(o+s)/2;zg(a(e),i)<-.002?s=e:o=e}return s}var Hg=(e,t,n)=>new Map(e.subtree[n].map(e=>[e,[t.P[e].slice(),t.R[e].map(e=>e.slice())]])),Ug=(e,t)=>{for(let[n,[r,i]]of t)e.P[n]=r.slice(),e.R[n]=i.map(e=>e.slice())};function Wg(e,t,n,r){let i=i=>t.P[e.index[`${n}Hand${r}${i}`]],{d:a,l:o}=Xo(e,t,n),s=U(o,n===`Left`?-1:1),c=e=>K(H(e,U(s,W(e,s)))),l=[1,2,3].map(e=>c(K(H(i(e+1),i(e)))));return[c(a),l[0],l[1]].map((e,t)=>Math.atan2(W(ho(e,l[t]),s),W(e,l[t]))*180/Math.PI)}function Gg(e,t,n,r){let i=H(t,e),a=H(r,n),o=H(e,n),s=W(i,i),c=W(a,a),l=W(a,o),u=W(i,o),d=W(i,a),f=s*c-d*d,p=e=>Math.min(1,Math.max(0,e)),m=f>1e-12?p((d*l-u*c)/f):0,h=c>1e-12?(d*m+l)/c:0;return h<0?(h=0,m=p(-u/s)):h>1&&(h=1,m=p((d-u)/s)),Math.hypot(...H(V(e,U(i,m)),V(n,U(a,h))))}function Kg(e,t,n,r){let i=r=>t.P[e.index[`${n}Hand${r}`]];for(let e of Ig)if(e!==r){for(let t=1;t<=3;t++)for(let n=1;n<=3;n++)if(Gg(i(`${r}${t}`),i(`${r}${t+1}`),i(`${e}${n}`),i(`${e}${n+1}`))<Fg)return!1}return!0}function qg(e,t,n,r,i,a,o,s,c=!0){let l=Bg(r.map(e=>t.P[e]),t.P[n],i,a,o),u=l??(c?a:0);return u>0&&No(e,t,n,t.P[n].slice(),wo(i,u*s)),l!==null}function Jg(e,t,n,{entries:r,stops:i=[],weight:a,preset:o}){if(!r?.length||!(a>0))return{touched:[]};let s=[...r,...i],c=n===`Left`?-1:1,l=t=>e.index[`${n}Hand${t}`],u=[],d=(i,l)=>{let u=!1,d=l.map(e=>t.P[e]),f=U(Xo(e,t,n).l,c),p=[0,1,2].reduce((e,t)=>{let n=wo(f,-ns(o,i,t));return e.map((r,i)=>i>t?V(e[t],J(n,H(r,e[t]))):r)},d),m=zg(d,r)>=-.002&&zg(p,r)<zg(d,r);for(let r=0;r<3;r++){let d=U(Xo(e,t,n).l,c),f=ns(o,i,r),p=m?f:0;p>0&&No(e,t,l[r],t.P[l[r]].slice(),wo(d,-p*a)),u=qg(e,t,l[r],l.slice(r),d,Math.max(0,rs(i,r)-f+p),s,a,!1)}return u};for(let i of Ig){let o=[1,2,3,4].map(e=>l(`${i}${e}`));if(o.some(e=>e===void 0))continue;let f=Hg(e,t,o[0]),p=d(i,o);if(!p&&i!==`Middle`){let s=Hg(e,t,o[0]),{l,n:u}=Xo(e,t,n),m=Math.sign(W(H(r[0].pos,f.get(o[0])[0]),l))*c;for(let r=Ng;r<=Pg&&!p;r+=Ng)Ug(t,f),No(e,t,o[0],t.P[o[0]].slice(),wo(u,m*c*r*a)),p=d(i,o)&&Kg(e,t,n,i);p||Ug(t,s)}let m={Ring:`Middle`,Pinky:`Ring`}[i];if(!p&&m){let r=U(Xo(e,t,n).l,c);for(let c=0;c<3;c++){let l=Wg(e,t,n,m)[c]-Wg(e,t,n,i)[c];l>1&&(p=qg(e,t,o[c],o.slice(c),r,l,s,a,!0))}}p&&u.push(i)}let f=[1,2,3,4].map(e=>l(`Thumb${e}`));if(f.every(e=>e!==void 0)){let{n:r}=Xo(e,t,n),i=!1;for(let n of[1,2]){let o=U(K(ho(K(H(t.P[f[n+1]],t.P[f[n]])),r)),c),l=Vg(f.slice(n).map(e=>t.P[e]),t.P[f[n]],o,Mg,s);l>0&&No(e,t,f[n],t.P[f[n]].slice(),wo(o,-l*a)),i=qg(e,t,f[n],f.slice(n),o,Mg,s,a,!1)}i&&u.push(`Thumb`)}return{touched:u}}function Yg(e,t,n,r,i){let a=null;for(let i of e.spec.fits??[]){let o=e.spec.anchors?.[i.anchor],s=t[`w_${i.anchor}_${r}`]??0;if(i.side!==r||o?.kind!==`object`||!o.grasp||!(s>1e-4)||a&&a.weight>=s||e.objectHand(o.object,n)===r||e.sockets?.get(i.anchor)?.rim)continue;let c=e.objectsAt(n),l=sg(e.scene,o.object).map(e=>c[e]).filter(Boolean),u=Math.min(1,Object.entries(t[`fingers_${r}`]??{}).reduce((e,[t,n])=>e+(t===`relaxed`?0:n||0),0));l.length&&(a={entries:l,weight:Rg(s)*u,preset:t[`fingers_${r}`]})}return a??$g(e,t,n,r,i)}var Xg=4,Zg=(e,t,n)=>e.grasp??{sphere:`spherical`,cylinder:`power`}[sg(t,n).length===1?Mc(t.objects[sg(t,n)[0]]).kind:`box`]??`palm`;function Qg(e,t,n,r){let{spec:i,scene:a}=e,o=t[`fingers_${r}`];for(let[t,s]of Object.entries(i.objects??{})){if(!ul(i,s,a,t)||i.props?.[s.prop]?.hand!==r)continue;let[c,l]=e.carrySpan(s),u=Math.min(1,(n-c)/Xg,s.release===void 0?1:(l-n)/Xg);if(!(u>0))continue;let d=qc[Zg(s,a,t)];return d===`relaxed`?o:{...o,[d]:Math.max(o?.[d]??0,u)}}return o}function $g(e,t,n,r,i){let{spec:a,scene:o}=e;for(let[s,c]of Object.entries(a.objects??{})){if(!ul(a,c,o,s)||a.props?.[c.prop]?.hand!==r||!i)continue;let[l,u]=e.carrySpan(c);if(n<l||n>u||e.hold?.attaching(s))continue;let d=sg(o,s).map(t=>({...o.objects[t],...e.objectPose(t,n,{s:i})})),f=Object.entries(e.objectsAt(n)).filter(([e,t])=>!sg(o,s).includes(e)&&t.half&&!t.carried&&d.some(e=>Math.hypot(...e.pos.map((e,n)=>e-t.pos[n]))<.25+Math.hypot(...t.half))).map(([,e])=>e);if(d.length)return{entries:d,stops:f,weight:1,preset:Qg(e,t,n,r)}}return null}var e_=(e,[t,n])=>Math.min(n,Math.max(t,e));function t_(e,t,n){let r=e.index,i=r[`${n}Hand`],a=r[`${n}ForeArm`],o=e.restWorldRot,s=K(H(t.P[i],t.P[a])),c=q(t.R[a],q(Y(o[a]),o[i])),{axF:l,axD:u,...d}=ic(c,t.R[i],s,J(q(c,Y(t.R[i])),Xo(e,t,n).l)),f=Object.fromEntries(Object.entries(d).map(([e,t])=>[e,e_(t,Us[e])]));if(Object.keys(d).every(e=>Math.abs(d[e]-f[e])<1e-6))return null;let p=q(q(wo(V(U(l,f.flex),U(u,f.dev)),Math.hypot(f.flex,f.dev)),wo(s,f.twist)),c);return No(e,t,i,t.P[i].slice(),q(p,Y(t.R[i]))),{need:d,got:f}}var n_={l:`Left`,r:`Right`},r_=e=>{let t=Math.min(1,Math.max(0,e));return t*t*(3-2*t)},i_=[0,0,1],a_=[`UpLeg`,`Leg`,`Foot`],o_=(e,t=[0,0,0])=>Array.isArray(e)||ArrayBuffer.isView(e)?[e[0],e[1],e[2]]:t,s_=(e,t=0)=>typeof e==`number`&&Number.isFinite(e)?e:t;function c_(e,t,n,r,i,a,o=n.length){for(let s of n){let n=e.index[s];No(e,t,n,t.P[n].slice(),q(X(r/o),q(So(i/o),Co(a/o))))}}var l_=.99,u_=.9995;function d_(e,t,n,r,i,a,o,s){let c=G(H(t.P[r],t.P[n]))+G(H(t.P[i],t.P[r])),l=H(a,t.P[n]),u=G(l),d=l_*c,f=.009500000000000064*c;if(u<=d||u-u_*c>.05)return a;let p=d+f*(1-Math.exp(-(u-d)/f));return o[`reach_over_${s}`]=Math.max(0,u-u_*c),V(t.P[n],U(l,p/u))}var f_=.095,p_=2,m_=new Map;function h_(e,t){let n=`${e.model}|${t}`;if(m_.has(n))return m_.get(n);let r=(90-t)*Math.min(1,Math.max(0,(t-45)/27)),i=Bs(e),a=n=>{let r=Mo(e);return[[`Left`,-1],[`Right`,1]].every(([a,o])=>{let s=e.index[`${a}Arm`],c=e.index[`${a}ForeArm`],l=e.index[`${a}Hand`],u=e.index[`${a}HandMiddle1`];return No(e,r,s,r.P[s].slice(),Co(o*t)),No(e,r,c,r.P[c].slice(),Co(o*n)),[.5,.75,1].map(e=>V(r.P[c],U(H(r.P[l],r.P[c]),e))).concat([r.P[u]]).every(e=>As(i.body,r,e,i.skip).d>=f_)})},o=r;if(i&&r>0){for(let e=0;e<=r;e+=.5)if(!a(e)){o=Math.max(0,e-p_);break}}return m_.set(n,o),o}var g_=60,__=e=>e-360*Math.round(e/360);function v_(e,t,n){let r=__(t),i=__(n),a=(Math.max(Math.abs(r),Math.abs(i))-g_)/60;if(a<=0)return null;let o=a>=1?1:a*a*(3-2*a);return{yaw:e,R:q(X(e),q(So(r*o),Co(i*o)))}}function y_(e,t,n={}){let r=Mo(e),i={},a=s_(t.arm_rest,72),o=s_(t.arm_hang)&&s_(t.arm_hang)*h_(e,a);for(let[n,i,s]of[[`Left`,-1,`l`],[`Right`,1,`r`]]){let c=e.index[`${n}Arm`],l=e.index[`${n}ForeArm`],u=o*(1-Math.min(1,Math.max(0,s_(t[`armw_${s}`])+s_(t[`hangoff_${s}`]))));No(e,r,c,r.P[c].slice(),Co(i*a)),u&&No(e,r,l,r.P[l].slice(),Co(i*u))}for(let[n,i]of Object.entries(n_)){let a=s_(t[`abend_${n}`]),o=s_(t[`aswing_${n}`]),s=e.index[`${i}ForeArm`],c=e.index[`${i}Arm`];a&&(No(e,r,s,r.P[s].slice(),So(-a)),Ko(e,r,i)),o&&No(e,r,c,r.P[c].slice(),So(-o))}c_(e,r,[`Neck`,`Head`],s_(t.head_yaw),s_(t.head_pitch),s_(t.head_roll));let s=s_(t.spine_yaw),c=s_(t.spine_pitch),l=s_(t.spine_roll);c_(e,r,[`Spine`,`Spine1`],s,c,l,3),c_(e,r,[`Spine2`],s_(t.chest_yaw,s),s_(t.chest_pitch,c),s_(t.chest_roll,l),3);let u=e.index.Hips,d=s_(t.yaw);No(e,r,u,r.P[u].slice(),q(X(d),q(So(s_(t.pitch)),Co(s_(t.roll)))));let f=H(o_(t.root,r.P[u]),r.P[u]);for(let e=0;e<r.P.length;e++)r.P[e]=V(r.P[e],f);let p=v_(d,s_(t.pitch),s_(t.roll)),m=p?.R??X(d);for(let[n,a]of Object.entries(n_)){if(!t[`foot_${n}`])continue;let o=o_(t[`foot_${n}`]);i[`leg_miss_${n}`]=Jo(e,r,e.index[`${a}UpLeg`],e.index[`${a}Leg`],e.index[`${a}Foot`],o,J(m,o_(t[`knee_${n}`],i_)),i_,`knee`);let s=Go(e,r,a,o,a_);s>150&&(i[`leg_fold_${n}`]=s),Yo(e,r,a,s_(t[`fyaw_${n}`],d),s_(t[`fpitch_${n}`]),p)}for(let a of n.armOrder??[`r`,`l`]){let o=n_[a],s=s_(t[`armw_${a}`]),c=e.index[`${o}Arm`],l=e.index[`${o}ForeArm`],u=e.index[`${o}Hand`],d=K(J(m,o_(t[`elbow_${a}`],[0,-1,-.3])));if(i[`arm_miss_${a}`]=0,s>1e-4&&n.handTarget){let t=r.P[u].slice(),f=V(t,U(H(n.handTarget(a,r,i)??t,t),s));n.keepOut&&(f=n.keepOut(a,r,f));let p=n.push?.(a);p&&(f=V(f,p));let m=n.sag?.(a,r,f);m&&(f=V(f,m));let h=n.skinPush?.(a);h&&(f=V(f,U(h,r_(s)))),n.softReach&&(f=d_(e,r,c,l,u,f,i,a));let g=V(U(K(H(r.P[l],U(V(r.P[c],t),.5))),1-s),U(d,s));i[`arm_miss_${a}`]=Jo(e,r,c,l,u,f,g,Ks,n.foldFree?null:`elbow`);let _=Go(e,r,o,f);_>145&&!n.foldFree&&(i[`arm_fold_${a}`]=_)}Qo(e,r,o,s_(t[`wtwist_${a}`]),s_(t[`wflex_${a}`])),is(e,r,o,n.fingerWeights?.(a)??t[`fingers_${a}`]);let f=n.hold?.(a,r);(!f||f.w<1)&&n.grip?.(a,r,i),f&&_c(e,r,o,f,Ks,i,a);let p=n.swivel?.(a);p&&(Zo(e,r,o,p*r_(s)),f||t_(e,r,o));let h=n.heldShapes?.(a,r);h&&(i[`closed_${a}`]=Jg(e,r,o,h).touched),n.afterArm?.(a,r,i)}return{s:r,diag:i}}var b_=e=>typeof e?.prop==`string`,x_=e=>!b_(e)&&e?.follow!==void 0,S_=e=>!!e&&typeof e==`object`&&!Array.isArray(e)&&[`prop`,`follow`,`pivot`,`axis`,`channel`,`keys`,`fall`].every(t=>e[t]===void 0),C_=e=>!!e&&typeof e==`object`&&!S_(e);function w_(e,t,n,r){let i=t.props[r.prop];return U(i.origin.map(t=>n.P[e.index[t]]).reduce((e,t)=>V(e,t),[0,0,0]),1/i.origin.length)}function T_(e,t,n){let r=e.index[`${n_[t.hand]}Hand`],i=e.restWorldPos,a=U(t.origin.map(t=>i[e.index[t]]).reduce((e,t)=>V(e,t),[0,0,0]),1/t.origin.length);return Io(n,r,J(Y(e.restWorldRot[r]),H(a,i[r])))}function E_(e,t,n,r,i=!1){let a=Xo(e,n,n_[t.props[r.prop].hand]),o=i?T_(e,t.props[r.prop],n):w_(e,t,n,r),s=e=>V(U(a.d,e[0]),V(U(a.l,e[1]),U(a.n,e[2]))),c=K(s(r.along??[0,0,1])),l=H(a.d,U(c,W(a.d,c)));Math.hypot(...l)<1e-6&&(l=H(a.l,U(c,W(a.l,c)))),l=K(l);let u=ho(l,c);return{pos:V(o,s(r.at??[0,0,0])),R:[[l[0],c[0],u[0]],[l[1],c[1],u[1]],[l[2],c[2],u[2]]]}}var D_=(e,t)=>({pos:V(e.pos,J(e.R,t.pos)),R:q(e.R,t.R)}),O_=(e,t)=>({pos:J(Y(e.R),H(t.pos,e.pos)),R:q(Y(e.R),t.R)});function k_(e,t,n,r){let i=n[e.channel]?.[r]??0,a=wo(e.axis??[0,1,0],i);return{pos:V(e.pivot,J(a,H(t.pos,e.pivot))),R:q(a,t.R??bo()),angle:i}}var A_=.06,j_=.8,M_=.045,N_=.3,P_=30,F_=180/Math.PI,I_=2,L_=[0,1,0],R_=(e,t,n)=>[[e[0],t[0],n[0]],[e[1],t[1],n[1]],[e[2],t[2],n[2]]],z_=(e,t)=>H(e,U(t,W(e,t)));function B_(e,t,n){let r=null;for(let i of e.fits??[]){let e=t[`w_${i.anchor}_${i.side}`]??0;i.side===n&&i.orient!==!1&&e>1e-4&&(!r||e>r.w)&&(r={fit:i,w:e})}return r&&{...r,w:r.w*Math.min(1,Math.max(0,t[`armw_${n}`]??0))}}function V_(e,t,n,r,i){if(i.prop){let a=t.props?.[i.prop];if(!a)return null;let o=Xo(e,n,r),s=U(a.origin.map(t=>n.P[e.index[t]]).reduce(V,[0,0,0]),1/a.origin.length),[c,l,u]=i.point===`origin`?[0,0,0]:a.points?.[i.point]??[0,0,0];return V(s,V(U(o.d,c),V(U(o.l,l),U(o.n,u))))}let a=i.joints??[`${r}HandIndex2`,`${r}HandMiddle2`];return U(a.map(t=>n.P[e.index[t]]).reduce(V,[0,0,0]),1/a.length)}function H_(e,t){let{spec:n}=e,r=e.scene?.objects?.[t];for(let e of[t,...r?.ancestors??[]]){let t=n.objects?.[e];if(t?.prop)return{key:e,entry:t,side:n.props?.[t.prop]?.hand??null}}return null}function U_(e,t,n,r){let i=e.spec.objects?.[t],a=e.scene?.objects?.[t]?.half;if(!e.hold?.span||!i?.prop||e.spec.props?.[i.prop]?.hand!==n||!i.keys?.length||i.grab===void 0||i.at!==void 0||i.along!==void 0||a&&K_(a)>=0)return null;let[o]=e.hold.span(t);return o>=1&&r<=Math.max(o,e.hold.firstKey(t)-1)?Math.min(r,o-1):null}function W_(e,t,n,r,i,a){let o=e.scene?.objects??{},s=i?.kind===`object`?sg(e.scene,i.object):Object.keys(o),c=null;for(let i of s){let s=o[i]?.half;if(!s)continue;let l=U_(e,H_(e,i)?.key,n,t),u=e.objectPose?.(i,l??t,l===null?a:null)??o[i];if(!u?.R)continue;let d={pos:u.pos,R:u.R,half:s},f=wc(r,d);(!c||f<c.d)&&(c={box:d,d:f,id:i})}let l=c&&H_(e,c.id);return!c||l?.side===n&&U_(e,l.key,n,t)===null?null:i?.kind===`object`||c.d<=A_?{...c.box,id:c.id}:null}var G_=[0,1,2];function K_(e){let t=G_.reduce((t,n)=>e[n]>e[t]?n:t,0);return G_.filter(e=>e!==t).every(t=>e[t]<M_)?t:-1}function q_(e,t,n,r,i){let a=e===`Right`,o=J(X(r??0),[a?1:-1,0,0]),s=Math.abs(t[1]),c=z_(V(U(L_,1-s),U(o,s)),t),l=K(G(c)>.001?c:z_(o,t)),u=i?z_(i,t):null;if(!u||G(u)<=N_)return R_(t,l,ho(t,l));let d=e=>Math.acos(Math.max(-1,Math.min(1,W(e,n))))*F_-(W(e,l)>0?P_:0),f=K(u),p=d(f)<=d(U(f,-1))?f:U(f,-1);return R_(t,p,ho(t,p))}function J_(e,t,n){let r=[e[0][0],e[1][0],e[2][0]],i=[e[0][1],e[1][1],e[2][1]],a=Math.atan2(W(ho(t,i),r),W(t,i))*F_,[o,s]=Ws.twist,c=Math.min(s,Math.max(o,n+a))-n;if(Math.abs(c-a)<1e-6)return e;let l=J(wo(r,c),t);return R_(r,l,ho(r,l))}function Y_(e,t,n,r,i,a,o,s){let c=B_(e.spec,a,i),l=Dm(e,i,o),u=c&&c.w>=.001&&wm(e.spec,c.fit.anchor);if(l||u?Tm(e.spec,i):Math.abs(a[`wtwist_${i}`]??0)>.001||Math.abs(a[`wflex_${i}`]??0)>.001)return;if(l&&o>l.grab)return l.keyed?void 0:Am(e,t,n,r,i,l);if(!c||c.w<.001)return;if(u)return Om(e,t,n,r,i,a,s,c,n=>V_(t,e.spec,n,r,c.fit.effector??{}),null,o);if(Object.keys(e.spec.objects??{}).some(t=>e.spec.objects[t]?.prop&&e.objectHand?.(t,o)===i&&U_(e,t,i,o)===null))return;let d={s:n,diag:s,c:a},f=e.spec.anchors?.[c.fit.anchor];if(f?.kind===`prop`)return;let p=V(Fd(e,c.fit.anchor,n,s,a,i),c.fit.offset??[0,0,0]),m=W_(e,o,i,p,f,d),h=m&&V_(t,e.spec,n,r,c.fit.effector??{});if(!h)return;let g=n=>({pos:V_(t,e.spec,n,r,c.fit.effector??{}),R:(({d:e,l:t,n})=>R_(e,t,n))(Xo(t,n,r))}),_=t.index,v=_[`${r}Arm`],y=_[`${r}ForeArm`],b=_[`${r}Hand`],x=K_(m.half),S=x>=0?J(m.R,G_.map(e=>+(e===x))):null;if(S&&Math.abs(S[1])>j_&&!H_(e,m.id))return Om(e,t,n,r,i,a,s,c,n=>V_(t,e.spec,n,r,c.fit.effector??{}),{w:{p,axis:S},type:`power`},o);let C=Xo(t,n,r),w=K(z_(C.l,C.d)),T=K(H(n.P[b],n.P[y])),E=q(n.R[y],q(Y(t.restWorldRot[y]),t.restWorldRot[b])),D=ic(E,n.R[b],T,J(q(E,Y(n.R[b])),C.l)).twist,{goal:O,plane:k,wristAt:ee}=gc(t,n,r,{pos:h,R:J_(q_(r,C.d,w,a.yaw,S),w,D)},g(n),c.w,`palm`),A={twist:0,flex:0,dev:0};for(let e=0;e<I_;e++)Jo(t,n,v,y,b,ee(e?n.R[b]:O),k,Ks,`elbow`),A=mc(t,n,r,b,y,O);s[`grip_${i}`]={w:c.w,...A}}var X_={period:3.8,deg:.8},Z_={yaw:.9,pitch:.6},Q_={period:5.6,m:.012,list:1.4},$_=.5,ev=1e-4,tv=2*Math.PI,nv=e=>e*e*(3-2*e),rv=(e,t)=>Array.isArray(e)?e.some((e,n)=>Math.abs(e-t[n])>ev):e&&typeof e==`object`?Object.keys({...e,...t}).some(n=>Math.abs((e[n]??0)-(t?.[n]??0))>.001):Math.abs((e??0)-(t??0))>.01;function iv(e,t){let n=2166136261;for(let t=0;t<e.length;t++)n=Math.imul(n^e.charCodeAt(t),16777619);let r=n>>>0;return Array.from({length:t},()=>{r=r+1831565813>>>0;let e=Math.imul(r^r>>>15,r|1);return e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296*tv})}function av(e,t,n,r){let i=Array(n).fill(!1),a=Object.keys(e);i[0]=!0;for(let t=1;t<n;t++)a.some(n=>rv(e[n][t],e[n][t-1]))&&(i[t]=i[t-1]=!0);let o=a.filter(e=>/^(armw_[lr]|w_.+_[lr])$/.test(e));for(let t=0;t<n;t++)o.some(n=>e[n][t]>.001)&&(i[t]=!0);for(let e of Object.values(t.objects??{}))if(Number.isFinite(e?.grab))for(let t=Math.max(0,e.grab);t<Math.min(n,Number.isFinite(e.release)?e.release:n);t++)i[t]=!0;for(let e of t.goals??[]){let t=Array.isArray(e?.at)?e.at:null;if(!(e?.still===void 0||!t?.length))for(let e=Math.max(0,Math.round(t[0]));e<=Math.min(n-1,Math.round(t[t.length-1]));e++)i[e]=!0}let s=Math.max(1,Math.round($_*r)),c=Array(n).fill(1/0);for(let e=0,t=-1/0;e<n;e++)i[e]&&(t=e),c[e]=e-t;for(let e=n-1,t=1/0;e>=0;e--)i[e]&&(t=e),c[e]=Math.min(c[e],t-e);return c.map(e=>nv(Math.min(1,e/s)))}function ov(e,t,n,r){let i={},a=Math.max(1,Math.round($_*r));for(let r of[`l`,`r`]){let o=Object.keys(e).filter(e=>e===`armw_${r}`||RegExp(`^w_.+_${r}$`).test(e)),s=Array.from({length:n},(t,n)=>o.some(t=>e[t][n]>.001));for(let e of Object.values(t.objects??{}))if(!(!Number.isFinite(e?.grab)||t.props?.[e.prop]?.hand!==r))for(let t=Math.max(0,e.grab);t<Math.min(n,Number.isFinite(e.release)?e.release:n);t++)s[t]=!0;if(!s.some(Boolean)){i[r]=null;continue}let c=Array(n).fill(1/0);for(let e=0,t=-1/0;e<n;e++)s[e]&&(t=e),c[e]=e-t;for(let e=n-1,t=1/0;e>=0;e--)s[e]&&(t=e),c[e]=Math.min(c[e],t-e);i[r]=c.map(e=>1-nv(Math.min(1,e/a)))}return i}function sv(e,{spec:t,sk:n,frameCount:r}){if(t.idle===!1||!e.root||!e.foot_l||!e.foot_r)return null;let i=t.fps??30,a=av(e,t,r,i);if(!a.some(e=>e>0))return null;let o=n.restWorldPos,s=o[n.index.Hips][1],c=o[n.index.LeftFoot][1],[l,u,d,f,p]=iv(JSON.stringify([e.root[0].map(e=>e.toFixed(3)),(e.yaw?.[0]??0).toFixed(1)]),5),m=Array(r).fill(null);for(let t=0;t<r;t++){if(!(a[t]>0))continue;let n=t/i,r=a[t],o=m[t]={spine_pitch:-r*X_.deg*Math.sin(tv*n/X_.period+l),head_yaw:r*Z_.yaw*(.6*Math.sin(tv*n/7.3+u)+.4*Math.sin(tv*n/11.9+p)),head_pitch:r*Z_.pitch*Math.sin(tv*n/9.1+d)};if(![`l`,`r`].every(n=>e[`foot_${n}`][t][1]<c+.03&&Math.abs(e[`fpitch_${n}`]?.[t]??0)<2)||e.root[t][1]<s-.15)continue;let h=r*Math.sin(tv*n/Q_.period+f),g=(e.yaw?.[t]??0)*Math.PI/180;o.root=[Math.cos(g)*Q_.m*h,0,-Math.sin(g)*Q_.m*h],o.roll=Q_.list*h,o.spine_roll=-Q_.list*h}return m}function cv(e,t,n){let r=t?.[n];if(!r)return e;let i={...e};for(let[t,n]of Object.entries(r))i[t]=Array.isArray(n)?Array.isArray(e[t])?e[t].map((e,t)=>e+n[t]):e[t]:(Number(e[t])||0)+n;for(let t of[`chest_pitch`,`chest_roll`])e[t]!==void 0&&r[t.replace(`chest`,`spine`)]!==void 0&&(i[t]=e[t]+r[t.replace(`chest`,`spine`)]);return i}var lv=(e,t,n)=>Math.min(n,Math.max(t,e));function uv(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);let n=t>>>0;return()=>{n=n+1831565813>>>0;let e=Math.imul(n^n>>>15,n|1);return e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296*2-1}}var dv={noise:.02,side:.03,first:.22,second:.08,last:.22,beforeLast:.08,turn:0},fv={noise:.025,side:.012,stride:.035,second:.05,beforeLast:.06,turn:.06},pv={noise:.1,first:.1,last:.25},mv=.1,hv=3,gv=60;function _v(e,{s0:t,turn:n,seed:r}){let i=e.steps,a=lv(e.vary??1,0,2),o=uv(r),s=Array.from({length:i},()=>({time:o(),length:o(),lift:o(),arm:o()})),c=o()<0?1:-1,l=e=>e%2==0?c:-c,u=Array.from({length:Math.ceil(i/2)},()=>o()),d=e=>u[Math.floor((e-1)/2)],f=Array.from({length:i},(t,n)=>n===i-1?0:n===0?e.firstStep:e.step),p=t,m=f.map(e=>{let t=Math.abs(n(p,p+e));return p+=e,Math.min(1,t/gv)}),h=i>=4,g=s.map((e,t)=>{if(i<2)return 1;let n=(t===0||t===i-1?.5:1)*(dv.noise*e.time+dv.side*l(t))+dv.turn*m[t];return t===0&&(n+=dv.first*(1-m[0])),t===1&&h&&(n+=dv.second),t===i-1&&(n+=dv.last),t===i-2&&h&&(n+=dv.beforeLast),1+a*n}),_=g.reduce((e,t)=>e+t,0),v=i*e.period,y=[];for(let e=0,t=0;e<i;e++)y.push(Math.round(t)),t+=v*g[e]/_;let b=e.period-e.swing,x=y.map((t,n)=>{if(a===0)return e.swing;let r=(n<i-1?y[n+1]:v)-t;return Math.min(r-2,Math.max(e.swing,r-b),n===i-1?e.swing+hv:1/0)}),S=f.map((e,t)=>t>0&&t<i-1),C=s.map((e,t)=>{if(!S[t])return 1;let n=fv.noise*(.7*e.length+.3*e.time)+fv.side*l(t)+fv.stride*d(t)-fv.turn*m[t];return t===1&&h&&(n-=fv.second),t===i-2&&h&&(n-=fv.beforeLast),1+a*n}),w=S.filter(Boolean).length,T=C.reduce((e,t,n)=>e+(S[n]?t:0),0);return{lift:y,air:x,inc:f.map((e,t)=>S[t]&&a>0?e*C[t]*w/T:e),height:s.map((t,n)=>e.lift*(1+a*(pv.noise*t.lift-(n===0?pv.first:0)-(n===i-1&&i>1?pv.last:0)))),arm:s.map(e=>1+a*mv*e.arm)}}var vv=18,yv=22,bv=7,xv=45,Sv=1,Cv=.4,wv=50,Tv=15,Ev=13,Dv={strike:4,load:4,mid:3,toeOff:5},Ov={strike:2,load:14,mid:7,toeOff:48,pow:1.8},kv=[1,2.2],Av=e=>{let t=Math.min(1,Math.max(0,((e??kv[1])-kv[0])/(kv[1]-kv[0])));return t*t*(3-2*t)},jv=.004,Mv=8,Nv=.008,Pv=.35,Fv=.001,Iv=.25,Lv=[.25,.5],Rv=.008,zv=e=>e*e*e*(e*(6*e-15)+10),Bv=new WeakSet,Vv=(e,t,n,r)=>V(e,J(X(t),J(So(n),J(X(-t),H(r,e)))));function Hv(e,t,n){let r=e.index,i=e.restWorldPos,a=G(H(i[r.LeftLeg],i[r.LeftUpLeg])),o=G(H(i[r.LeftFoot],i[r.LeftLeg])),s=Math.min(1,Math.max(0,(Ev-t)/4)),c=Av(n),l=(e,t)=>e+(t-e)*c,u=l(Ov.strike,vv)+s*Dv.strike,d=l(Ov.load,yv)+s*Dv.load,f=l(Ov.mid,bv)+s*Dv.mid,p=l(Ov.toeOff,xv)+s*Dv.toeOff;return{reach:e=>Math.sqrt(a*a+o*o+2*a*o*Math.cos(e*Math.PI/180)),hipOff:{l:H(i[r.LeftUpLeg],i[r.Hips]),r:H(i[r.RightUpLeg],i[r.Hips])},strike:u,load:d,mid:f,trail:e=>f+(p-f)*Math.min(1,Math.max(0,e))**l(Ov.pow,Sv)}}var Uv=(e,t,n)=>V(e.root[t],J(X(e.yaw?.[t]??0),J(Co(e.roll?.[t]??0),n)));function Wv(e,t,{f0:n,end:r,period:i,pace:a,ground:o,start:s}){let c=e.index,l=e.restWorldPos,{reach:u,hipOff:d,strike:f,load:p,mid:m,trail:h}=Hv(e,i,a),g=Math.max(2,Math.round(Pv*i)),_=(e,t)=>{if(t<e.a)return f;if(e.heel!==void 0&&t>=e.heel)return h((t-e.heel)/Math.max(1,e.b-e.heel));let n=(t-e.a)/i/Cv;return e.strike&&n<1?(n<.5?f:m)+(p-(n<.5?f:m))*Math.sin(Math.PI*n):m},v=Vf(t,r+1),y=l[c.Hips][1]-Nv,b=v.root.map(e=>[e[0],e[2]]);for(let e=0;e<2;e++)b=b.map((e,t)=>{if(t<=n||t>=r)return e;let i=0,a=0,o=0;for(let e=-6;e<=6;e++){let s=Math.min(r,Math.max(n,t+e)),c=Math.exp(-(e*e)/8);i+=c*b[s][0],a+=c*b[s][1],o+=c}let s=Math.min(1,(t-n)/Mv,(r-t)/Mv),c=s*s*(3-2*s);return[e[0]+(i/o-e[0])*c,e[1]+(a/o-e[1])*c]});let x=e=>{let t=[b[e][0],v.root[e][1],b[e][1]],i=v.yaw?.[e]??0,a=v.roll?.[e]??0,s=[];for(let n of[`l`,`r`]){let r=o[n].find(t=>e>=t.a-(t.strike?g:0)&&e<=t.b);if(!r||r.free!==void 0&&e>=r.free)continue;let c=v[`foot_${n}`][e],l=J(X(i),J(Co(a),d[n])),f=u(_(r,e)),p=Math.hypot(t[0]+l[0]-c[0],t[2]+l[2]-c[2]);p<f&&s.push(c[1]+Math.sqrt(f*f-p*p)-l[1])}if(!s.length)return y;let c=Math.min(...s),l=Math.min(y,c-jv*Math.log(s.reduce((e,t)=>e+Math.exp(-(t-c)/jv),0)))-Fv,f=Math.min(1,(e-n)/Mv,(r-e)/Mv),p=f*f*(3-2*f);return t[1]+(l-t[1])*p};for(let e of[`l`,`r`])for(let t of o[e]){if(t.heel===void 0||!t.flat)continue;let e=J(X(t.yw),[0,0,1]),r=Math.max(n+1,t.a);for(;r<t.heel&&(b[r][0]-t.flat[0])*e[0]+(b[r][1]-t.flat[2])*e[2]<0;)r++;t.free=r}let S=[];for(let e=n;e<=r;e++)S[e]=x(e);let C=Math.max(2,Math.round(Iv*i)),w=(e,t)=>{let n=e;for(let r=e;r<=t;r++)S[r]<S[n]&&(n=r);return n},T=[...new Set([`l`,`r`].flatMap(e=>o[e].filter(e=>e.strike&&e.a>n+2&&e.a<r-2).map(e=>e.a)))].sort((e,t)=>e-t),E=[{f:n,y:S[n]}];T.forEach((e,t)=>{let n=w(Math.max(E.at(-1).f+2,e-2),Math.min(r-2,e+C));if(t>0){let e=E.at(-1),t={f:n,y:S[n]},r=t.f-e.f,i=null;for(let n=Math.ceil(e.f+Lv[0]*r);n<=Math.floor(e.f+Lv[1]*r);n++){let r=S[n];for(let t=e.f+1;t<n;t++){let i=zv((t-e.f)/(n-e.f));i>1e-6&&(r=Math.min(r,e.y+(S[t]-e.y)/i))}for(let e=n+1;e<t.f;e++){let i=zv((e-n)/(t.f-n));i<1-1e-6&&(r=Math.min(r,(S[e]-t.y*i)/(1-i)))}(!i||r>i.y)&&(i={f:n,y:r})}i&&i.y>Math.max(e.y,t.y)&&E.push(i)}n>E.at(-1).f&&E.push({f:n,y:S[n]})}),E.push({f:r,y:S[r]});for(let e=1;e+1<E.length;e++){let t=E[e],n=Math.min(...[E[e-1],E[e+1]].map(e=>e.y+Rv*(t.f-e.f)**2/2));t.y>Math.max(E[e-1].y,E[e+1].y)&&(t.y=Math.min(t.y,n))}let D=[];for(let e=0;e<30;e++){let e=0,t=Kv(E.map(e=>e.f),E.map(e=>e.y),0,0);for(let i=0;i+1<E.length;i++){let a=E[i],o=E[i+1],s=0;for(let e=a.f;e<=o.f;e++)D[e]=t(e),s=Math.max(s,D[e]-S[e]);if(s>3e-4){let t=a.y>o.y&&i>0||o.f===r?a:o;t.f!==n&&t.f!==r&&(t.y-=s,e=Math.max(e,s))}}if(!e)break}for(let e=n;e<=r;e++)D[e]=Math.min(D[e],S[e]);let O=t.filter(e=>/ step \d+$/.test(e.src??``)).sort((e,t)=>e.f-t.f),k=0,ee=s;for(let e=n+1;e<r;e++){for(;k<O.length&&O[k].f<=e;)ee=O[k++].src;t.push({f:e,set:{root:[b[e][0],D[e],b[e][1]]},src:ee})}}function Gv(e,t,{end:n,period:r,pace:i,ground:a}){let{reach:o,hipOff:s,trail:c}=Hv(e,r,i),l=Vf(t,n+1),u=new Map(t.map(e=>[e.f,e.src]));for(let e of[`l`,`r`])for(let r of a[e]){if(r.free===void 0||!Number.isFinite(r.b)||r.b>n)continue;let i=[],a=[],d=0;for(let t=r.free;t<=r.b;t++){let n=Uv(l,t,s[e]),u=o(c((t-r.heel)/Math.max(1,r.b-r.heel))),f=e=>G(H(n,Vv(r.ball,r.yw,e,r.flat)))-u,p=d,m=wv;if(f(p)<=0)m=p;else if(f(m)<=0)for(let e=0;e<24;e++){let e=(p+m)/2;f(e)>0?p=e:m=e}d=m,i.push(m),a.push({f:t,hip:n,want:u})}let f=i.map((e,t)=>Math.max(...i.slice(t).map((e,t)=>e-t*Tv)));for(let e=0;e<2;e++)f=f.map((e,t)=>Math.max(i[t],((f[t-1]??0)+e+(f[t+1]??e))/3));a.forEach(({f:n,hip:i,want:a},o)=>{let s=Vv(r.ball,r.yw,f[o],r.flat),c=G(H(i,s))-a;c>0&&(s=V(s,U(H(i,s),c/G(H(i,s))))),t.push({f:n,set:{[`foot_${e}`]:s,[`fpitch_${e}`]:f[o],[`fyaw_${e}`]:r.yw},src:u.get(n)})})}}function Kv(e,t,n,r){let i=e.length-1,a=e.slice(1).map((t,n)=>t-e[n]),o=[],s=[],c=[],l=[];for(let e=0;e<=i;e++)e===0?(o[e]=0,s[e]=2*a[0],c[e]=a[0],l[e]=6*((t[1]-t[0])/a[0]-n)):e===i?(o[e]=a[i-1],s[e]=2*a[i-1],c[e]=0,l[e]=6*(r-(t[i]-t[i-1])/a[i-1])):(o[e]=a[e-1],s[e]=2*(a[e-1]+a[e]),c[e]=a[e],l[e]=6*((t[e+1]-t[e])/a[e]-(t[e]-t[e-1])/a[e-1]));for(let e=1;e<=i;e++){let t=o[e]/s[e-1];s[e]-=t*c[e-1],l[e]-=t*l[e-1]}let u=[];u[i]=l[i]/s[i];for(let e=i-1;e>=0;e--)u[e]=(l[e]-c[e]*u[e+1])/s[e];return n=>{let r=0;for(;r<i-1&&n>e[r+1];)r++;let o=n-e[r],s=a[r],c=(e[r+1]-n)/s,l=o/s;return c*t[r]+l*t[r+1]+((c**3-c)*u[r]+(l**3-l)*u[r+1])*s*s/6}}var qv=3,Jv=.35,Yv=.2,Xv=.03,Zv=.04,Qv=.025,$v=e=>e*180/Math.PI,ey=e=>{let t=Math.min(1,Math.max(0,e));return t*t*(3-2*t)};function ty(e,t,n,r,i){let a=H(t,e),o=Math.min(r+i-1e-6,Math.max(Math.abs(r-i)+1e-6,G(a))),s=U(a,1/G(a)),c=H(n,U(s,W(n,s)));c=U(c,1/(G(c)||1));let l=(r*r+o*o-i*i)/(2*r*o),u=H(t,V(e,V(U(s,r*l),U(c,r*Math.sqrt(Math.max(0,1-l*l))))));return $v(Math.atan2(-W(u,n),-u[1]))}function ny(e,{end:t,ground:n,sk:r}){let i=Vf(e,t+2),a=new Map(e.map(e=>[e.f,e.src])),o=r?.index,s=r?.restWorldPos,c=r&&G(H(s[o.LeftLeg],s[o.LeftUpLeg])),l=r&&G(H(s[o.LeftFoot],s[o.LeftLeg]));for(let u of[`l`,`r`]){let d=n[u],f=u===`l`?`Left`:`Right`,p=r&&H(s[o[`${f}UpLeg`]],s[o.Hips]),m=r&&H(s[o[`${f}ToeBase`]],s[o[`${f}Foot`]]),h=r&&s[o[`${f}ToeBase`]][1],g=r&&[0,.005-s[o[`${f}Foot`]][1],-.045];for(let n=0;n+1<d.length;n++){let o=d[n],s=d[n+1];if(!Number.isFinite(o.b)||!s.strike||s.a>t||s.a-o.b<3)continue;let f=[...new Set(e.filter(e=>!Bv.has(e)&&e.f>o.b&&e.f<s.a&&e.set[`foot_${u}`]).map(e=>e.f))].sort((e,t)=>e-t),_=[o.b,...f,s.a],v=i[`foot_${u}`],y=e=>v[Math.max(0,Math.min(v.length-1,e))],b=H(y(o.b),y(o.b-1)),x=H(y(s.a+1),y(s.a)),S=[0,1,2].map(e=>Kv(_,_.map(t=>y(t)[e]),b[e],x[e])),C=e=>i[`fyaw_${u}`]?.[e]??0,w=e=>i[`fpitch_${u}`]?.[e]??0,T=(e,t)=>ty(Uv(i,e,p),t,J(X(C(e)),[0,0,1]),c,l)-qv,E=s.a-o.b,D=r&&w(o.b)-T(o.b,y(o.b)),O=r&&w(s.a)-T(s.a,y(s.a));for(let t=o.b+1;t<s.a;t++){let n=S.map(e=>e(t)),i={[`foot_${u}`]:n};if(r){let e=Math.min(wv,T(t,n)+D*(1-ey((t-o.b)/(Jv*E)))+O*(1-ey((s.a-t)/(Yv*E)))),r=h+Xv*ey(Math.min(t-o.b,s.a-t)/3),a=e=>n[1]+J(So(e),m)[1];if(a(e)<r){let t=-30,n=e;for(let e=0;e<20;e++){let e=(t+n)/2;a(e)<r?n=e:t=e}e=t}let c=w(t),l=e=>n[1]+J(So(e),g)[1],d=Math.min(Zv,Math.max(l(c),Qv));if(e<c&&l(e)<d){let t=e,n=c;for(let e=0;e<20;e++){let e=(t+n)/2;l(e)<d?t=e:n=e}e=n}i[`fpitch_${u}`]=e}let c={f:t,set:i,src:a.get(t)};Bv.add(c),e.push(c)}}}}var ry=[6,4],iy=50,ay=1.1,oy=[18,3],sy=[6,3],cy=8,ly=4.5,uy=5.5,dy=.015,fy=[.52,.64],py=.3,my=4,hy=6.4,gy=.8,_y=e=>_o(.66-.18*e,.2,.48),vy=e=>_o(.32-.11*e,0,.45),yy=e=>_o(2.8-.45*e,1.2,3),by=.92,xy=e=>_o(4.7-1.1*e,1.8,4),Sy=[.2,.6],Cy=.9,wy=.18,Ty=.35,Ey=.18,Dy=.55,Oy=10,ky=.22,Ay=.03,jy=50,My=e=>J(X(e),[0,0,1]),Ny=e=>J(X(e),[1,0,0]),Py=e=>{let t=Math.min(1,Math.max(0,e));return t*t*(3-2*t)};function Fy(e,t){let n={};for(let r of[...e].sort((e,t)=>e.f-t.f))r.f<=t&&Object.assign(n,r.set);return n}function Iy(e,t,n,r=`walk`){let i=`${r} start`,a=[],o=(e,t)=>{let n={f:e,set:t,src:i};return a.push(n),n},s=Fy(t,e.f0);if(!s.foot_l||!s.foot_r||!s.root)throw Error(`MOTION_SPEC_INVALID: walk needs foot_l, foot_r and root keyed before f0`);if(e.vary!==void 0&&!(Number.isFinite(e.vary)&&e.vary>=0&&e.vary<=2))throw Error(`MOTION_SPEC_INVALID: ${r} vary must be a number from 0 (every step the same) to 2, got ${JSON.stringify(e.vary)}`);let c=n.index,l=n.restWorldPos,u=l[c.LeftFoot][1],d=l[c.Hips][1],f={l:H(l[c.LeftToeBase],l[c.LeftFoot]),r:H(l[c.RightToeBase],l[c.RightFoot])},p=[0,.005-u,-.045],m={l:-1/0,r:-1/0},h=G(H(l[c.LeftLeg],l[c.LeftUpLeg]))+G(H(l[c.LeftFoot],l[c.LeftLeg])),g=l[c.Hips][1]-l[c.LeftUpLeg][1],_=e.step??.5,v=e.halfWidth??.08,y=e=>Math.sqrt(Math.max(0,(.98*h)**2-e**2))+u+g-d,b={steps:8,step:_,period:20,swing:14,halfWidth:v,lift:.08,turnDistance:.4,firstStep:.4,pelvisHigh:Math.min(-.005,y(Math.hypot(.03,v-.035))),pelvisLow:y(Math.hypot(_/2,v)),vary:1,...e},x=b.step/b.period/(.5/20);b.armSwing=e.armSwing??_o(hy*x,4,22);let S=_y(x),C=vy(x),w=yy(x),T=xy(x),E=_o(Cy*x,0,3),D=oy[0]+oy[1]*Math.min(x,2.5),O=sy[0]+sy[1]*Math.min(x,2.5),[k,ee]=b.heading??[s.yaw??0,s.yaw??0],A=e=>k+(ee-k)*Py(e/b.turnDistance),te=U(V(s.foot_l,s.foot_r),.5);te[1]=0;let ne=[te];for(let e=0;e<4e3;e++)ne.push(V(ne[e],U(My(A(e*.01)),.01)));let re=e=>ne[Math.max(0,Math.min(ne.length-1,Math.round(e/.01)))],ie=(e,t)=>{let n=V(re(e),U(Ny(A(e)),(t===`l`?1:-1)*b.halfWidth));return n[1]=u,n},ae={l:-.07,r:.07},oe={foot_l:s.foot_l,foot_r:s.foot_r,fyaw_l:s.fyaw_l??k,fyaw_r:s.fyaw_r??k},se=[`root`,`yaw`,`roll`,`foot_l`,`foot_r`,`fyaw_l`,`fyaw_r`,`spine_yaw`,`spine_roll`,`spine_pitch`,`aswing_l`,`aswing_r`,`abend_l`,`abend_r`,`wflex_l`,`wflex_r`,`head_yaw`],ce=s.roll??0,le=s.spine_roll??0,ue=s.spine_pitch??0,de={l:[{a:e.f0,b:1/0,strike:!1}],r:[{a:e.f0,b:1/0,strike:!1}]};o(e.f0,Object.fromEntries(se.map(e=>[e,s[e]??oe[e]??(e===`yaw`?k:0)])));let fe=ae.r,pe=null,me=_v(b,{s0:fe,turn:(e,t)=>A(t)-A(e),seed:[e.f0,b.steps,b.step,b.period,b.swing,b.firstStep,k,ee,te[0].toFixed(3),te[2].toFixed(3)].join(`|`)});for(let t=0;t<b.steps;t++){i=`${r} step ${t+1}`;let n=t%2==0?`l`:`r`,a=n===`l`?`r`:`l`,c=t===b.steps-1,l=c?fe:fe+me.inc[t],u=e.f0+16+me.lift[t],h=u+me.air[t],g=u+Math.floor(me.air[t]/2);if(t===0){let e=V(re(ae[a]),U(Ny(k),(a===`l`?1:-1)*b.halfWidth*.75));e[1]=s.root[1],o(u-4,{root:e,yaw:k}),o(u,{arm_hang:1})}let ee=_o(Math.abs(l-ae[n])/ay,.3,1.15),te=iy*(.55+.45*ee)*(c?.8:1),ne=oe[`foot_${n}`],se=oe[`fyaw_${n}`],he=V(ne,J(X(se),f[n])),ge=Math.max(u-Math.max(my,Math.round((t===0?.35:py)*b.period)),m[n]+1,e.f0+1);Object.assign(de[n].at(-1),{b:u,heel:ge,ball:he,yw:se,flat:ne});for(let e=ge;e<=u;e++){let t=te*((e-ge)/Math.max(1,u-ge))**1.8;o(e,{[`foot_${n}`]:Vv(he,se,t,ne),[`fpitch_${n}`]:t,[`fyaw_${n}`]:se})}let _e=Math.max(1,Math.round(ky*me.air[t])),ve=ie((ae[n]+l)/2,n);ve[1]+=me.height[t];let ye=Vv(he,se,Math.min(te,jy),ne),be=V(ye,U(H(ve,ye),Ty));be[1]=ye[1]+Ey*ee*Math.min(1,(me.air[t]/Oy)**2)*(Dy+.44999999999999996*Av(x))*(me.height[t]/b.lift);let xe=U(Ny(A(ae[a])),n===`l`?1:-1),Se=oe[`foot_${a}`],Ce=e=>(e[0]-Se[0])*xe[0]+(e[2]-Se[2])*xe[2],we=Ce(ve)-Ce(be);we>0&&(be[0]+=xe[0]*we,be[2]+=xe[2]*we);let Te=u+Math.max(2,Math.round(wy*me.air[t]));!c&&Te<g-1&&o(Te,{[`foot_${n}`]:be,[`fpitch_${n}`]:.7*Math.min(te,jy)}),o(g,{[`foot_${n}`]:ve,[`fyaw_${n}`]:A((ae[n]+l)/2),[`fpitch_${n}`]:0});let Ee=ae[a]+(fy[0]+(fy[1]-fy[0])*Av(x))*(l-ae[a]),De=pe?pe.s+(Ee-pe.s)*((g-pe.f)/(h-pe.f)):null,Oe=De===null?ae[a]+.03:De-dy*Math.abs(l-ae[n])/2,ke=t===0?.015:.032,Ae=V(re(Oe),U(Ny(A(Oe)),(a===`l`?1:-1)*ke));Ae[1]=d+b.pelvisHigh;let je=e.pelvisLow??(me.inc[t]>_?Math.min(b.pelvisLow,y(Math.hypot(me.inc[t]/2,v))):b.pelvisLow),Me=re(Ee).slice();Me[1]=d+(c?b.pelvisHigh:je),pe={f:h,s:Ee};let Ne=ie(l,n),Pe=A(l),Fe=V(Ne,J(X(Pe),p)),Ie=-(ry[0]+(ry[1]-ry[0])*Av(x))*(c?.5:1),Le=Math.max(2,Math.round(.2*b.period)),Re=V(Vv(Fe,Pe,Ie,Ne),U(My(Pe),-.12*Math.abs(l-ae[n])));Re[1]+=Ay,!c&&_e>1&&h-_e>g+1&&o(h-_e,{[`foot_${n}`]:Re,[`fpitch_${n}`]:.6*Ie});for(let e=0;e<=Le;e++){let t=Ie*(1-Py(e/Le));o(h+e,{[`foot_${n}`]:Vv(Fe,Pe,t,Ne),[`fpitch_${n}`]:t,[`fyaw_${n}`]:Pe})}m[n]=h+Le,de[n].push({a:h,b:1/0,strike:!0}),oe[`foot_${n}`]=Ne,oe[`fyaw_${n}`]=Pe,ae[n]=l;let ze=(c?0:t<3?[0,.3,.7][t]:1)*me.arm[t],Be=n===`l`?1:-1,Ve=_o(ee,.4,1.1),He=c?0:t===0?.5:1,Ue=ly*Ve*He*(a===`l`?1:-1),We=(h-g)/b.period,Ge=e=>{let t=[Math.cos(Math.PI*(e-We)),Math.cos(Math.PI*e)];return t.map(e=>e/Math.max(...t.map(Math.abs)))},Ke=Ge(-C).map(e=>-4.5*Ve*Be*ze*e),qe=Ge(S).map(e=>uy*Ve*Be*ze*e),Je=Ge(by).map(e=>-Math.sign(Ue)*w*Ve*He*e),Ye=Ge(We).map((e,t)=>t?gy*e:e),Xe=e=>({aswing_l:-.85*b.armSwing*Be*ze*e,aswing_r:b.armSwing*Be*ze*e,abend_l:ze*(D-Be*O*e),abend_r:ze*(D+Be*O*e)});o(g,{root:Ae,yaw:A(Oe)+Ke[0],roll:ce+Ue,spine_roll:le-Ue*1.26+Je[0],spine_yaw:qe[0]-Ke[0],...Xe(Ye[0]),wflex_l:cy*ze,wflex_r:cy*ze}),o(h,{root:Me,yaw:A(Ee)+Ke[1],roll:ce,spine_roll:le+Je[1],spine_yaw:qe[1]-Ke[1],...Xe(Ye[1]),head_yaw:0});let Ze=ue+E*He,Qe=T*Ve*He;o(Math.max(e.f0+1,h-Math.round(Sy[1]*b.period)),{spine_pitch:Ze-.6*Qe}),o(Math.max(e.f0+1,h-Math.round(Sy[0]*b.period)),{spine_pitch:Ze+Qe}),fe=l}let he=e.f0+16+b.steps*b.period+18,ge=Math.max(...a.map(e=>e.f));return e.pelvisHigh===void 0&&e.pelvisLow===void 0&&(ny(a,{end:ge,ground:de}),Wv(n,a,{f0:e.f0,end:ge,period:b.period,pace:x,ground:de,start:`${r} start`}),Gv(n,a,{end:ge,period:b.period,pace:x,ground:de}),ny(a,{end:ge,ground:de,sk:n})),i=`${r} end`,o(he,Fy(a,he)),a}function Ly(e,t){let n=(e.keys??[]).map((e,t)=>e.src?e:{...e,src:`keys[${t}]`});return(e.generators??[]).forEach((e,r)=>{if(e.type!==`walk`)throw Error(`MOTION_SPEC_INVALID: generators[${r}] has unknown type "${e.type}" (only "walk")`);n=n.concat(Iy(e,n,t,`generators[${r}] walk`))}),n}var Ry={yaw:.5,pitch:.2,roll:.7},zy={yaw:4,pitch:6,roll:10},By=33,Vy=8,Hy=[`yaw`,`pitch`,`roll`];function Uy(e){let t=new Map;for(let n of e){let e=/ (start|step \d+)$/.exec(n.src??``),r=e&&n.src.slice(0,-e[0].length);if(!e||!/\bwalk(To)?$/.test(r))continue;let i=t.get(r)??[1/0,-1/0];t.set(r,[Math.min(i[0],n.f),Math.max(i[1],n.f)])}return[...t.values()].filter(([e,t])=>t>e)}var Wy=(e,t)=>{let n=Math.floor(t/2),r=t=>e[Math.max(0,Math.min(e.length-1,t))];return e.map((e,t)=>{let i=0;for(let e=t-n;e<=t+n;e++)i+=r(e);return i/(2*n+1)})};function Gy(e,t,n){let r=Uy(t);if(!r.length)return;let i=t=>e[t]??Array(n).fill(0);for(let a of Hy){let o=i(`spine_${a}`),s=i(a).map((e,t)=>e+o[t]),c=Wy(s,By),l=null;for(let[e,o]of r)if(!t.some(t=>t.f>=e&&t.f<=o&&t.set?.[`head_${a}`]!==void 0&&!/\bwalk(To)? (start|step \d+|end)$/.test(t.src??``))){l??=i(`head_${a}`).slice();for(let t=Math.max(0,e);t<=Math.min(n-1,o);t++){let n=Math.min(1,(t-e)/Vy,(o-t)/Vy),r=Math.max(-zy[a],Math.min(zy[a],s[t]-c[t]));l[t]-=Ry[a]*r*n*n*(3-2*n)}}l&&(e[`head_${a}`]=l)}}var Ky=30,qy=.3,Jy=8,Yy=33;function Xy(e,t){let n=e.slice(),r=Math.floor(Yy/2),i=e.length;for(let[a,o]of t)for(let t=Math.max(0,a);t<=Math.min(i-1,o);t++){let a=e.slice(Math.max(0,t-r),Math.min(i,t+r+1)).sort((e,t)=>e-t);n[t]=a.length%2?a[(a.length-1)/2]:(a[a.length/2-1]+a[a.length/2])/2}return n}function Zy(e,t,n,r){let i=[];for(let a=0;a<t-1;a++){if(Math.abs(e[a+1]-e[a])<=qy)continue;let o=Math.max(0,a-n),s=Math.min(t-1,a+1+r),c=i.at(-1);c&&o<=c[1]+1?c[1]=Math.max(c[1],s):i.push([o,s])}return i}function Qy(e){let t=[];for(let[n,r]of[...e].sort((e,t)=>e[0]-t[0])){let e=t.at(-1);e&&n<=e[1]+1?e[1]=Math.max(e[1],r):t.push([n,r])}return t}function $y(e,t,n){let r=e.filter(e=>e.set?.head_yaw!==void 0&&!/\bwalk(To)? (start|step \d+|end)$/.test(e.src??``)).sort((e,t)=>e.f-t.f),i=[r.filter(e=>e.f<t).at(-1),...r.filter(e=>e.f>=t&&e.f<=n),r.find(e=>e.f>n)].filter(Boolean);return i.some(e=>JSON.stringify(e.set.head_yaw)!==JSON.stringify(i[0].set.head_yaw))}function eb(e,t,n,r=5){if(!(r>0))return;let i=Array(n).fill(0),a=e.yaw??i,o=e.spine_yaw??i,s=Uy(t).map(([e,t])=>[Math.ceil(e),Math.floor(t)]),c=Xy(a.map((e,t)=>e+o[t]),s),l=e=>c[Math.min(n-1,e)],u=Qy([...s,...Zy(c,n,r+Jy,Jy)]),d=null;for(let[a,o]of u)if(!$y(t,a,o)){d??=(e.head_yaw??i).slice();for(let e=Math.max(0,a);e<=Math.min(n-1,o);e++){let t=Math.min(1,(e-a)/Jy,(o-e)/Jy),n=Math.max(-30,Math.min(Ky,l(e+r)-c[e]));d[e]+=n*t*t*(3-2*t)}}d&&(e.head_yaw=d)}function tb(e,t){let n=e.length,r=new Float64Array(n);for(let i=0;i<n;i++)if(e[i]>0)for(let a=Math.max(0,i-t-1);a<=Math.min(n-1,i+t+1);a++){let n=1-Math.abs(i-a)/(t+1),o=n*n*(3-2*n);r[a]=Math.max(r[a],e[i]*o)}return r}var nb=e=>Math.round(e*1e4)/1e4,rb=6;function ib(e,t){let{sk:n}=e.ctx,r=n.index,i=n.restWorldPos,a=e.baked.root;if(!a)return null;let o=e.frames.length,s=new Float64Array(o);for(let t=0;t<o;t++){let{s:n,diag:a,c:o}=e.frames[t];for(let[e,c]of Object.entries(n_)){if(!(a[`leg_miss_${e}`]>5e-4)||!Array.isArray(o[`foot_${e}`]))continue;let l=.999*(G(H(i[r[`${c}Leg`]],i[r[`${c}UpLeg`]]))+G(H(i[r[`${c}Foot`]],i[r[`${c}Leg`]]))),u=H(o[`foot_${e}`],n.P[r[`${c}UpLeg`]]),d=u[1]*u[1]-W(u,u)+l*l,f=d>=0?-u[1]-Math.sqrt(d):-u[1];f>0&&f<=.05&&(s[t]=Math.max(s[t],f+5e-4))}}let c=s.filter(e=>e>0).length;if(!c)return null;let l=tb(s,rb),u=[];for(let t=0;t<o;t++){if(!(l[t]>0))continue;let n=e.f0+t,r=a[n];a[n]=[r[0],r[1]-l[t],r[2]],u.push(n)}return t.solve(u),{frames:c,eased:u.length,max:nb(Math.max(...s)),how:`hips lowered`}}function ab(e){let t=0,n=0;for(let r of e.frames)for(let e of[`l`,`r`]){let i=r.diag[`reach_over_${e}`]??0;i>.001&&(t++,n=Math.max(n,i))}return t?{frames:t,max:nb(n),how:`wrist target clamped to reach`}:null}var ob=.01,sb=.97,cb=25,lb=.08,ub=.15,db=10,fb=.002,pb=[.25,.5,.75,1],mb=e=>e*e*(3-2*e);function hb(e,t,n,r){if(!(t[`armw_${n}`]>=.5))return null;let i=null;for(let[e,r]of Object.entries(t)){let t=/^w_(.+)_([lr])$/.exec(e);t&&t[2]===n&&r>=.5&&(!i||r>i.w)&&(i={w:r,name:t[1]})}let a=i&&e.spec.anchors?.[i.name];return a&&(a.kind===`world`||a.kind===`object`&&!e.objectHand?.(a.object,r))?i.name:null}function gb(e,t,n,r){let{s:i}=e.frames[t-e.f0],a=e.ctx.sk.index,o=e.ctx.scene?.objects??{},s=Object.entries(e.objectsAt(t-e.f0)??{}).filter(([,e])=>e.half&&!e.ignore),c=e=>r!==void 0&&(e===r||o[e]?.ancestors?.includes(r)),l=0;for(let[e,t,r,o]of Sc){if(a[t]===void 0||a[r]===void 0)continue;let u=Cc(i.P[a[t]],i.P[a[r]],5);for(let[t,r]of s)e===`hand_${n}`&&c(t)||(l+=Math.max(0,o-Math.min(...u.map(e=>wc(e,r)))))}return l}function _b(e,t,n){let r=0;return Iu(e,{frames:t},n,(e,t,n,i,a)=>{r+=i-a}),r}function vb(e,t,n,r){if(r?.prop)return n.props?.[r.prop]?.[r.point]??null;let i=(r?.joints??[`RightHandIndex2`,`RightHandMiddle2`]).map(n=>t.P[e.index[n]]).filter(Boolean);return i.length?i.reduce((e,t)=>e.map((e,n)=>e+t[n]/i.length),[0,0,0]):null}function yb(e,t,n){let r=[];e.frames.forEach((i,a)=>{let o=e.f0+a;if(!(i.diag[`arm_miss_${t}`]>n)||i.diag[`arm_fold_${t}`]||!hb(e.ctx,i.c,t,o))return;let s=r.at(-1);s&&o-s[1]<=3?s[1]=o:r.push([o,o])});let i=r=>r>=e.f0&&r<e.f0+e.frames.length&&e.frames[r-e.f0].diag[`arm_miss_${t}`]>n&&!e.frames[r-e.f0].diag[`arm_fold_${t}`];for(let e of r)for(let t=0;t<db&&i(e[1]+1);t++)e[1]+=1;return r}function bb(e,t){let{ctx:n}=e,{sk:r}=n,i=r.index,a=e.frameCount,o=e.baked,s=n.spec.checks?.limits?.reach??.01,c=t=>e.frames[t-e.f0],l=e.f0,u=e.f0+e.frames.length-1,d=[],f={pitch:new Float64Array(a),move:new Float64Array(a)},p=[];for(let m of[`r`,`l`])for(let[h,g]of yb(e,m,s)){let s=e=>c(e).s.P[i[`${n_[m]}Arm`]],_=e=>{let{s:t,diag:r,c:i}=c(e),a=hb(n,i,m,e);return a?Fd(n,a,t,{...r,frame:e},i):null},v=e=>c(e).c[`armw_${m}`]>=.99&&c(e).c[`w_${hb(n,c(e).c,m,e)}_${m}`]>=.99,y=Array.from({length:g-h+1},(e,t)=>h+t),b=y.some(v)?y.filter(v):y,x=-1,S=null;for(let e of b){let t=_(e);t&&(!S||G(H(t,s(e)))>G(H(S,s(x))))&&(x=e,S=t)}if(!S)continue;let{s:C,diag:w,c:T}=c(x),E=m===`l`?`r`:`l`,D=(n.spec.fits??[]).find(e=>e.side===m&&e.anchor===hb(n,T,m,x)),O=D&&vb(r,C,w,D.effector),k=Math.max(O?G(H(O,S)):0,w[`arm_miss_${m}`]??0),ee=Nd(r,m)+(O?G(H(O,C.P[i[`${n_[m]}Hand`]])):0),A=s(x),te=(T.yaw??0)*Math.PI/180,ne=[Math.sin(te),0,Math.cos(te)],re=[S[0]-A[0],0,S[2]-A[2]],ie=G(re)>.001?K(re):ne,ae=W(ie,ne)>.3&&S[1]<A[1]+.1?cb:0,oe=ub*Math.min(1,Math.max(0,(A[1]-S[1]-.2)/.4)),se=Math.max(0,1-Math.max(f.pitch[x]/cb,f.move[x]/lb));if(!se)continue;o.root||(o.root=Array.from({length:a},()=>r.restWorldPos[i.Hips].slice()),p.push(`root`)),o.spine_pitch||(o.spine_pitch=Array(a).fill(0),p.push(`spine_pitch`));let ce=o.root.map(e=>e.slice()),le=o.spine_pitch.slice(),ue=(e,t)=>{o.root[e]=[ce[e][0]+ie[0]*lb*t,ce[e][1]-oe*t,ce[e][2]+ie[2]*lb*t],o.spine_pitch[e]=le[e]+ae*t},de=(e,t)=>[`l`,`r`].every(n=>!((e[`leg_miss_${n}`]??0)>Math.max(t[`leg_miss_${n}`]??0,5e-4)+fb)),fe=(e,t)=>!(c(x).c[`armw_${E}`]>.5)||(e[`arm_miss_${E}`]??0)<=(t[`arm_miss_${E}`]??0)+fb,pe=n.spec.anchors[hb(n,T,m,x)]?.object,me=c(x),he=gb(e,x,m,pe),ge=n=>{ue(x,n),t.solve([x]);let{s:i,diag:a}=c(x),l=D&&vb(r,i,a,D.effector),u={t:n,miss:Math.max(l?G(H(l,S)):0,a[`arm_miss_${m}`]??0),ok:de(a,w)&&fe(a,w)&&gb(e,x,m,pe)<=he+fb,bent:G(H(S,s(x)))<=sb*ee};return o.root[x]=ce[x],o.spine_pitch[x]=le[x],e.frames[x-e.f0]=me,u},_e=null,ve=0;for(let e of pb.map(e=>e*se)){let t=ge(e);if(!t.ok)break;if((!_e||t.miss<_e.miss)&&(_e=t),t.miss<=ob&&t.bent){let t=ve,n=e;for(let e=0;e<4;e++){let e=ge((t+n)/2);e.ok&&e.miss<=ob&&e.bent?(n=e.t,_e=e):t=e.t}break}ve=e}if(!_e||!(_e.miss<k-ob))continue;let ye=(e,t)=>Math.min(1,Math.max(0,o[e]?.[t]??1)),be=hb(n,T,m,x),xe=[],Se=e=>ye(`armw_${m}`,e)*ye(`w_${be}_${m}`,e)*(e>=h&&e<=g?1:mb(1-(e<h?h-e:e-g)/11));for(let e=Math.max(l,h-db);e<=Math.min(u,g+db);e++)ue(e,_e.t*Se(e)),xe.push(e);let Ce=xe.map(e=>c(e)),we=xe.map(t=>gb(e,t,m,pe));t.solve(xe);let Te=e=>Ce[e-xe[0]],Ee=(e,t)=>{let n=_(t),i=D&&n&&vb(r,e.s,e.diag,D.effector);return Math.max(i?G(H(i,n)):0,e.diag[`arm_miss_${m}`]??0)},De=e=>y.reduce((t,n)=>t+(e(n).diag[`arm_miss_${m}`]??0),0),Oe=e=>Math.max(...b.map(t=>Ee(e(t),t))),ke=xe.map(t=>gb(e,t,m,pe)),Ae={...rd,...n.spec.checks?.limits},je=Array.from({length:Math.min(u,xe.at(-1)+3)-Math.max(l,xe[0]-3)+1},(e,t)=>Math.max(l,xe[0]-3)+t),Me=_b(r,je.map(e=>c(e)),Ae)>_b(r,je.map(e=>e>=xe[0]&&e<=xe.at(-1)?Ce[e-xe[0]]:c(e)),Ae)+1e-4,Ne=xe.every((e,t)=>de(c(e).diag,Ce[t].diag)&&fe(c(e).diag,Ce[t].diag)&&ke[t]<=we[t]+fb),Pe=Oe(Te),Fe=Oe(c);if(!Ne||Me||!(De(c)<De(Te)-1e-6)||!(Fe<Pe-ob/2)){for(let e of xe)o.root[e]=ce[e],o.spine_pitch[e]=le[e];xe.forEach((t,n)=>{e.frames[t-e.f0]=Ce[n]});continue}for(let e of xe)f.pitch[e]+=ae*_e.t*Se(e),f.move[e]+=lb*_e.t*Se(e);d.push({side:m,frames:[h,g],lean:nb(ae*_e.t),shift:[nb(ie[0]*lb*_e.t),nb(ie[2]*lb*_e.t)],drop:nb(oe*_e.t),miss:[nb(Pe),nb(Fe)]})}if(!d.length)for(let e of p)delete o[e];return d.length?{runs:d,how:`an out-of-reach hand on a pinned target: the body leaned (spine_pitch deg), shifted its hips (x, z m) and lowered them (m) toward it, eased in and out; the feet kept their targets`}:null}var xb=.01,Sb=4,Cb=.03,wb=.02;function Tb(e,t){let n=e.frames.length,r=rd.plantH,i=0,a=0,o=0,s=new Set;for(let[t,c]of[[`l`,`Left`],[`r`,`Right`]]){let l=e.baked[`foot_${t}`];if(!l)continue;let u=e.frames.map((t,n)=>mu(e,n,c)),d=(e,t)=>u[e][t][1]<r&&u[e-1][t][1]<r&&Math.abs(u[e][t][1]-u[e-1][t][1])<5e-4,f=Array.from({length:n},()=>null);for(let e=1;e<n;){if(!d(e,`ball`)&&!d(e,`heel`)){e++;continue}let t=null,s=null,c=e,l=0,p=[0,0,0],m=!1,h=[],g=e=>{let n=H(s,u[e][t]);n[1]=0,p=n,h.push([e,n]),l=Math.max(l,Math.hypot(n[0],n[2]))};for(;c<n&&(d(c,`ball`)||d(c,`heel`));c++){let e=d(c,`ball`)?`ball`:`heel`;m||=u[c][e===`ball`?`heel`:`ball`][1]>=r,e!==t&&(t=e,s=V(u[c-1][t],p)),g(c)}if(m&&l>=xb)for(;c<n&&u[c][t][1]<Cb;c++)g(c);if(l>2e-4&&(l<xb||m)){i++,o=Math.max(o,l),l>=xb&&a++;for(let[e,t]of h)f[e]=t;let e=Math.max(Sb,Math.ceil(Math.hypot(p[0],p[2])/wb));for(let t=1;t<=e&&c-1+t<n&&!f[c-1+t];t++){let n=t/(e+1),r=1-n*n*(3-2*n);f[c-1+t]=[p[0]*r,0,p[2]*r]}}e=c}for(let t=0;t<n;t++){if(!f[t])continue;let n=e.f0+t;l[n]=V(l[n],f[t]),s.add(n)}}return i?(t.solve([...s]),{plants:i,...a?{pivots:a}:{},frames:s.size,max:nb(o),how:a?`planted heel/ball held in place; turning feet pivot on it`:`planted heel/ball held in place`}):null}var Eb=6,Db=4,Ob=1,kb=e=>e*e*(3-2*e);function Ab(e,t){let n=e.frames.length,r=rd.plantH,i=new Set,a=0;for(let[t,o]of[[`l`,`Left`],[`r`,`Right`]]){let s=e.baked[`fyaw_${t}`]??e.baked.yaw;if(!e.baked[`foot_${t}`]||!s)continue;let c=e.frames.map((t,n)=>mu(e,n,o)),l=(e,t)=>c[e][t][1]<r&&c[e-1][t][1]<r&&Math.abs(c[e][t][1]-c[e-1][t][1])<5e-4,u=e=>e>0&&e<n&&l(e,`heel`)&&l(e,`ball`),d=Array.from({length:n},(t,n)=>s[e.f0+n]),f=d.slice();for(let e=1;e<n;e++){if(!u(e))continue;let t=f[e-1],r=e,i=0;for(;u(r);r++)i=Math.max(i,Math.abs(f[r]-t));if(i<=Ob){e=r;continue}a=Math.max(a,i);for(let n=e;n<r;n++)f[n]=t;let o=r<n?d[r]-t:0,s=Math.max(Db,Math.ceil(Math.abs(o)/Eb));for(let e=0;o&&e<s&&r+e<n&&!u(r+e);e++)f[r+e]=d[r+e]-o*(1-kb((e+1)/(s+1)));e=r}let p=f.map((e,t)=>e!==d[t]);if(!p.some(Boolean))continue;let m=e.baked[`fyaw_${t}`]=s.slice();p.forEach((t,n)=>{t&&(m[e.f0+n]=f[n],i.add(e.f0+n))})}return i.size?(t.solve([...i]),{frames:i.size,max:nb(a)}):null}var jb=.001,Mb=.15,Nb=2;function Pb(e,t){let{sk:n}=e.ctx,r=e.frames.length,i=new Set,a=0;for(let[t,o]of Object.entries(n_)){let s=e.baked[`foot_${t}`],c=n.index[`${o}Foot`];if(!s)continue;let l=e.frames.map(({s:t},r)=>{let i=kc(n,t,o),a=Math.min(i.heel[1],i.ball[1],i.tip[1])-t.P[c][1]+s[e.f0+r][1];return Math.min(Mb,-a-jb)});if(!l.some(e=>e>0))continue;let u=tb(l,Nb);for(let t=0;t<r;t++){if(!(u[t]>0))continue;let n=e.f0+t;s[n]=[s[n][0],s[n][1]+u[t],s[n][2]],a=Math.max(a,l[t]),i.add(n)}}return i.size?(t.solve([...i]),{frames:i.size,max:nb(a),how:`soles lifted onto the floor`}):null}var Fb=4,Ib=.002,Lb=3,Rb={l:Sc.filter(e=>e[0]===`hand_l`||e[0]===`farm_l`),r:Sc.filter(e=>e[0]===`hand_r`||e[0]===`farm_r`)};function zb(e,t,n,r,i){let{sk:a}=e.ctx,o=a.index,s=e.frames.length,c=Array.from({length:s},()=>null);for(let a=0;a<s;a++){let{s,c:l}=e.frames[a],u=e.objectsAt(a),d=null;for(let[e,a]of Object.entries(u)){if(!a.half||a.ignore)continue;let c=null;for(let[l,u,d,f]of Rb[t]){let t=od(r,l,e)??rd.allow,p=Cc(s.P[o[u]],s.P[o[d]]),m=p.map(e=>wc(e,a)),h=Math.min(...m),g=f-h-t;if(!(g<=0)){if(g>n){i.deep++;continue}(!c||g>c[0])&&(c=[g,p[m.indexOf(h)]])}}c&&(d=V(d??[0,0,0],U(Ac(c[1],a),c[0]+Ib)))}if(d){if(!(l[`armw_${t}`]>1e-4)){i.skipped++;continue}c[a]=d}}return c}function Bb(e,t,n){let r=e.ctx.spec.checks?.allow,i=e.frames.length,a={deep:0,skipped:0},o=new Set,s=0;for(let c=0;c<Lb;c++){a.deep=0,a.skipped=0;let c=new Set;for(let t of[`l`,`r`]){let l=zb(e,t,n,r,a),u=e.ctx.push[t],d=Array.from({length:i},()=>null);for(let e=0;e<i;e++)if(l[e]){o.add(`${t}${e}`);for(let t=Math.max(0,e-Fb-1);t<=Math.min(i-1,e+Fb+1);t++){let n=1-Math.abs(e-t)/5,r=U(l[e],n*n*(3-2*n));(!d[t]||G(r)>G(d[t]))&&(d[t]=r)}}for(let t=0;t<i;t++){if(!d[t])continue;let n=e.f0+t,r=V(u.get(n)??[0,0,0],d[t]);u.set(n,r),s=Math.max(s,G(r)),c.add(n)}}if(!c.size)break;t.solve([...c])}return!o.size&&!a.skipped?null:{frames:o.size,max:nb(s),skipped:a.skipped,tooDeep:a.deep,how:`hand pushed out along the box normal`}}var Vb=1.1,Hb=.35,Ub=3,Wb=e=>{let t=e.ctx.spec?.checks?.limits;return Ju(e.ctx.sk,e,t,{...rd,...t})};function Gb(e,t,n){let r=[];for(let i=1;i<n;i++){if(e[i]<=1)continue;let a=i;for(;a+1<n&&e[a+1]>1;)a++;let o=Math.max(6,2*(a-i+1)),s=Math.max(0,...t.filter(e=>e<=i-1-o)),c=Math.min(n-1,...t.filter(e=>e>=a+o));r.length&&s<=r[r.length-1][1]?r[r.length-1][1]=Math.max(r[r.length-1][1],c):r.push([s,c]),i=a}return r}function Kb(e,t){let n=t[t.length-1]-t[0],r=t.slice(1).map((n,r)=>{let i=0;for(let a=Math.floor(t[r])+1;a<=Math.ceil(n);a++)i=Math.max(i,e[a]??0);return{len:n-t[r],need:Vb*i}}),i=e=>r.reduce((t,n)=>t+n.len*Math.max(n.need,e),0),a=Hb,o=1;for(let e=0;e<40;e++){let e=(a+o)/2;i(e)>n?o=e:a=e}let s=r.map(e=>e.len*Math.max(e.need,a)),c=n/s.reduce((e,t)=>e+t,0),l=[t[0]];return s.forEach((e,t)=>l.push(l[t]+e*c)),l[l.length-1]=t[t.length-1],{T:l,stretch:Math.max(...s.map((e,t)=>e*c/r[t].len))}}function qb(e,t){let n=e.frames.length,r=[],i=0,a=1;for(let o=0;o<Ub;o++){let o=Wb(e),s=[...new Set(e.keys.map(e=>e.f))].sort((e,t)=>e-t),c=Gb(o,s,n);if(!c.length)break;let l=c.map(([e,t])=>{let n=[...new Set([e,...s.filter(n=>n>e&&n<t),t])].sort((e,t)=>e-t),r=Kb(o,n);return a=Math.max(a,r.stretch),{cuts:n,T:r.T}});i+=c.length;let u=e=>{for(let{cuts:t,T:n}of l){if(e<t[0]||e>t[t.length-1])continue;let r=0;for(;r<t.length-2&&e>t[r+1];)r++;return n[r]+(n[r+1]-n[r])*(e-t[r])/(t[r+1]-t[r])}return e};r.push(u),t.rebake(e.keys.map(e=>({...e,f:u(e.f)}))),t.solve(t.all())}if(!r.length)return null;e.timeMap=e=>r.reduce((e,t)=>t(e),e);let o=Wb(e).filter(e=>e>1).length;return{windows:i,maxStretch:Math.round(a*100)/100,stillFast:o,how:`key intervals around speed spikes stretched`}}var Jb=Array.from({length:19},(e,t)=>-90+t*10),Yb=3,Xb=5,Zb=.003,Qb=.003,$b=.03,ex=.08,tx=.03,nx=40,rx=.05,ix=4,ax=2,ox=.09,sx=400;function cx(e,t,n){let r=null;for(let i of e.ctx.spec.checks?.below??[]){let a=String(i.joint).replace(/^joint:/,``),o=String(i.ref).replace(/^joint:/,``),s=e.f0+t;(Array.isArray(i.when)?s>=i.when[0]&&s<=i.when[1]:!i.when||(e.frames[t].c[i.when]??0)>.5)&&a===`${n}ForeArm`&&o===`${n}Arm`&&Number.isFinite(i.min)&&(r=Math.max(r??0,i.min))}return r}var lx=10,ux={l:`Left`,r:`Right`};function dx(e,t,n){let r=0;for(let i of e.fits??[]){let a=e.anchors?.[i.anchor],o=t[`w_${i.anchor}_${i.side}`]??0;(i.side===n||a?.kind===`prop`&&e.props?.[a.prop]?.hand===n)&&(r=Math.max(r,o))}return Math.min(1,r)}var fx=Object.fromEntries(Sc.map(e=>[e[0],e[3]]));function px(e,t,n,r){let i=0;for(let a of e)i=Math.max(i,r-Math.min(...Cc(t,n,5).map(e=>wc(e,a))));return i}function mx(e,t,n,r,i,a=[]){let o=t.index,s=o[`${r}Arm`],c=o[`${r}ForeArm`],l=n.P[s],u=n.P[o[`${r}Hand`]],d=i?V(l,J(wo(H(u,l),i),H(n.P[c],l))):n.P[c],f=Math.max(Vs(e,t,n,s,l,d),Vs(e,t,n,c,d,u)),p=r===`Left`?`l`:`r`;return{depth:f,scene:a.length?Math.max(px(a,l,d,fx[`uarm_${p}`]),px(a,d,u,fx[`farm_${p}`])):0,rise:Math.max(0,d[1]-(l[1]-ox)),under:l[1]-d[1]}}var hx=(e,t)=>{let n=e.index,r=e.restWorldPos;return G(H(r[n[`${t}ForeArm`]],r[n[`${t}Arm`]]))+G(H(r[n[`${t}Hand`]],r[n[`${t}ForeArm`]]))};function gx(e,t,n){let{sk:r}=e.ctx,i=ux[n],a=e.frames.length,o=e.ctx.swivel[n],s=e.frames.map(({s:a,c:s},c)=>{let l=r_(s[`armw_${n}`]??0),u=(o.get(e.f0+c)??0)*l;if(!u&&mx(t,r,a,i,0).depth<=Qb)return null;let d=a.P[r.index[`${i}Arm`]],f=hx(r,i)+.15,p=Object.values(e.objectsAt(c)).filter(e=>e.half&&!e.ignore&&G(H(V(e.pos,J(e.R,[0,e.half[1],0])),d))-G(e.half)<f),m=mx(t,r,a,i,-u,p).scene,h=cx(e,c,i);return Jb.map(e=>{let{depth:n,scene:o,rise:s,under:c}=mx(t,r,a,i,e*l-u,p),d=Math.max(0,n-Qb)*100,f=h===null?0:Math.max(0,h-c),g=Math.max(0,o-Math.max(m,Qb))*100;return nx*(d*d+g*g)+rx*(e/10)**2+ix*(s*100)**2+sx*(f*100)**2})});if(s.every(e=>!e))return null;let c=Jb.indexOf(0),l=Jb.map((e,t)=>t===c?0:1/0),u=Jb.map(()=>0),d=[];for(let e=0;e<a;e++){let t=s[e]??l,n=u,r=[];u=t.map((e,t)=>{let i=1/0,a=c;for(let e=0;e<Jb.length;e++){if(Math.abs(Jb[t]-Jb[e])>lx)continue;let r=n[e]+ax*((Jb[t]-Jb[e])/10)**2;r<i&&(i=r,a=e)}return r.push(a),i+e}),d.push(r)}let f=Array(a),p=u.indexOf(Math.min(...u));for(let e=a-1;e>=0;e--)f[e]=Jb[p],p=d[e][p];return f.map((e,t)=>(f[Math.max(0,t-1)]+2*f[t]+f[Math.min(a-1,t+1)])/4)}function _x(e,t,n,r){let{sk:i}=e.ctx,a=ux[n],o=i.index,s=e.frames.length,c=Array(s).fill(null),l=[o.Head,o.Neck,o.HeadTop_End].filter(e=>e!==void 0);for(let u=0;u<s;u++){let{s,c:d}=e.frames[u],f=e.f0+u,p=1-dx(e.ctx.spec,d,n);if(p<.05)continue;let m=null;for(let n of[o[`${a}Hand`],o[`${a}ForeArm`]]){let r=Hs(t,i,s,n);if(r.into<0||l.includes(r.into))continue;let a=Math.min(tx,od(e.ctx.spec.checks?.allow,ou(i,n),ou(i,r.into))??0),o=r.depth-Math.max(a,Qb);o>0&&(!m||o>m.past)&&(m={...r,b:n,past:o})}if(!m)continue;if(!(d[`armw_${n}`]>1e-4)){r.skipped++;continue}let h=G(e.ctx.skinPush[n].get(f)??[0,0,0]);if(h>=ex){r.deep++;continue}let g=js(t,s,m.p,new Set([...t.skip.get(m.b),...l]));g&&(c[u]=U(g,p*Math.min($b,ex-h,m.past+Zb)))}let u=Array(s).fill(null);return c.forEach((e,t)=>{if(e)for(let n=Math.max(0,t-Xb-1);n<=Math.min(s-1,t+Xb+1);n++){let r=1-Math.abs(t-n)/6,i=U(e,r*r*(3-2*r));(!u[n]||G(i)>G(u[n]))&&(u[n]=i)}}),u}function vx(e,t){let n=Es(e.ctx.sk);if(!n)return null;let r=e.frames.length,i={skipped:0,deep:0},a=new Set,o=new Set,s=0,c=0;for(let r=0;r<Yb;r++){let r=new Set;for(let t of[`r`,`l`]){let i=gx(e,n,t);i&&i.forEach((n,i)=>{let o=e.f0+i,c=e.ctx.swivel[t].get(o)??0,l=Math.abs(n)<.5?0:n;Math.abs(l-c)<.5||(l?e.ctx.swivel[t].set(o,l):e.ctx.swivel[t].delete(o),s=Math.max(s,Math.abs(l)),l&&a.add(`${t}${i}`),r.add(o))})}r.size&&t.solve([...r]),r=new Set,i.skipped=0,i.deep=0;for(let t of[`r`,`l`])_x(e,n,t,i).forEach((n,i)=>{if(!n)return;let a=e.f0+i,s=V(e.ctx.skinPush[t].get(a)??[0,0,0],n);e.ctx.skinPush[t].set(a,s),c=Math.max(c,G(s)),o.add(`${t}${i}`),r.add(a)});if(!r.size)break;t.solve([...r])}if(o.size){let n=new Set;for(let t of[`r`,`l`]){let i=n=>e.ctx.skinPush[t].get(e.f0+n)??[0,0,0];for(let a=0;a<2;a++){let a=Array.from({length:r},(e,t)=>i(t));a.forEach((i,o)=>{let s=[-2,-1,0,1,2].reduce((e,t,n)=>V(e,U(a[Math.min(r-1,Math.max(0,o+t))],[1,4,6,4,1][n]/16)),[0,0,0]);G(s)<1e-5&&!e.ctx.skinPush[t].has(e.f0+o)||(e.ctx.skinPush[t].set(e.f0+o,s),n.add(e.f0+o))})}}n.size&&t.solve([...n])}return!a.size&&!o.size&&!i.skipped?null:{elbowFrames:a.size,maxTurn:Math.round(s),handFrames:o.size,maxPush:nb(c),skipped:i.skipped,tooDeep:i.deep,how:`elbow turned about the shoulder-wrist line; a hand a little inside pushed out along the skin`}}var yx=4,bx=.004,xx=6,Sx=2.2,Cx={l:Sc.filter(e=>/^(uarm|farm|hand)_l$/.test(e[0])),r:Sc.filter(e=>/^(uarm|farm|hand)_r$/.test(e[0]))};function wx(e,t,n,r){let i=H(r,n),a=W(i,i),o=null;for(let r of Cc(e,t)){let e=V(n,U(i,a<1e-12?0:_o(W(H(r,n),i)/a,0,1))),t=G(H(r,e));(!o||t<o.d)&&(o={a:r,b:e,d:t})}return o}function Tx(e,t){let n=[t[0]-e[0],0,t[2]-e[2]],r=G(n);return r>1e-6?U(n,1/r):null}function Ex(e){return Object.entries(e.ctx?.scene?.people??{}).sort(([e],[t])=>e<t?-1:+(e>t)).filter(([,e])=>Sc.every(([,t,n])=>e.names.includes(t)&&e.names.includes(n)))}function Dx(e,t,n,r,i,a){let{sk:o}=e.ctx,s=o.index,c=e.frames.length,l=e.f0??0,u=Array.from({length:c},()=>null),d=new Map;for(let o=0;o<c;o++){let{s:c,c:f}=e.frames[o],p=null;for(let[e,a]of n){let n=ld(a,o+l),u=n.find(e=>e[0]===`hips`)[1];if(G(H(c.P[s.Hips],u))>Sx)continue;let f=null;for(let[a,o,l,u]of Cx[t]){let t=od(i,a,`person:${e}`),d=t??r,p=c.P[s[o]],m=c.P[s[l]];for(let[,e,r,i]of n){let n=wx(p,m,e,r),a=u+i-n.d;a>d&&(!f||a-(t??0)>f.need)&&(f={need:a-(t??0),hit:n})}}if(!f)continue;let m=Tx(u,c.P[s.Hips])??[0,0,0],h=d.get(e)??m,g=f.hit.d>1e-6?U(H(f.hit.a,f.hit.b),1/f.hit.d):h;(W(g,h)<0||W(g,m)<0)&&(g=h),d.set(e,g),p=V(p??[0,0,0],U(g,f.need+bx))}if(p){if(!(f[`armw_${t}`]>1e-4)){a.skipped++;continue}u[o]=p}}return u}function Ox(e,t){let n=Ex(e);if(!n.length)return null;let{checks:r={}}=e.ctx.spec,i={...rd,...r.limits}.allow,a=e.frames.length,o={skipped:0},s=new Set,c=0,l=0;for(let u=0;u<xx;u++){o.skipped=0;let u=new Set;for(let t of[`l`,`r`]){let l=Dx(e,t,n,i,r.allow,o),d=e.ctx.push[t],f=Array.from({length:a},()=>null);for(let e=0;e<a;e++)if(l[e]){s.add(`${t}${e}`);for(let t=Math.max(0,e-yx-1);t<=Math.min(a-1,e+yx+1);t++){let n=1-Math.abs(e-t)/5,r=U(l[e],n*n*(3-2*n));(!f[t]||G(r)>G(f[t]))&&(f[t]=r)}}for(let t=0;t<a;t++){if(!f[t])continue;let n=e.f0+t,r=V(d.get(n)??[0,0,0],f[t]);d.set(n,r),c=Math.max(c,G(r)),u.add(n)}}if(!u.size)break;l++,t.solve([...u])}return!s.size&&!o.skipped?null:{frames:s.size,max:nb(c),passes:l,skipped:o.skipped,how:`hand pushed out of the other person, back the way it came`}}var kx=[`reach`,`slide`,`penetration`,`self`,`retime`,`stance`,`grasp`,`person`];function Ax(e){if(e===!1)return{reach:!1,slide:!1,penetration:0,self:!1,retime:!1,stance:!1,grasp:!1,person:!1};let t=e??{},n=t.penetration===!0?.02:Math.min(.05,Math.max(0,Number(t.penetration)||0));return{reach:t.reach!==!1,slide:t.slide!==!1,penetration:n,self:t.self!==!1,retime:t.retime===!0,stance:t.stance!==!1,grasp:t.grasp!==!1,person:t.person!==!1}}var jx=(e,t)=>e?{...t??{frames:0,how:`planted heel/ball held in place`},turns:e,how:`${t?.how??`planted heel/ball held in place`}; a flat planted foot keeps its heading until it lifts`}:t,Mx=(e,t)=>e&&t?{frames:Math.max(e.frames,t.frames),eased:Math.max(e.eased,t.eased),max:Math.max(e.max,t.max),how:e.how}:e??t;function Nx(e,t,n,{whole:r=!0}={}){let i={},a=(e,t)=>{t&&(i[e]=t)};return t.retime&&r&&a(`retime`,qb(e,n)),t.slide&&a(`ground`,Pb(e,n)),t.reach&&a(`reachLegs`,ib(e,n)),t.reach&&a(`reachBody`,bb(e,n)),t.slide&&a(`slide`,jx(Ab(e,n),Tb(e,n))),t.reach&&i.slide?.pivots&&a(`reachLegs`,Mx(i.reachLegs,ib(e,n))),t.penetration>0&&a(`penetration`,Bb(e,n,t.penetration)),t.self&&a(`self`,vx(e,n)),t.person&&a(`person`,Ox(e,n)),t.reach&&a(`reachArms`,ab(e)),i}var Px=.15,Fx=.12,Ix=400,Lx=.02,Rx=60;function zx(e){let t=Mc(e),n=e.half;return t.kind===`sphere`?4/3*Math.PI*t.r**3:t.kind===`cylinder`?Math.PI*t.r*t.r*t.h:8*n[0]*n[1]*n[2]}function Bx(e,t,n){let r=e?.objects?.[n]?.mass;if(Number.isFinite(r))return r;let i=sg(t,n).map(e=>t.objects[e]);if(i.length===1&&Mc(i[0]).kind===`sphere`&&2*Mc(i[0]).r<Fx)return Px;let a=i.reduce((e,t)=>e+zx(t)*Ix,0);return Math.min(Rx,Math.max(Lx,a))}var Vx=10,Hx=9.81,Ux=2,Wx=.06,Gx=.006,Kx=25,qx=.5,Jx=`load: what each hand carries, kg, and its most N m (mass x 9.81 x the shoulder-to-wrist distance across) at f; frames [first, last] held`,Yx=e=>e?.fix!==!1&&e?.fix?.grasp!==!1,Xx=e=>{let t=Math.min(1,Math.max(0,e));return t*t*(3-2*t)},Zx=e=>Object.entries(e.objects??{}).filter(([,t])=>b_(t)&&e.props?.[t.prop]).map(([t,n])=>[t,n,e.props[n.prop].hand]);function Qx(e,t,n,r,i,a){let{spec:o,scene:s,sk:c}=e;if(!Yx(o)||!(a>.001))return null;for(let[l,u,d]of Zx(o)){if(d!==t||u.keys?.length)continue;let f=Bx(o,s,l),[p,m]=e.carrySpan(u);if(n<p||n>m||f*Hx*Nd(c,t)<Ux)continue;let h=Xx((n-p)/4)*Xx((m-n)/4)*a,g=Math.min(Wx,Gx*f)*h;if(!(g>0))return null;let _=H(r.P[c.index[`${n_[t]}Arm`]],i),v=G([_[0],0,_[2]])>1e-6?K([_[0],0,_[2]]):[0,0,0];return V([0,-g,0],U(v,g))}return null}var $x=(e,t,n,r)=>{let i=H(t.P[e.index[`${n_[n]}Hand`]],t.P[e.index[`${n_[n]}Arm`]]);return r*Hx*Math.hypot(i[0],i[2])};function eS(e,t,n){let{spec:r,scene:i}=t.ctx,a=t.f0??0;if(!Yx(r))return;let o=Zx(r).map(([e,t,n])=>({id:e,o:t,k:n,mass:Bx(r,i,e)}));o.length&&t.frames.forEach(({s:r},i)=>{let s=i+a;for(let i of o)Og(t,i.id,s)===i.k&&n({...i,f:s,Nm:$x(e,r,i.k,i.mass)})})}function tS(e,t){let n={};eS(e,t,({id:e,k:t,mass:r,f:i,Nm:a})=>{let o=n[`hand_${t}`]??={object:e,mass:Math.round(r*1e3)/1e3,maxNm:0,at:i,frames:[i,i]};a>o.maxNm&&(o.maxNm=a,o.at=i),o.frames[1]=i});for(let e of Object.values(n))e.maxNm=Math.round(e.maxNm*10)/10;return Object.keys(n).length?n:null}function nS(e,t,n,r,i){let a=r===`r`?`l`:`r`,{spec:o,scene:s}=e.ctx,c=new Set([t,...sg(s,t)]);return Object.entries(o.anchors??{}).some(([t,r])=>(e.baked?.[`w_${t}_${a}`]?.[i]??0)>qx&&(r.kind===`object`&&c.has(r.object)||r.kind===`prop`&&r.prop===n.prop))}function rS(e,t){let n=[];return eS(e,t,({id:e,o:r,k:i,f:a,Nm:o})=>{o>Kx&&!nS(t,e,r,i,a)&&n.push({kind:`LOAD`,msg:`${n_[i].toLowerCase()} holds ${e} at ${o.toFixed(0)} N m`,frame:a,value:Math.round(o*10)/10,limit:Kx})}),n}function iS(e,t,n){let{sk:r,scene:i}=e.ctx,a=e.frames[n-(e.f0??0)]?.s,o=kg(e,t,n),s=ml(i,t),c=i.objects[sg(i,t)[0]]??i.objects[t];if(!a||!o||!c?.half)return null;let l=e=>J(Y(o.R),H(e,o.pos)),u=J(Y(s.R),H(V(c.pos,J(c.R,[0,c.half[1],0])),s.pos)),d=l(U(V(a.P[r.index.RightHand],a.P[r.index.RightHandMiddle1]),.5)),f=l(a.P[r.index.LeftArm]),p=[0,1,2].flatMap(e=>[-1,1].map(t=>{let n=u.slice();return n[e]+=t*c.half[e],{p:n,i:e,sg:t}})).filter(e=>!(e.i===1&&e.sg<0)),m=p.reduce((e,t)=>Math.abs(d[t.i]-t.p[t.i])<Math.abs(d[e.i]-e.p[e.i])?t:e);return p.filter(e=>e!==m).reduce((e,t)=>G(H(t.p,f))<G(H(e.p,f))?t:e).p.map(e=>Math.round(e*1e3)/1e3)}var aS={LOAD(e,t){let[,n,r]=/^(left|right) holds (\S+) at/.exec(t.subject)??[],i=e.spec?.objects?.[r];if(!i||!e.out)return null;let a=n===`left`?`l`:`r`,o=a===`r`?`left`:`right`,[s]=dg(e.out,i),c=Bx(e.spec,e.out.ctx.scene,r),l={cause:`objects.${r} (${c.toFixed(1)} kg)`,hint:`${r} weighs ${c.toFixed(1)} kg: ${t.worst.toFixed(0)} N m on the ${n} arm at f${t.worstFrame} (one hand holds ${Kx}); put the ${o} hand on it too (a reachGrip on an object anchor on ${r} from f${s}), or carry it closer to the body`};if(a!==`r`)return l;let u=iS(e.out,r,Math.max(s,Math.min(t.worstFrame,dg(e.out,i)[1])));if(!u)return l;let d=`${r}Other`,f={kind:`object`,object:r,local:u,grasp:`palm`};return{...l,fix:{ops:t=>[t.anchors?{op:`add`,path:`/anchors/${d}`,value:f}:{op:`add`,path:`/anchors`,value:{[d]:f}},{op:`add`,path:`/use/-`,value:{skill:`reachGrip`,f0:Math.max(0,s-Vx),args:{anchor:d,side:`l`,reach:Math.min(Vx,s)||1,hold:Math.max(1,dg(e.out,i)[1]-s),release:1}}}]}}}},oS=e=>e*e*(3-2*e),sS=.02;function cS(e,t,n,r=()=>void 0){let i=new Map,a=new Map,o=r(),s=s=>{if(r()!==o&&(o=r(),i.clear(),a.clear()),i.has(s))return i.get(s);let c={};for(let[r,i]of Object.entries(t?.objects??{})){let a=[r,...i.ancestors??[]].find(t=>C_(e.objects?.[t])),l=e.objects?.[a];c[r]=l?b_(l)||x_(l)?{...i,carried:a}:Ph(l)?{...i,...D_(tg({spec:e,scene:t,timeMap:o},a,s),O_(t.objects[a]??Jl(t)[a],i))}:{...i,...k_(l,i,n,s)}:i}return i.set(s,c),c};return{all:s,obstacles:e=>(r()!==o&&s(e),a.has(e)||a.set(e,Object.fromEntries(Object.entries(s(e)).filter(([,e])=>!e.carried))),a.get(e))}}function lS(e,t,n,r){if(r.prop)return n.props?.[r.prop]?.[r.point];let i=r.joints??[`RightHandIndex2`,`RightHandMiddle2`];return U(i.map(n=>t.P[e.index[n]]).reduce((e,t)=>V(e,t),[0,0,0]),1/i.length)}function uS(e,t,n,r=!1,i=!0,a=null){let{sk:o}=e;return{softReach:e.softReach,foldFree:r,hold:i&&e.hold?(r,i)=>r===a?null:e.hold.lead(r,n,i,t):void 0,push:r?void 0:t=>e.push?.[t]?.get(n),swivel:t=>e.swivel?.[t]?.get(n),skinPush:r?void 0:t=>e.skinPush?.[t]?.get(n),handTarget(r,i,a){a.frame=n;let s=i.P[o.index[r===`l`?`LeftHand`:`RightHand`]],c=[];for(let[n,o]of Object.entries(t)){let s=/^w_(.+)_([lr])$/.exec(n);!s||s[2]!==r||!(o>1e-6)||c.push([o,V(Fd(e,s[1],i,a,t,r),t[`fit_${s[1]}_${r}`]??[0,0,0])])}let l=c.reduce((e,[t])=>e+t,0);if(l>1){for(let e of c)e[0]/=l;l=1}let u=U(t[`hand_${r}`]??s,1-l);for(let[e,t]of c)u=V(u,U(t,e));let d=Math.max(0,...c.map(([e])=>oS(Math.min(1,Math.min(e,1-e)*3))));if(d>0){let n=i.P[o.index.Spine],r=i.P[o.index.Neck],a=H(r,n),s=V(n,U(a,Math.min(1,Math.max(0,W(H(u,n),a)/W(a,a))))),c=e.spec.detourRadius??.25,l=H(u,s),f=G(l);if(f<c){let e=J(wo([0,1,0],t.yaw??0),[0,0,1]),n=K(V(f>1e-6?U(l,1/f):e,U(e,.6)));u=V(u,U(H(V(s,U(n,c)),u),d))}}return u},keepOut:e.keepOut&&!r?(n,r,i)=>{let a=(1-dx(e.spec,t,n))*Math.min(1,Math.max(0,t[`armw_${n}`]??0));for(let t=0;t<2&&a>.001;t++){let t=Rs(e.keepOut.body,o,r,i,zs,e.keepOut.skip);if(t===i)break;i=V(i,U(H(t,i),a))}return i}:void 0,afterArm:(t,n,r)=>Gd(e,t,n,r),grip:r?void 0:(r,i,a)=>Y_(e,o,i,n_[r],r,t,n,a),sag:r?void 0:(r,i,a)=>Qx(e,r,n,i,a,(1-dx(e.spec,t,r))*Math.min(1,Math.max(0,t[`armw_${r}`]??0))),heldShapes:r||!e.grasp?void 0:(r,i)=>Yg(e,t,n,r,i),fingerWeights:r||!e.grasp?void 0:r=>Qg(e,t,n,r)}}function dS(e,t,n,r=!0){let i={...cv(t,e.idle,n)};for(let t of[`l`,`r`])e.busy?.[t]&&(i[`hangoff_${t}`]=e.busy[t][n]);for(let t of e.spec.fits??[]){let a=`w_${t.anchor}_${t.side}`;if(!(i[a]>1e-4))continue;let o={...i,[a]:1,[`armw_${t.side}`]:1};for(let e of Object.keys(o))e!==a&&RegExp(`^w_.+_${t.side}$`).test(e)&&(o[e]=0);let s=[0,0,0],c=null,l=null,u=wm(e.spec,t.anchor),d=e.sk.index[`${n_[t.side]}Arm`],f=e.sk.index[`${n_[t.side]}Hand`];for(let i=0;i<6;i++){o[`fit_${t.anchor}_${t.side}`]=s;let{s:i,diag:a}=y_(e.sk,o,uS(e,o,n,!0,r,t.side)),p=lS(e.sk,i,a,t.effector),m=V(Fd(e,t.anchor,i,a,o,t.side),t.offset??[0,0,0]);if(!p)break;let h=H(m,p),g=G(h);u&&(!c||g<c.err)&&(c={err:g,hand:H(i.P[f],p)}),l={goal:m,shoulder:i.P[d]},s=V(s,h)}u&&c&&l&&G(H(V(l.goal,s),l.shoulder))>Nd(e.sk,t.side)+sS&&(s=c.hand),i[`fit_${t.anchor}_${t.side}`]=s}let{s:a,diag:o}=y_(e.sk,i,uS(e,i,n,!1,r));return o.frame=n,{s:a,diag:o,c:i}}function fS(e,{sk:t,scene:n},r={}){if(e?.schema!==`cozyclay.motion-spec.v1`)throw Error(`MOTION_SPEC_INVALID: schema must be cozyclay.motion-spec.v1`);let i=Math.round(e.frames);if(!(i>=1&&i<=2e4))throw Error(`MOTION_SPEC_INVALID: frames must be 1..20000`);let a=Ax(e.fix),[o,s]=r.window?[Math.max(0,r.window[0]),Math.min(i-1,r.window[1])]:[0,i-1],c={sk:t,spec:e,scene:n,grasp:a.grasp,softReach:a.reach,push:{l:new Map,r:new Map},swivel:{l:new Map,r:new Map},skinPush:{l:new Map,r:new Map},keepOut:a.self?Bs(t):null},l={ctx:c,fps:e.fps??30,frameCount:i,f0:o,frames:[]};c.objectPose=(e,t,n)=>kg(l,e,t,n),c.objectHand=(e,t)=>Og(l,e,t),c.restingAt=(e,t)=>_g(l,e,t),c.carrySpan=e=>dg(l,e),c.solvedAt=e=>yg(l,e),c.weightAt=(e,t)=>l.baked?.[e]?.[t],c.frameCount=i;let u={rebake(r){l.keys=r;let a=Rf(e.flow,e.label??``,Ef(e));l.baked=Vf(r,i,a),c.socketTurns=new Map,c.graspPlans=new Map,Gy(l.baked,r,i),eb(l.baked,r,i,a.headLead),c.idle=sv(l.baked,{spec:e,sk:t,frameCount:i}),c.busy=ov(l.baked,e,i,l.fps);let s=cS(e,n,l.baked,()=>l.timeMap);c.objectsAt=s.all,l.objectsAt=o?e=>s.obstacles(e+o):s.obstacles},solve(e){for(let t of e)t>=o&&t<=s&&(l.frames[t-o]=dS(c,Hf(l.baked,t),t))},all:()=>Array.from({length:s-o+1},(e,t)=>o+t)};return c.hold=Hm(c,l,e=>dS(c,Hf(l.baked,e),e,!1),e=>dS(c,Hf(l.baked,e),e)),u.rebake(r.keys??Ly(e,t)),u.solve(u.all()),l.fixed=r.fixes===!1?{}:Nx(l,a,u,{whole:!r.window}),c.hold&&l.timeMap&&u.solve(u.all()),l}var pS=`{ f, pos: [x, y, z], rot: [x, y, z, w] } or { f, pos, aim: [x, y, z], roll? }`,mS=`{ at, onto?, bounce?, tumble?, v? }`,hS=e=>Array.isArray(e)&&e.length===4&&e.every(Number.isFinite)&&Math.abs(Math.hypot(...e)-1)<=.01,gS=e=>nl(e)&&Math.hypot(...e)>1e-9;function _S(e,t,n){if(n.rot!==void 0&&n.aim!==void 0)return e(`${t} gives both rot and aim; give one: rot [x, y, z, w], or aim [x, y, z] (the world direction its +Y points) with roll`);if(n.aim===void 0){n.roll!==void 0&&e(`${t}.roll turns the object about aim; give aim [x, y, z] with it, or leave roll out (rot fixes the roll)`),n.lean!==void 0&&e(`${t}.lean lets the compiler lean aim; give aim [x, y, z] with it (rot is used exactly)`),hS(n.rot)||e(`${t}.rot must be a unit quaternion [x, y, z, w], got ${Z(n.rot)}${n.rot===void 0?`; or give aim [x, y, z], the world direction its +Y points`:``}`);return}gS(n.aim)||e(`${t}.aim must be a non-zero world direction [x, y, z] for the object's +Y (a bat: knob to barrel), got ${Z(n.aim)}`),n.roll!==void 0&&!Number.isFinite(n.roll)&&e(`${t}.roll must be degrees about aim (a number), got ${Z(n.roll)}`),n.lean!==void 0&&!(Number.isFinite(n.lean)&&n.lean>=0&&n.lean<=45)&&e(`${t}.lean must be the most degrees the compiler may lean aim (0..45), got ${Z(n.lean)}`)}function vS(e,t,n,r,i,a=!1){if(!Array.isArray(r.keys))return e(`${n}.keys must be an array of ${pS}`);let o=Number.isInteger(i)?i-1:1/0,s=a?0:r.grab??0,c=a?o:r.release??o,l=new Map;r.keys.forEach((r,i)=>{let o=`${n}.keys[${i}]`;if(!r||typeof r!=`object`||Array.isArray(r))return e(`${o} must be ${pS}, got ${Z(r)}`);for(let e of Object.keys(r))El.includes(e)||t(`${o} has unknown field "${e}"${il(e,El)}; a key is ${pS}`);Number.isInteger(r.f)?r.f<s||r.f>c?e(a?`${o}.f = ${r.f} is outside the take (0..${c})`:`${o}.f = ${r.f} is outside grab..release (${s}..${c}); keys pose a carried object only while it is in hand (drop its prop to move it on its own, C17)`):l.has(r.f)?e(`${o}.f = ${r.f}: keys[${l.get(r.f)}] is at that frame already; one key per frame`):l.set(r.f,i):e(`${o}.f must be a whole frame, got ${Z(r.f)}`),nl(r.pos)||e(`${o}.pos must be [x, y, z], the world position of the object's base (a group: its root), got ${Z(r.pos)}`),_S(e,o,r)})}function yS(e,t,n,r,i){let a=/^object:(.+?)(?:\.(?:center|top|base))?$/s.exec(i)?.[1];if(a===void 0)return;let o=sg(n,a).flatMap(t=>[t,...n.objects[t].ancestors??[]].find(t=>C_(e.objects?.[t]))??[]).find(t=>x_(e.objects[t]));o&&t(`${r} "${i}": "${a}" moves with the follow entry objects.${o}; a follow entry rides a joint, landmark, prop or anchor point, or an object no follow entry moves`)}function bS(e,t,n,r,i){tf(e,t,n,`${r}.follow`,i.follow)&&yS(e,t,n.scene,`${r}.follow`,i.follow),i.offset!==void 0&&!nl(i.offset)&&t(`${r}.offset must be [x, y, z], metres along the record's own axes after aim (+Y along aim), got ${Z(i.offset)}`);let a=i.aim;if(a!==void 0&&a!==`face`&&a!==`up`){if(Array.isArray(a)){gS(a)||t(`${r}.aim must be a non-zero world direction [x, y, z], got ${Z(a)}`);return}if(typeof a!=`string`||!/^[a-z]+:/.test(a))return t(`${r}.aim must be "face", "up", a world direction [x, y, z] or a point ref (toward it), where the record's +Y points; got ${Z(a)}`);tf(e,t,n,`${r}.aim`,a)&&yS(e,t,n.scene,`${r}.aim`,a)}}function xS(e,t,n,r){return n===void 0||Number.isInteger(n)&&n>=0&&(!Number.isInteger(r)||n<r)?!0:(e(`${t} must be a whole frame 0..${Number.isInteger(r)?r-1:`frames-1`}, got ${Z(n)}`),!1)}function SS(e,t,n,r,{frames:i,scene:a,carry:o}){let s=Array.isArray(r.fall)?r.fall:[r.fall],c=new Set;s.length||e(`${n}.fall is an empty list; give ${mS} or a list of them`),s.forEach((s,l)=>{let u=Array.isArray(r.fall)?`${n}.fall[${l}]`:`${n}.fall`;if(!s||typeof s!=`object`||Array.isArray(s))return e(`${u} must be ${mS} (at: the frame it starts to fall), got ${Z(s)}`);for(let e of Object.keys(s))Tl.includes(e)||t(`${u} has unknown field "${e}"${il(e,Tl)}; a fall is ${mS}`);if(s.at===void 0)e(`${u}.at must be the whole frame it starts to fall`);else if(xS(e,`${u}.at`,s.at,i)){c.has(s.at)&&e(`${u}.at = ${s.at}: another fall starts on that frame`),c.add(s.at);let t=r.grab??0,n=r.release;o&&s.at>=t&&(n===void 0||s.at<n)&&e(`${u}.at = ${s.at} is while it is in hand (grab ${t}..release ${n??`end`}); a carried object falls before its grab or from its release on`)}s.onto!==void 0&&Hl(e,a,`${u}.onto`,s.onto,{groups:!0}),s.bounce!==void 0&&!(Number.isFinite(s.bounce)&&s.bounce>=0&&s.bounce<=.6)&&e(`${u}.bounce must be 0..0.6 (the share of its landing speed it bounces back with; 0 lands dead), got ${Z(s.bounce)}`),s.v!==void 0&&!(o&&s.v===`hand`||nl(s.v))&&e(`${u}.v must be [vx, vy, vz] m/s (the velocity it leaves with)${o?` or "hand" (the velocity the hand gives it at the release)`:``}, got ${Z(s.v)}`),s.tumble!==void 0&&typeof s.tumble!=`boolean`&&e(`${u}.tumble must be true (it rolls to rest on a stable face, the default) or false (it drops straight down as it was), got ${Z(s.tumble)}`)})}function CS(e,t,n,r){let i=r.spring,a=`{ length?, stiffness?, damping? }`;if(!i||typeof i!=`object`||Array.isArray(i))return e(`${n}.spring must be ${a}, got ${Z(i)}`);for(let e of Object.keys(i))wl.includes(e)||t(`${n}.spring has unknown field "${e}"${il(e,wl)}; a spring is ${a}`);let o={length:`string or rod length, m`,stiffness:`how fast it swings back, 1/s^2`,damping:`how soon it settles, 1 = no overshoot`};for(let t of wl){let r=i[t],{min:a,max:s}=yh[t];r!==void 0&&!(Number.isFinite(r)&&r>=a&&r<=s)&&e(`${n}.spring.${t} must be ${a}..${s} (${o[t]}), got ${Z(r)}`)}}var wS=(e,t)=>{let n=0;for(;n<e.length&&e[n]===t[n];)n+=1;return n};function TS(e){let t=String(e),n=Kc.reduce((e,n)=>wS(n,t)>wS(e,t)?n:e);return wS(n,t)>=4?`; did you mean "${n}"?`:il(t,Kc)}function ES(e,t,n){n.mass!==void 0&&!(Number.isFinite(n.mass)&&n.mass>=.01&&n.mass<=60)&&e(`${t}.mass must be kg in 0.01..60, got ${Z(n.mass)}`)}function DS(e,t,n){n.visible!==void 0&&(typeof n.visible!=`string`||!n.visible)&&e(`${t}.visible must name a channel (shown above 0.5)`),n.level!==void 0&&(typeof n.level!=`string`||!n.level)&&e(`${t}.level must name a channel (the record's level 0..4: 0 dark, 1 as authored; it scales its light, glow and effect rate)`)}function OS(e,t,{sk:n,scene:r,frames:i=e.frames,unknown:a=t}){for(let[o,s]of Object.entries(e.objects??{})){let c=`objects.${o}`,l=s?.prop===void 0?x_(s)?`follow`:Ph(s)?`free`:S_(s)?`switch`:`hinge`:`carry`,u=Cl[l];(l!==`switch`&&l!==`follow`||!r?.others?.[o])&&Hl(t,r,c,o,{groups:!0}),l===`hinge`&&s?.spring!==void 0&&t(`${c}.spring: spring is not for hinged objects; a hinge turns only by its channel (give spring to a carry or a free entry)`);for(let e of Object.keys(s??{}))!u.includes(e)&&(l!==`hinge`||e!==`keys`&&e!==`fall`&&e!==`spring`)&&a(`${c} (${l}) has unknown field "${e}"${il(e,u)}; fields: ${u.join(`, `)}`);if(ES(t,c,s),l===`follow`){bS(e,t,{sk:n,scene:r},c,s),DS(t,c,s);continue}if(l===`switch`){s.visible===void 0&&s.level===void 0&&t(`${c} needs visible or level (a channel): a switch shows, hides or dims "${o}" without moving it; a carry needs prop, a hinge pivot and channel`),DS(t,c,s);continue}if(l===`free`){s.keys!==void 0&&vS(t,a,c,s,i,!0),s.fall!==void 0&&SS(t,a,c,s,{frames:i,scene:r,carry:!1}),s.spring!==void 0&&CS(t,a,c,s),DS(t,c,s);continue}if(l===`carry`){e.props?.[s.prop]||t(`${c}.prop "${s.prop}" is not in spec.props`);for(let e of[`at`,`along`])s[e]!==void 0&&!nl(s[e])&&t(`${c}.${e} must be [d, l, n] along the palm axes, got ${Z(s[e])}`);s.grasp!==void 0&&!Kc.includes(s.grasp)&&t(`${c}.grasp must be one of ${Kc.join(`, `)}${TS(s.grasp)}, got ${Z(s.grasp)}`),DS(t,c,s),xS(t,`${c}.grab`,s.grab,i)&&xS(t,`${c}.release`,s.release,i)&&s.grab!==void 0&&s.release!==void 0&&!(s.grab<s.release)&&t(`${c}: grab (${s.grab}) must come before release (${s.release})`),s.keys!==void 0&&vS(t,a,c,s,i),s.fall!==void 0&&SS(t,a,c,s,{frames:i,scene:r,carry:!0}),s.spring!==void 0&&CS(t,a,c,s);continue}(s?.keys!==void 0||s?.fall!==void 0)&&t(`${c}: a hinge turns by its channel "${s.channel}", keyed in spec.keys; keys and fall move an object with no pivot, axis or channel (C17), or a carried one (prop)`),nl(s?.pivot)||t(`${c}.pivot must be [x, y, z] (world hinge point), got ${Z(s?.pivot)}`),s?.axis!==void 0&&(!nl(s.axis)||Math.hypot(...s.axis)<1e-9)&&t(`${c}.axis must be a non-zero [x, y, z], got ${Z(s.axis)}`),(typeof s?.channel!=`string`||!s.channel)&&t(`${c}.channel must name the angle channel (degrees)`)}}var Q=e=>{let t=Math.round(e*1e3)/1e3;return Object.is(t,-0)?0:t},kS=e=>`[${e.map(e=>{let t=Q(e);return t>0?`+${t}`:`${t}`}).join(`, `)}]`,AS=[`near`,`above`,`moved`,`still`,`speed`],jS={near:.05,above:0,moved:.05,still:.01},MS=new Set([`near`,`still`]),NS=new Set([`moved`,`still`,`speed`]),PS=e=>AS.filter(t=>e?.[t]!==void 0),FS=(e,t)=>e.name??`goals[${t}]`,IS=(e,t)=>(MS.has(t)?e.tol:e.by)??jS[t],LS=(e,t)=>e.mode??(t===`speed`?`any`:`all`),RS=e=>!e.startsWith(`object:`)||/\.(center|top|base|rim)$/.test(e)?e:`${e}.base`;function zS(e,t){let[,n,r]=/^object:(.+)\.(center|top|base|rim)$/s.exec(RS(t))??[],i=sg(e,n).map(t=>e.objects[t]);if(!i.length)return null;if(r===`rim`)return Yd(i).o;let a=[1/0,1/0,1/0],o=[-1/0,-1/0,-1/0];for(let e of i)for(let t of[-1,1])for(let n of[0,2])for(let r of[-1,1]){let i=V(e.pos,J(e.R,[t*e.half[0],n*e.half[1],r*e.half[2]]));for(let e=0;e<3;e++)a[e]=Math.min(a[e],i[e]),o[e]=Math.max(o[e],i[e])}let s=[(a[0]+o[0])/2,(a[1]+o[1])/2,(a[2]+o[2])/2];return r===`top`?[s[0],o[1],s[2]]:r===`base`?[s[0],a[1],s[2]]:s}var BS=e=>e.moved??e.still,VS=(e,t,n=Array.isArray(t.at)?t.at[0]:t.at)=>BS(t).startsWith(`object:`)?zS(e.ctx.scene,BS(t)):Zd(e,n,BS(t));function HS(e,t,n){let r=Zd(e,n,t),i=e.fps??24;if(!r)return null;let a=Zd(e,n-1,t),o=Zd(e,n+1,t);if(a&&o)return G(H(o,a))*i/2;let s=a??o;return s?G(H(r,s))*i:null}var US=`landmark:mouth`,WS=/^object:(.+)\.top$/s;function GS(e,t){let[n,r]=t.near,i=[n,r].map(e=>WS.exec(e)?.[1]),a=i[0]&&r===US?0:i[1]&&n===US?1:-1;if(a<0)return t.near;let o=sg(e,i[a]).map(t=>e.objects[t]).filter(e=>e?.half&&e.pos&&e.R);return(o.length?o.reduce((e,t)=>t.pos[1]+2*t.half[1]>e.pos[1]+2*e.half[1]?t:e):null)?.renderer===`cylinder`?t.near.map((e,t)=>t===a?`object:${i[a]}.rim`:e):t.near}function KS(e,t){let n=t.near.find(e=>WS.test(e));if(!n)return``;let r=WS.exec(n)[1];return GS(e,t)===t.near?` (${n} is the top-face centre of its world bounding box; object:${r}.rim is its opening, which tilts with it)`:` (measured at ${r}'s rim nearest the mouth, object:${r}.rim; its .top is its bounding box's top)`}function qS(e,t,n,r,i){if(n===`near`){let[n,i]=GS(e.ctx.scene,t);return Qd(e,r,n,i)}if(n===`above`){let n=Zd(e,r,t.above[0]),i=Zd(e,r,t.above[1]);return n&&i?n[1]-i[1]:null}if(n===`speed`)return HS(e,t.speed,r);let a=i&&Zd(e,r,RS(BS(t)));return a?G(H(a,i)):null}var JS=(e,t,n)=>MS.has(e)?t-n:n-t,YS=e=>Math.max(1e-4,Math.round(e*1e4)/1e4);function XS(e,t,n,r,i){let a=IS(t,n),o=(n===`moved`||n===`still`)&&!BS(t).startsWith(`object:`),s=n===`moved`||n===`still`?VS(e.out,t,r):null,c=[];for(let o=Math.max(r,e.f0);o<=Math.min(i,e.last);o++){let r=qS(e.out,t,n,o,s);r!==null&&c.push({f:o,v:r,short:JS(n,r,a)})}return{rows:c,from:o?r:void 0}}function ZS(e,t){if(e.events.has(t))return e.events.get(t);if(e.visiting.has(t))return null;e.visiting.add(t);let n=e.goals[t],r=PS(n)[0],i=r&&QS(e,t),a;if(i&&!i.wait){let{rows:t}=XS(e,n,r,i.a,i.b);a=t.length?t.find(e=>e.short<=0)?.f??null:void 0}else a=i?.wait?null:void 0;return e.visiting.delete(t),e.events.set(t,a),a}function QS(e,t){let n=e.goals[t],[r,i]=Array.isArray(n.at)?n.at:[n.at,n.at];for(let a of[`after`,`before`]){if(n[a]===void 0)continue;let o=e.names.get(n[a]);if(o===void 0||o===t)return{wait:`${a} "${n[a]}" names no other goal`};let s=ZS(e,o);if(s===void 0)return{skip:!0};if(s===null)return{wait:`waits for "${n[a]}" (${a}), which never holds`};if(a===`after`?r=Math.max(r,s+1):i=Math.min(i,s-1),r>i)return{wait:`no frames left ${a} "${n[a]}" (it holds first at f${s}; at is f${Array.isArray(n.at)?`${n.at[0]}-f${n.at[1]}`:n.at})`}}return{a:r,b:i}}function $S(e,t,n,r,i,a,o=``){let s=i?`f${n.f}, the best of f${i[0]}-f${i[1]}`:`f${n.f}`;return t===`near`?`${e}: ${Q(n.v)} m at ${s} (needs <= ${r})${o}`:t===`above`?`${e}: ${Q(n.v)} m above at ${s} (needs >= ${r})`:t===`speed`?`${e}: ${Q(n.v)} m/s at ${s} (needs >= ${r})`:t===`still`?`${e}: ${Q(n.v)} m from ${a===void 0?`its scene pose`:`f${a}`} at ${s} (needs <= ${r})`:`${e}: moved ${Q(n.v)} m${a===void 0?``:` from f${a}`} at ${s} (needs >= ${r})`}function eC(e,t,n){let r=e.f0??0;return QS({out:e,goals:t,names:new Map(t.map((e,t)=>[FS(e,t),t])),f0:r,last:r+(e.frames?.length??0)-1,events:new Map,visiting:new Set},n)}function tC(e,t){let n=[],r=[],i=e.f0??0,a={out:e,goals:t,names:new Map(t.map((e,t)=>[FS(e,t),t])),f0:i,last:i+(e.frames?.length??0)-1,events:new Map,visiting:new Set};return t.forEach((t,o)=>{let s=PS(t)[0];if(!s)return;let c=FS(t,o),l=IS(t,s),u=QS(a,o),d=Array.isArray(t.at)?t.at[0]:t.at;if(u.skip)return;if(u.wait){r.push({name:c,kind:s,ok:!1,value:null,at:null,need:l}),d>=i&&d<=a.last&&n.push({kind:`GOAL`,msg:`${c}: ${u.wait}`,frame:d-i,value:.01,limit:0});return}let{rows:f,from:p}=XS(a,t,s,u.a,u.b);if(!f.length)return;s===`moved`&&p!==void 0&&(f=[f.reduce((e,t)=>t.v>e.v?t:e)]);let m=LS(t,s)===`any`,h=Array.isArray(t.at)?u.a!==u.b:!1,g=f.reduce((e,t)=>(m?t.short<e.short:t.short>e.short)?t:e),_=g.short<=0;if(r.push({name:c,kind:s,ok:_,value:Q(g.v),at:g.f,need:l}),_)return;let v=s===`near`?KS(e.ctx.scene,t):``;for(let e of m?[g]:f.filter(e=>e.short>0))n.push({kind:`GOAL`,msg:$S(c,s,e,l,m&&h?[u.a,u.b]:null,p,s===`near`?v:``),frame:e.f-i,value:YS(e.short),limit:0})}),{issues:n,results:r}}var nC=`{ name?, near | above | moved | still | speed, tol?, by?, at, mode?, after?, before? }`,rC=new Set([`near`,`still`]),iC=new Set([`above`,`moved`,`speed`]);function aC(e,t){let n=Number.isFinite(t)&&t!==0?Math.abs(t):.05;return e===`speed`?`speed takes by (the point reaches by m/s): use by: ${n} (m/s), not tol`:e===`above`?`above takes by (a.y - b.y >= by, default 0): use by: ${n} for a at least ${n} m above b, or by: -${n} to let a sit up to ${n} m below b, not tol`:`moved takes by (the object moves >= by, default 0.05): use by: ${n} (metres), not tol`}var oC=e=>typeof e==`string`&&e!==``&&!/^[a-z]+:/.test(e),sC=e=>[`moved`,`still`,`speed`].find(t=>oC(e?.[t]));function cC(e){return Array.isArray(e)&&e.some(sC)?e.map(e=>{let t=sC(e);return t?{...e,[t]:`object:${e[t]}`}:e}):e}function lC(e,t,n,r,i=``){let a=e=>Number.isInteger(e);if(n===void 0)return e(`${t} needs at: a frame or [f0, f1] (absolute frames within 0..${r-1})`);let o=Array.isArray(n)?n:[n,n];if(!(o.length===2&&o.every(a)&&o[0]<=o[1]))return e(`${t}.at must be an integer frame or [f0, f1] with f0 <= f1, got ${Z(n)}`);(o[0]<0||o[1]>r-1)&&e(`${t}.at = ${Z(n)} is outside 0..${r-1} (spec.frames ${r})${o[1]>r-1?i:``}`)}function uC(e,t,n,r,i,a){let o=i[a];if(typeof o!=`string`)return t(`${r}.${a} must be an object id or a point ref (object:<id>[.center|.top|.base], prop:<prop>.<point>, joint:<Bone>, landmark:mouth, anchor:<name>), got ${Z(o)}`);tf(e,t,n,`${r}.${a}`,o)&&a!==`speed`&&!o.startsWith(`object:`)&&(Number.isInteger(i.at)||Array.isArray(i.at)&&i.at[0]===i.at[1])&&t(`${r}.${a} "${o}" measures ${a===`moved`?`how far the point gets`:`how far the point strays`} from where it is at at[0], so at must be [f0, f1] with f0 < f1, got ${Z(i.at)}`)}function dC(e,t,n,r,i,a){let o=`goals[${i}]`,s={sk:n.sk,scene:n.scene},c=n.unknown??t;if(!r||typeof r!=`object`||Array.isArray(r))return t(`${o} must be ${nC}, got ${Z(r)}`);for(let e of Object.keys(r))Al.includes(e)||c(`${o} has unknown field "${e}"${il(e,Al)} (fields: ${Al.join(`, `)})`);r.name!==void 0&&(typeof r.name!=`string`||!r.name.trim()?t(`${o}.name must be a non-empty string, got ${Z(r.name)}`):a.has(r.name)?t(`${o}.name "${r.name}" is already used by goals[${a.get(r.name)}]; goal names must differ`):a.set(r.name,i));let l=PS(r),u=l[0];if(l.length||t(`${o} needs one predicate: ${AS.join(`, `)}`),l.length>1&&t(`${o} names ${l.join(` and `)}; a goal takes exactly one of ${AS.join(`, `)} (split it into ${l.length} goals)`),l.length===1&&NS.has(u))uC(e,t,s,o,r,u);else if(l.length===1){let n=r[u];Array.isArray(n)&&n.length===2&&n.every(e=>typeof e==`string`)?n.forEach((n,r)=>tf(e,t,s,`${o}.${u}[${r}]`,n)):t(`${o}.${u} must be [ref, ref] (two point refs), got ${Z(n)}`)}r.tol!==void 0&&(l.length===1&&!rC.has(u)?t(`${o}.tol applies to near and still; ${aC(u,r.tol)}`):Number.isFinite(r.tol)&&r.tol>=0||t(`${o}.tol must be a number >= 0 (metres), got ${Z(r.tol)}`)),r.by===void 0?u===`speed`&&l.length===1&&t(`${o}.speed needs by: the speed the point must reach, in m/s (e.g. by: 2)`):l.length===1&&!iC.has(u)?t(`${o}.by applies to above, moved and speed; ${u} takes tol`):(!Number.isFinite(r.by)||u===`moved`&&r.by<0||u===`speed`&&r.by<=0)&&t(`${o}.by must be a ${u===`moved`?`number >= 0 (metres)`:u===`speed`?`number > 0 (m/s)`:`finite number (metres)`}, got ${Z(r.by)}`),r.mode!==void 0&&r.mode!==`all`&&r.mode!==`any`&&t(`${o}.mode must be "all" or "any", got ${Z(r.mode)}`),lC(t,o,r.at,n.frames,n.past)}function fC(e,t){let n=new Map(e.map((e,t)=>[e&&typeof e==`object`?FS(e,t):`goals[${t}]`,t])),r=e.map((e,r)=>[`after`,`before`].flatMap(i=>{if(!e||typeof e!=`object`||e[i]===void 0)return[];let a=n.get(e[i]);return typeof e[i]!=`string`||a===void 0?(t(`goals[${r}].${i} must name another goal (its name, or goals[<i>] when it has none), got ${Z(e[i])}${typeof e[i]==`string`?il(e[i],[...n.keys()]):``}`),[]):a===r?(t(`goals[${r}].${i} names the goal itself; name the goal whose first met frame this one waits for`),[]):[a]})),i=e.map(()=>0),a=[],o=n=>{if(i[n]!==2){if(i[n]===1){let r=a.slice(a.indexOf(n)).map(t=>`"${FS(e[t],t)}"`);return t(`goals wait on each other through after/before: ${[...r,r[0]].join(` -> `)}; one of them must not wait`)}i[n]=1,a.push(n);for(let e of r[n])o(e);a.pop(),i[n]=2}};e.forEach((e,t)=>o(t))}function pC(e,t,n){if(e.goals===void 0)return;if(!Array.isArray(e.goals))return t(`spec.goals must be an array of goals ${nC}, got ${Z(e.goals)}`);let r=new Map;e.goals.forEach((i,a)=>dC(e,t,n,i,a,r)),fC(e.goals,t)}var mC=new Set([`l`,`r`]),hC=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function gC(e,t,n,r){if(hC(n))for(let i of Object.keys(n))r.includes(i)||e(`${t} has unknown field "${i}"${tl(i,r)} (fields: ${r.join(`, `)})`)}function _C(e,t,{sk:n,scene:r,unknown:i=t}){for(let[a,o]of Object.entries(e.anchors??{})){let s=`anchors.${a}`;if(/_[lr]$/.test(a)&&t(`${s}: an anchor name may not end in _l or _r (the weight channel w_${a}_l would read as anchor "${a.slice(0,-2)}"); the side goes on the weight channel, so name it "${a.slice(0,-2)}"`),!o||!bl[o.kind]){t(`${s}.kind must be one of ${Object.keys(bl).join(`, `)}, got ${Z(o?.kind)}`);continue}gC(i,`${s} (${o.kind})`,o,[`kind`,...bl[o.kind]]);for(let e of[`p`,`offset`,`local`])o[e]!==void 0&&!nl(o[e])&&t(`${s}.${e} must be [x, y, z], got ${Z(o[e])}`);(o.kind===`world`||o.kind===`body`)&&o.p===void 0&&t(`${s} (${o.kind}) needs p: [x, y, z]${o.kind===`body`?`, ${Zc.pole}`:``}`),o.kind===`bone`&&Vl(t,n,s,o.bone),o.kind===`segment`&&(Vl(t,n,`${s}.from`,o.from),Vl(t,n,`${s}.to`,o.to),o.reach!==void 0&&!mC.has(o.reach)&&t(`${s}.reach must be "l" or "r"`)),o.kind===`object`&&Hl(t,r,s,o.object,{groups:!0})&&(o.grasp!==void 0&&!Kc.includes(o.grasp)&&t(`${s}.grasp must be one of ${Kc.join(`, `)}, got ${Z(o.grasp)}`),o.socket!==void 0&&r?.objects&&!Td(r,o.object,o.socket)&&t(`${s}.socket: "${o.object}" has no socket ${Z(o.socket)} (sockets: ${wd(r,o.object).map(e=>e.name).join(`, `)||`none`})`),o.socket!==void 0&&o.grasp===void 0&&t(`${s}.socket needs grasp (${Kc.join(`, `)}): the socket says how the hand takes it`)),o.kind===`person`&&!hd(r,o.person,o.bone??``,0)&&t(`${s} (person) needs person: the id of another character with an installed take (people: ${gd(r)}) and bone: one of its joints, got ${Z(o.person)} ${Z(o.bone)}`),o.kind===`landmark`&&o.name!==`mouth`&&t(`${s}: the only landmark is "mouth", got ${Z(o.name)}`),o.kind===`prop`&&!e.props?.[o.prop]?.points?.[o.point]&&o.point!==`origin`&&t(`${s} needs prop point ${o.prop}.${o.point}, which spec.props does not define`)}}function vC(e,t,{sk:n,unknown:r=t}){for(let[i,a]of Object.entries(e.props??{})){let e=`props.${i}`;gC(r,e,a,xl),mC.has(a?.hand)||t(`${e}.hand must be "l" or "r", got ${Z(a?.hand)}`),!Array.isArray(a?.origin)||!a.origin.length?t(`${e}.origin must list one or more bones`):a.origin.forEach(r=>Vl(t,n,`${e}.origin`,r));for(let[n,r]of Object.entries(a?.points??{}))nl(r)||t(`${e}.points.${n} must be [d, l, n] along the palm axes, got ${Z(r)}`)}(e.fits??[]).forEach((i,a)=>{let o=`fits[${a}]`;gC(r,o,i,Sl),mC.has(i?.side)||t(`${o}.side must be "l" or "r", got ${Z(i?.side)}`),e.anchors?.[i?.anchor]||t(`${o}.anchor "${i?.anchor}" is not in spec.anchors${il(String(i?.anchor),Object.keys(e.anchors??{}))}`);let s=i?.effector;if(s?.prop!==void 0){let n=e.props?.[s.prop];n?s.point!==`origin`&&!n.points?.[s.point]&&t(`${o}.effector ${s.prop}.${s.point} is not a point of spec.props.${s.prop} (points: ${[...Object.keys(n.points??{}),`origin`].join(`, `)})`):t(`${o}.effector.prop "${s.prop}" is not in spec.props${il(String(s.prop),Object.keys(e.props??{}))}`)}else Array.isArray(s?.joints)?s.joints.forEach(e=>Vl(t,n,`${o}.effector`,e)):t(`${o}.effector must be { prop, point } or { joints: [bone, ...] }`);i?.offset!==void 0&&!nl(i.offset)&&t(`${o}.offset must be [x, y, z]`),i?.orient!==void 0&&typeof i.orient!=`boolean`&&t(`${o}.orient must be true or false (false: the hand takes no grip turn), got ${Z(i.orient)}`)})}function yC(e,t,{frames:n,unknown:r=t,past:i=``}){(e.generators??[]).forEach((e,a)=>{let o=`generators[${a}]`;if(e?.type!==`walk`)return t(`${o}.type must be "walk", got ${Z(e?.type)}`);gC(r,o,e,Dl),(!Number.isInteger(e.f0)||e.f0<0||e.f0>n-1)&&t(`${o}.f0 must be an integer frame within 0..${n-1}, got ${Z(e.f0)}${e.f0>n-1?i:``}`),e.heading!==void 0&&!(Array.isArray(e.heading)&&e.heading.length===2&&e.heading.every(Number.isFinite))&&t(`${o}.heading must be [h0, h1] in degrees (${Zc.yaw}), got ${Z(e.heading)}`);for(let n of Dl.slice(2))n!==`heading`&&e[n]!==void 0&&!Number.isFinite(e[n])&&t(`${o}.${n} must be a finite number, got ${Z(e[n])}`);e.steps!==void 0&&!(Number.isInteger(e.steps)&&e.steps>=1)&&t(`${o}.steps must be an integer >= 1, got ${Z(e.steps)}`),e.turnDistance!==void 0&&!(e.turnDistance>0)&&t(`${o}.turnDistance must be > 0 m, got ${Z(e.turnDistance)}`)})}function bC(e,t,{sk:n,scene:r,frames:i,unknown:a=t,past:o=``}){let s=e.checks??{};for(let e of Object.keys(s))Ol.includes(e)||a(`checks.${e} is not a check${il(e,Ol)} (checks: ${Ol.join(`, `)})`);let c=(e,n=()=>{})=>{let r=s[e],i=`{ ${kl[e].join(`, `)} }`;if(r!==void 0){if(!Array.isArray(r))return t(`checks.${e} must be an array of ${i}, got ${Z(r)}`);r.forEach((r,o)=>{if(!hC(r))return t(`checks.${e}[${o}] must be ${i}, got ${Z(r)}`);gC(a,`checks.${e}[${o}]`,r,kl[e]),n(r,o)})}},l=(e,n)=>{n!==void 0&&typeof n!=`string`&&(Array.isArray(n)&&n.length===2&&n.every(Number.isInteger)&&n[0]<=n[1]&&n[0]>=0&&n[1]<=i-1||t(`${e}.when must be a weight channel or [f0, f1] within 0..${i-1}, got ${Z(n)}${Array.isArray(n)&&n[1]>i-1?o:``}`))};c(`contacts`,(r,i)=>{Ul(e,t,n,`checks.contacts[${i}].point`,r.point),Ul(e,t,n,`checks.contacts[${i}].target`,r.target),l(`checks.contacts[${i}]`,r.when)}),c(`orient`,(r,i)=>{Ul(e,t,n,`checks.orient[${i}].from`,r.from),Ul(e,t,n,`checks.orient[${i}].to`,r.to),l(`checks.orient[${i}]`,r.when),r.along===`face`||r.along===`up`||nl(r.along)||t(`checks.orient[${i}].along must be "face", "up" or [x, y, z]`)}),c(`below`,(e,r)=>{Vl(t,n,`checks.below[${r}].joint`,e.joint),Vl(t,n,`checks.below[${r}].ref`,e.ref),l(`checks.below[${r}]`,e.when)}),c(`clearance`,(e,n)=>{Hl(t,r,`checks.clearance[${n}]`,e.object),l(`checks.clearance[${n}]`,e.frames)}),c(`appear`,(r,i)=>{Vl(t,n,`checks.appear[${i}].joint`,r.joint),e.anchors?.[r.anchor]||t(`checks.appear[${i}].anchor "${r.anchor}" is not in spec.anchors`)}),c(`supports`,(e,n)=>Hl(t,r,`checks.supports[${n}]`,e.object)),c(`allow`);for(let e of Object.keys(s.limits??{}))e in rd||a(`checks.limits.${e} is not a QA limit${il(e,Object.keys(rd))}`);let u=e.fix;if(u!==void 0&&u!==!1&&(typeof u!=`object`||!u))t(`spec.fix must be false or { ${kx.join(`, `)} }`);else for(let e of Object.keys(u||{}))kx.includes(e)||a(`spec.fix.${e} is not a fix${il(e,kx)} (fixes: ${kx.join(`, `)})`);u&&u.grasp!==void 0&&typeof u.grasp!=`boolean`&&t(`spec.fix.grasp must be true (fingers close on what a hand holds, the default) or false (the preset grip, the object at its grab-frame offset), got ${Z(u.grasp)}`),u&&u.person!==void 0&&typeof u.person!=`boolean`&&t(`spec.fix.person must be true (arms kept out of the other characters, the default) or false, got ${Z(u.person)}`)}function xC(e,t,n){_C(e,t,n),vC(e,t,n),OS(e,t,n),yC(e,t,n),bC(e,t,n),pC(e,t,n)}var SC=12,CC=60;function wC(e){let t=new Map;for(let n of e){let e=/\[(\d+)\]( \(f(\d+)\))?/.exec(n),r=e?`${n.slice(0,e.index)}[#]${e[2]?` (f#)`:``}${n.slice(e.index+e[0].length)}`:n;t.has(r)||t.set(r,{line:n,idx:[],fs:[]}),e&&(t.get(r).idx.push(e[1]),e[3]&&t.get(r).fs.push(`f${e[3]}`))}return[...t.entries()].map(([e,t])=>t.idx.length>1?e.replace(`[#]`,`[${t.idx.join(`,`)}]`).replace(` (f#)`,` (${t.fs.join(`, `)})`):t.line)}function TC(e){let t=new Set(e.channels??[]);for(let n of Object.values(e.objects??{}))for(let e of[n?.channel,n?.visible,n?.level])typeof e==`string`&&e&&t.add(e);let n=e.checks??{},r=e=>Array.isArray(e)?e.filter(e=>e&&typeof e==`object`):[];for(let e of[n.contacts,n.orient,n.below,n.clearance].flatMap(r))typeof e.when==`string`&&t.add(e.when);for(let e of r(n.appear))typeof e.channel==`string`&&t.add(e.channel);return t}function EC(e,t,n,r){if(Bc.has(n)){if(!nl(r))return e(`${t} ${n} must be [x, y, z] (3 finite numbers), got ${Z(r)}`);if(Vc.has(n)){let i=Math.hypot(...r);if(i<1e-6)return e(`${t} ${n} = ${Z(r)} has no direction; a pole is a ${Zc.pole}`);n.startsWith(`knee`)&&r[2]<-.7*i&&e(`${t} ${n} = ${Z(r)} points backward; knees bend toward +z. A pole is a ${Zc.pole}`)}n.startsWith(`foot`)&&r[1]<.04&&e(`${t} ${n} y = ${r[1]} puts the ankle into the floor; foot_* is the ${Zc.foot}`);return}if(Uc.has(n)){if(!r||typeof r!=`object`||Array.isArray(r))return e(`${t} ${n} must be { preset: weight }, presets ${Gc.join(`, `)}; got ${Z(r)}`);for(let[i,a]of Object.entries(r))Gc.includes(i)?Number.isFinite(a)&&a>=0&&a<=1||e(`${t} ${n}.${i} must be a weight within 0..1, got ${Z(a)}`):e(`${t} ${n} preset "${i}" is unknown${il(i,Gc)} (presets: ${Gc.join(`, `)})`);return}if(!Number.isFinite(r))return e(`${t} ${n} must be a finite number${n===`yaw`?` (degrees; ${Zc.yaw})`:n.startsWith(`fyaw`)?` (${Zc.fyaw})`:``}, got ${Z(r)}`);let i=Xc(n);i&&(r<i[1]||r>i[2])&&e(`${t} ${n} = ${r} is outside ${i[1]}..${i[2]} (${i[3]})`)}var DC=e=>Array.isArray(e)?e:[],OC=e=>Array.isArray(e)?e[1]:e;function kC(e,t){let n=[...DC(e.keys).map(e=>e?.f),...DC(e.generators).map(e=>e?.f0)].filter(Number.isInteger),r=e.checks??{},i=[...[`contacts`,`orient`,`below`].flatMap(e=>DC(r[e]).map(e=>OC(e?.when))),...DC(r.clearance).map(e=>OC(e?.frames)),...DC(e.goals).map(e=>OC(e?.at))].filter(Number.isInteger),a=Math.max(t-1,...n,...i)+1;return`; set frames >= ${a}${Math.max(0,...n)+1>=a?` or frames: "auto"`:``}`}function AC(e,t,n,r,i=``){if(e.keys!==void 0&&!Array.isArray(e.keys))return t(`spec.keys must be an array of { f, set, step? }`);let a=Object.keys(e.anchors??{}),o=TC(e),s=[...Bc,...Hc,...Uc,...o,...a.flatMap(e=>[`w_${e}_l`,`w_${e}_r`])];(e.keys??[]).forEach((e,c)=>{let l=e?.src?e.src.startsWith(`keys[`)?e.src:`${e.src} key`:`keys[${c}]`;if(!e||typeof e!=`object`)return t(`${l} must be { f, set, step? }`);for(let t of Object.keys(e))vl.includes(t)||r(`${l} has unknown field "${t}"${tl(t,vl)}; a key is { f, set, step? }`);if(!Number.isInteger(e.f))return t(`${l}.f must be an integer frame, got ${Z(e.f)}`);(e.f<0||e.f>n-1)&&t(`${l}.f = ${e.f} is outside 0..${n-1} (spec.frames ${n})${e.f>0?i:``}`);let u=`${l} (f${e.f})`;if(!e.set||typeof e.set!=`object`||Array.isArray(e.set))return t(`${u} needs set: { channel: value }`);for(let[n,r]of Object.entries(e.set)){let e=/^w_(.+)_([lr])$/.exec(n);e&&!a.includes(e[1])?t(`${u} sets ${n}, but there is no anchor "${e[1]}"${il(n,s)}`):e||Bc.has(n)||Hc.has(n)||Uc.has(n)?EC(t,u,n,r):o.has(n)||n.endsWith(`_vis`)?Number.isFinite(r)||t(`${u} ${n} must be a finite number, got ${Z(r)}`):t(`${u} sets unknown channel "${n}"${il(n,s)}`)}for(let n of e.step??[])n in e.set||t(`${u} step names "${n}", which this key does not set`);e.step!==void 0&&!Array.isArray(e.step)&&t(`${u} step must be an array of channel names`)})}function jC(e,t,n){if(e===void 0||e===!1)return;if(!e||typeof e!=`object`||Array.isArray(e))return t(`spec.flow must be false or { smooth?, lag?, overlap?, headLead? }, got ${Z(e)}`);for(let t of Object.keys(e))[`smooth`,`lag`,`overlap`,`headLead`].includes(t)||n(`spec.flow has unknown field "${t}" (fields: smooth, lag, overlap, headLead)`);e.smooth!==void 0&&typeof e.smooth!=`boolean`&&t(`spec.flow.smooth must be true or false, got ${Z(e.smooth)}`);let r=e.overlap;r!==void 0&&typeof r!=`boolean`&&!(Number.isFinite(r)&&r>=0&&r<=2)&&t(`spec.flow.overlap must be true, false or a scale 0..2, got ${Z(r)}`);let i=e.headLead;i!==void 0&&typeof i!=`boolean`&&!(Number.isInteger(i)&&i>=0&&i<=12)&&t(`spec.flow.headLead must be true, false or 0..12 whole frames, got ${Z(i)}`);let a=e=>Number.isFinite(e)&&e>=0&&e<=6,o=e.lag;if(!(o===void 0||o===!1||a(o))){if(!o||typeof o!=`object`||Array.isArray(o))return t(`spec.flow.lag must be false, 0..6 frames or { spine?, head?, arms? }, got ${Z(o)}`);for(let[e,r]of Object.entries(o))[`spine`,`head`,`arms`].includes(e)?a(r)||t(`spec.flow.lag.${e} must be 0..6 frames, got ${Z(r)}`):n(`spec.flow.lag has unknown field "${e}" (fields: spine, head, arms)`)}}function MC(e,{sk:t,scene:n,lenient:r=!1,problems:i=[]}={}){let a=[...i],o=e=>{a.length<CC&&a.push(e)},s=r?()=>{}:o;if(!e||typeof e!=`object`)throw Error(`MOTION_SPEC_INVALID: spec must be an object`);e.schema!==`cozyclay.motion-spec.v1`&&o(`spec.schema must be "cozyclay.motion-spec.v1", got ${Z(e.schema)}`);for(let t of Object.keys(e))_l.includes(t)||s(`spec.${t} is not a spec field${il(t,_l)} (fields: ${_l.join(`, `)})`);e.fps!==void 0&&e.fps!==24&&o(`spec.fps must be 24, the timeline rate, got ${Z(e.fps)}`),jC(e.flow,o,s);let c=e.frames;(!Number.isInteger(c)||c<1||c>2e4)&&o(`spec.frames must be an integer 1..20000 or "auto", got ${Z(c)}`);let l=Number.isInteger(c)?kC(e,c):``;if(AC(e,o,Number.isInteger(c)?c:2e4,s,l),xC(e,o,{sk:t,scene:n,frames:Number.isInteger(c)?c:2e4,lenient:r,unknown:s,past:l}),!a.length)return;let u=wC(a),d=u.length>SC||a.length>=CC;throw Error(`MOTION_SPEC_INVALID: ${u.slice(0,SC).join(`
|
|
7
|
+
`)}${d?`\n(${u.length>SC?`${u.length-SC}`:`more`}${a.length>=CC?`+`:``} more problems not listed)`:``}`)}function NC(e,t,n){let{s:r,diag:i,c:a}=e.frames[t],[o,s]=n.split(/:(.*)/s);if(o===`joint`)return r.P[e.ctx.sk.index[s]];if(o===`prop`){let[e,t]=s.split(`.`);return i.props?.[e]?.[t]??null}if(o===`anchor`)return Fd(e.ctx,s,r,i,a);throw Error(`MOTION_SPEC_INVALID: check point "${n}"`)}function PC(e,t,n){let r=/^prop:([^.]+)\./.exec(t)?.[1],i=e.ctx.spec.props?.[r]?.hand,{spec:a,scene:o}=e.ctx;return i?Object.keys(a.objects??{}).find(t=>ul(a,a.objects[t],o,t)&&Og(e,t,n)===i)??null:null}function FC(e,t){let[n,r]=t.split(/:(.*)/s),i=n===`anchor`?e.ctx.spec.anchors?.[r]:null;return i?.kind!==`object`||!i.grasp?null:e.ctx.sockets?.get(r)?.owner??i.object}var IC=(e,t,n)=>Array.isArray(n)?t+(e.f0??0)>=n[0]&&t+(e.f0??0)<=n[1]:!n||(e.frames[t].c[n]??0)>.99;function LC(e,t,n){return n===`up`?[0,1,0]:n===`face`?Lo(e.ctx.sk,e.frames[t].s,e.ctx.sk.index.Head,[0,0,1]):K(n)}function RC(e,t,n){let r=NC(e,t,n.point),i=NC(e,t,n.target);if(!r||!i)return null;let a=FC(e,n.target)??PC(e,n.point,t+(e.f0??0));return a?Qd(e,t,n.point,`object:${a}`)??G(H(r,i)):G(H(r,i))}function zC(e,t={}){let n=[],r=e.frames.length,i=e.ctx.sk.index,a=(e,t,r,i,a)=>n.push({kind:e,msg:t,frame:r,value:+i.toFixed(4),limit:a});for(let n=0;n<r;n++){for(let r of t.contacts??[])if(IC(e,n,r.when)){let t=RC(e,n,r);t!==null&&t>(r.tol??.01)&&a(`CONTACT`,`${r.name}: ${(t*100).toFixed(1)} cm apart`,n,t,r.tol??.01)}for(let r of t.orient??[])if(IC(e,n,r.when)){let t=NC(e,n,r.from),i=NC(e,n,r.to);if(!t||!i)continue;let o=W(K(H(i,t)),LC(e,n,r.along));o<(r.minCos??.64)&&a(`ORIENT`,`${r.name}: cos ${o.toFixed(2)}`,n,o,r.minCos??.64)}for(let r of t.below??[])if(IC(e,n,r.when)){let{P:t}=e.frames[n].s,o=t[i[r.ref]][1]-t[i[r.joint]][1];o<(r.min??.08)&&a(`BELOW`,`${r.name}: ${r.joint} only ${(o*100).toFixed(1)} cm below ${r.ref}`,n,o,r.min??.08)}for(let r of t.clearance??[])if(IC(e,n,r.frames)){let t=e.objectsAt(n)[r.object],o=Sc.find(e=>e[0]===r.part);if(!t||!o)continue;let{P:s}=e.frames[n].s,c=Math.min(...Cc(s[i[o[1]]],s[i[o[2]]]).map(e=>wc(e,t)))-o[3];c<r.min&&a(`CLEARANCE`,`${r.name}: ${(c*100).toFixed(1)} cm`,n,c,r.min)}}for(let n of t.appear??[])for(let t=1;t<r;t++){if((e.frames[t-1].c[n.channel]??0)>.5==(e.frames[t].c[n.channel]??0)>.5)continue;let r=G(H(NC(e,t,`joint:${n.joint}`),NC(e,t,`anchor:${n.anchor}`)));r>(n.tol??.035)&&a(`APPEAR`,`${n.name}: switches with the hand ${(r*100).toFixed(1)} cm from ${n.anchor}`,t,r,n.tol??.035)}return n}var BC=/^(.+): [\d.]+ cm off its keys$/,VC={twist:`twist about the forearm`,flex:`flex`,dev:`deviation (+ toward the thumb)`};function HC(e,t){let n=e.objects[t]??Jl(e)[t];return sg(e,t).flatMap(t=>{let r=e.objects[t],i=O_(n,r),[a,o,s]=r.half;return[-a,a].flatMap(e=>[0,2*o].flatMap(t=>[-s,s].map(n=>V(i.pos,J(i.R,[e,t,n])))))})}function UC(e,t,n){let{scene:r}=e.ctx,i=e.f0??0;for(let[a]of Vm(e.ctx.spec)){let o=Rm(e,a),s=HC(r,a);if(s.length)for(let r=Math.max(i,Math.ceil(o.t[0]));r<=Math.min(i+e.frames.length-1,Math.floor(o.t[o.t.length-1]));r++){let c=zm(o,r),l=Eg(e,a,r),u=Math.max(...s.map(e=>go(V(c.pos,J(c.R,e)),V(l.pos,J(l.R,e)))));u>t.reach&&n(`REACH`,`${a}: ${(u*100).toFixed(1)} cm off its keys`,r-i,u,t.reach)}}}function WC(e,t){let n=BC.exec(t.subject)?.[1],r=e.spec?.objects?.[n];if(!r?.keys?.length)return null;let i=t.worstFrame,a=e.spec.props?.[r.prop]?.hand,o=e.fr(i).diag[`hold_${a}`]??{},s=r.keys.reduce((e,t,n)=>Math.abs(t.f-i)<Math.abs(r.keys[e].f-i)?n:e,0),c=Object.entries(Us).filter(([e,[t,n]])=>o[e]<t||o[e]>n).map(([e,[t,n]])=>`the wrist ${VC[e]} needs ${Math.round(o[e])}deg (limit ${t}..${n})`);c.length&&(c[c.length-1]+=` after the elbow swung ${Math.round(o.swivel??0)}deg and the forearm turned`);let l=o.miss>.005&&o.fold,u=l?`the grip is ${(o.miss*100).toFixed(1)} cm inside the forearm's reach (the elbow would fold ${Math.round(o.fold)}deg; it bends to 145deg and stops at 150deg)`:`the arm is ${(o.miss*100).toFixed(1)} cm short`,d=[...o.miss>.005?[u]:[],...c],f=r.keys[s].aim&&r.keys[s].roll===void 0?``:`; an aim key without roll takes the roll the arm holds most easily`;return{cause:`objects.${n}.keys[${s}] f${r.keys[s].f}`,hint:`${n} at f${i}: ${d.length?d.join(`, `):`the hand cannot hold it there`}; ${l?`key a pose farther from the shoulder, or turn or move the body away from it`:`key a pose nearer the hand, or bring the body to it`} (root, yaw, spine_yaw)${f}`}}var GC=e=>Math.round(e*10)/10,KC=e=>Math.round(e*100)/100,qC=`held: per key, deg = the drawn +Y off the asked one (aim, or rot's +Y), cm = the drawn base off pos, got = the drawn +Y (when 1 deg off or more), rot = what an aim key used, lean = the lean a mouth key took by default (give lean 0 to hold aim exactly)`;function JC(e){let t=Vm(e.ctx.spec);return t.length?Object.fromEntries(t.map(([t,n])=>{let r=Rm(e,t);return[t,[...(e.ctx.hold?.entry?.(t)??n).keys].sort((e,t)=>e.f-t.f).map((n,i)=>{let a=Eg(e,t,Math.round(r.t[i])),o=[a.R[0][1],a.R[1][1],a.R[2][1]],s=GC(ko(n.aim?K(n.aim):J(Oo(r.q[i]),[0,1,0]),o));return{f:n.f,deg:s,cm:GC(go(n.pos,a.pos)*100),...s>=1?{got:o.map(KC)}:{},...n.aim?{rot:r.rots[i]}:{},...n.leaned?{lean:n.lean}:{}}})]})):null}var YC=3,XC=.03,ZC=e=>V(e.pos,J(e.R,[0,e.half[1],0])),QC=(e,t)=>[e[0][t],e[1][t],e[2][t]];function $C(e,t,n=null){let r=H(ZC(e),ZC(t)),i=[0,1,2].map(t=>QC(e.R,t)),a=[0,1,2].map(e=>QC(t.R,e)),o=[...i,...a,...i.flatMap(e=>a.map(t=>ho(e,t)))],s={depth:1/0,axis:[0,1,0]};for(let c of o){if(G(c)<1e-6)continue;let o=K(c),l=(e,t)=>t.reduce((t,n,r)=>t+Math.abs(W(n,o))*e.half[r],0),u=l(e,i)+l(t,a);if(u-Math.abs(W(r,o))<=0)return{depth:u-Math.abs(W(r,o)),axis:o};let d=W(n??r,o)<0?U(o,-1):o,f=u-W(r,d);f<s.depth&&(s={depth:f,axis:d})}return s}var ew=(e,t,n,r)=>{let i=n===`l`?`Left`:`Right`,a=U(V(t.P[e.index[`${i}HandIndex2`]],t.P[e.index[`${i}HandMiddle2`]]),.5);return r.some(e=>wc(a,e)<=0)},tw=(e,t,n)=>!t.visible||(e.baked?.[t.visible]?.[n]??0)>.5,nw=(e,t,n)=>sg(e.ctx.scene,t).map(t=>({...e.ctx.scene.objects[t],..._g(e,t,n)}));function rw(e,t,n){let{sk:r,spec:i}=e.ctx,a=e.frames[n-(e.f0??0)];if(!a)return null;let o=w_(r,i,a.s,i.objects[t]);return Math.max(0,Math.min(...nw(e,t,n).map(e=>wc(o,e))))}function iw(e,t,n){let r=nw(e,t,n);if(!r.length)return null;let i=Math.min(...r.map(e=>e.pos[1]-Math.abs(e.R[1][0])*e.half[0]-Math.abs(e.R[1][2])*e.half[2])),a=U(r.map(ZC).reduce((e,t)=>V(e,t),[0,0,0]),1/r.length),o=[a[0],i-.01,a[2]],s=null;for(let[t,r]of Object.entries(e.ctx.objectsAt(n))){if(r.carried||!r.half)continue;let e=wc(o,r);e<=.02&&(!s||e<s[1])&&(s=[t,e])}return s?.[0]??null}function aw(e,t,n){let r=Object.entries(t.ctx.spec.objects??{}).filter(([,e])=>b_(e));if(!r.length)return[];let i=n.checks??{},a={...rd,...i.limits},o=i.allow,s=[],c=t.f0??0,l=e.index,u=(e,t,n,r,i)=>s.push({kind:e,msg:t,frame:n,value:+r.toFixed(4),limit:i}),d=(e,t)=>e.reduce((e,n)=>t.reduce((e,t)=>e??od(o,n,t),e),null)??a.allow;for(let[i,o]of r){let[r,s]=dg(t,o),f=n.props?.[o.prop]?.hand,p=new Set([`hand_${f}`,`farm_${f}`]);if(o.grab!==void 0&&r>0&&t.frames[r-c]&&tw(t,o,r-1)){let e=rw(t,i,r),n=[o.fall??[]].flat().some(e=>Array.isArray(e.v)&&e.at<r);n&&e>XC?u(`CATCH`,`${i} missed by ${(e*100).toFixed(1)} cm`,r-c,e,XC):!n&&e>a.grab&&u(`GRAB`,`${i}: hand ${(e*100).toFixed(1)} cm from it at grab`,r-c,e,a.grab)}let m=o.grab===void 0?null:iw(t,i,r),h=e=>Math.abs(e-r)<=YC||o.release!==void 0&&Math.abs(e-s)<=YC;for(let n=0;n<t.frames.length;n++){let a=n+c,s=Dg(t,i,a);if(!s||!tw(t,o,a))continue;let f=s.map(e=>e.id),g=s.map(e=>[e,ZC(e),G(e.half)]),{s:_}=t.frames[n],v=Object.entries(t.frames[n].diag).filter(([t,n])=>/^hold_[lr]$/.test(t)&&n?.second===i&&(n.w>=.5||ew(e,_,t.slice(-1),s))).map(([e])=>`hand_${e.slice(-1)}`);for(let[e,t,r,a]of Sc){if(p.has(e)||v.includes(e))continue;let o=_.P[l[t]],s=_.P[l[r]],c=U(V(o,s),.5),m=a+go(o,s)/2,h=d([e],[i,...f]),y=null,b=-1/0;for(let[e,t,n]of g)m-(go(c,t)-n)<=h||(y??=Cc(o,s),b=Math.max(b,a-Math.min(...y.map(t=>wc(t,e)))));b>h&&u(`COLLIDE`,`${e} x ${i}`,n,b,h)}if(!(a<r))for(let[e,r]of Object.entries(t.objectsAt(n))){if(!r.half||r.ignore||e===m&&h(a))continue;let t=d([i,...f],[e]),o=ZC(r),s=G(r.half),c=-1/0;for(let[e,n,i]of g)go(n,o)<i+s+t&&(c=Math.max(c,$C(e,r).depth));c>t&&u(`COLLIDE`,`${i} x ${e}`,n,c,t)}}}return UC(t,a,u),s}var ow=.009,sw=.022,cw=.004,lw=.008,uw=.995,dw=.01,fw=120,pw=150,mw=-.3,hw=[`Index`,`Middle`,`Ring`,`Pinky`],gw={l:`Left`,r:`Right`};function _w(e,t){let n=sg(e,t),r=n.length===1?Mc(e.objects[n[0]]).kind:`box`;return r===`sphere`?`spherical`:r===`cylinder`?`power`:null}function vw(e){let{spec:t,scene:n}=e.ctx,r=[],i=t.fix?.grasp===!1?{...t,fix:{...t.fix,grasp:!0}}:t;for(let[t,a]of Object.entries(i.objects??{})){if(!b_(a)||!ul(i,a,n,t))continue;let o=i.props?.[a.prop]?.hand,[s,c]=dg(e,a);o&&r.push({id:t,k:o,grasp:a.grasp??_w(n,t),from:s+4+1,to:c})}for(let t of i.fits??[]){let n=i.anchors?.[t.anchor];if(n?.kind!==`object`||!n.grasp||e.ctx.sockets?.get(t.anchor)?.rim)continue;let a=`w_${t.anchor}_${t.side}`,o=e.f0??0,s=e.baked?.[`fingers_${t.side}`],c=e=>Object.entries(s?.[e]??{}).reduce((e,[t,n])=>e+(t===`relaxed`?0:n||0),0);r.push({id:n.object,k:t.side,grasp:n.grasp,from:o,to:o+e.frames.length-1,held:t=>(e.baked?.[a]?.[t]??0)>=uw&&c(t)>=uw,rests:!0})}return r}var yw=(e,t,n)=>sg(e.ctx.scene,t).map(t=>({...e.ctx.scene.objects[t],...kg(e,t,n)}));function bw(e,t,n){let r=gw[n],i=n=>t.P[e.index[`${r}Hand${n}`]],a=[{bone:`${r}Hand`,finger:`palm`,a:t.P[e.index[`${r}Hand`]],b:i(`Middle1`),r:sw}];for(let e of[...hw,`Thumb`])for(let t=1;t<=3;t++)a.push({bone:`${r}Hand${e}${t}`,finger:e,tip:t===3,a:i(`${e}${t}`),b:i(`${e}${t+1}`),r:ow});return a}function xw(e,t){return e.map(e=>{let n={depth:-1/0};for(let r of t){let t=Rc(r,e.a,e.b,e.r);t>n.depth&&(n={depth:t,entry:r})}let r=U(V(e.a,e.b),.5),i=n.entry&&Lc(n.entry,r);return{...e,depth:n.depth,at:i,normal:n.entry&&Ic(n.entry,r)}})}function Sw(e,t){if(!t.length)return 1/0;let n=[e[0],e[2]],r=t.map(e=>[e[0],e[2]]),i=(e,t)=>{let r=[t[0]-e[0],t[1]-e[1]],i=Math.max(0,Math.min(1,((n[0]-e[0])*r[0]+(n[1]-e[1])*r[1])/(r[0]**2+r[1]**2||1)));return Math.hypot(n[0]-e[0]-i*r[0],n[1]-e[1]-i*r[1])},a=Cw(r);return a.length>=3&&a.every((e,t)=>{let r=a[(t+1)%a.length];return(r[0]-e[0])*(n[1]-e[1])-(r[1]-e[1])*(n[0]-e[0])>=0})?0:Math.min(...a.map((e,t)=>i(e,a[(t+1)%a.length])))}function Cw(e){let t=[...e].sort((e,t)=>e[0]-t[0]||e[1]-t[1]),n=(e,t,n)=>(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0]);if(t.length<3)return t;let r=[],i=[];for(let e of t){for(;r.length>=2&&n(r.at(-2),r.at(-1),e)<=0;)r.pop();r.push(e)}for(let e of t.reverse()){for(;i.length>=2&&n(i.at(-2),i.at(-1),e)<=0;)i.pop();i.push(e)}return[...r.slice(0,-1),...i.slice(0,-1)]}function ww(e,t,n,r,i,a){let o=xw(bw(e,t,n.k),r),s=gw[n.k].toLowerCase();if(n.rests&&o[0].depth<-.03)return;for(let e of o)e.finger!==`palm`&&e.depth>cw&&i(`FINGER_PEN`,`${e.bone} into ${n.id}`,a,e.depth,cw);let c=e=>o.some(t=>t.finger===e&&t.tip&&t.depth>=-.008),l=hw.filter(c).length,u=c(`Thumb`);(n.grasp===`pinch`?u&&c(`Index`):l>=3||u&&l>=2)?!u&&(n.grasp===`power`||n.grasp===`spherical`)&&i(`THUMB_OFF`,`${s} thumb off ${n.id}`,a,-Math.max(...o.filter(e=>e.finger===`Thumb`&&e.tip).map(e=>e.depth)),lw):i(`FINGER_GAP`,`${s} fingers off ${n.id}`,a,l+ +!!u,n.grasp===`pinch`?2:3);let d=o.filter(e=>e.depth>=-.008&&e.normal),f=U(r.reduce((e,t)=>V(e,V(t.pos,J(t.R,[0,t.half[1],0]))),[0,0,0]),1/r.length),p=d.filter(e=>e.normal[1]<=mw).map(e=>e.at),m=d.filter(e=>e.finger===`Thumb`).map(e=>e.normal),h=d.filter(e=>hw.includes(e.finger)).map(e=>e.normal),g=e=>e.length?K(e.reduce(V,[0,0,0])):null,_=g(m),v=g(h),y=_&&v&&Math.acos(Math.max(-1,Math.min(1,W(_,v))))*180/Math.PI>=fw,b=(e,t)=>Math.acos(Math.max(-1,Math.min(1,W(e,t))))*180/Math.PI,x=d.some((e,t)=>d.slice(t+1).some(t=>b(e.normal,t.normal)>=pw));!n.rests&&!y&&!x&&Sw(f,p)>dw&&i(`SUPPORT`,`${n.id} not supported`,a,Math.min(1,Sw(f,p)),dw)}function Tw(e,t){if(t.ctx.spec.fix===!1)return[];let n=[],r=t.f0??0,i=(e,t,r,i,a)=>n.push({kind:e,msg:t,frame:r,value:+i.toFixed(4),limit:a});for(let n of vw(t))for(let a=Math.max(n.from,r);a<=Math.min(n.to,r+t.frames.length-1);a++){if(n.held&&!n.held(a))continue;let o=yw(t,n.id,a);o.length&&ww(e,t.frames[a-r].s,n,o,i,a-r)}return n}var Ew=.009,Dw=.004,Ow=[`Left`,`Right`],kw=[`Index`,`Middle`,`Ring`,`Pinky`],Aw=[[-45,100],[-5,115],[-20,90]],jw=e=>e*180/Math.PI;function Mw(e,t,n){let r=K(H(e,U(n,W(e,n)))),i=K(H(t,U(n,W(t,n))));return jw(Math.atan2(W(ho(r,i),n),W(r,i)))}function Nw(e,t,n,r){let i=[1,2,3,4].map(t=>e.index[`${n}Hand${r}${t}`]);if(i.some(e=>e===void 0))return null;let{d:a,l:o}=Xo(e,t,n),s=U(o,n===`Left`?-1:1),c=[0,1,2].map(e=>K(H(t.P[i[e+1]],t.P[i[e]])));return[a,c[0],c[1]].map((e,t)=>Mw(e,c[t],s))}function Pw(e,t,n,r){let i=H(t,e),a=H(r,n),o=H(e,n),s=W(i,i),c=W(a,a),l=W(a,o),u=W(i,o),d=W(i,a),f=s*c-d*d,p=e=>Math.min(1,Math.max(0,e)),m=f>1e-12?p((d*l-u*c)/f):0,h=c>1e-12?(d*m+l)/c:0;return h<0?(h=0,m=p(-u/s)):h>1&&(h=1,m=p((d-u)/s)),Math.hypot(...H(V(e,U(i,m)),V(n,U(a,h))))}function Fw(e,t,n,r,i){for(let a of kw){let o=Nw(e,t,n,a);if(!o)return;o.forEach((e,t)=>{let[o,s]=Aw[t],c=`${n}Hand${a}${t+1}`;e<o?r(`FINGER_ROM`,`${c} bent back`,i,-e,-o):e>s&&r(`FINGER_ROM`,`${c} curled past range`,i,e,s)})}let a=r=>t.P[e.index[`${n}Hand${r}`]];for(let e=0;e<kw.length;e++)for(let t=e+1;t<kw.length;t++){let o=null;for(let n=1;n<=3;n++)for(let r=1;r<=3;r++){let i=2*Ew-Pw(a(`${kw[e]}${n}`),a(`${kw[e]}${n+1}`),a(`${kw[t]}${r}`),a(`${kw[t]}${r+1}`));i>Dw&&(!o||i>o.overlap)&&(o={overlap:i,a:n,b:r})}o&&r(`FINGER_SELF`,`${n}Hand${kw[e]}${o.a} into ${n}Hand${kw[t]}${o.b}`,i,o.overlap,Dw)}}function Iw(e,t){let n=[],r=(e,t,r,i,a)=>n.push({kind:e,msg:t,frame:r,value:+i.toFixed(4),limit:a}),i=Ow.filter(t=>e.index[`${t}Hand`]!==void 0);return t.frames.forEach((t,n)=>{for(let a of i)Fw(e,t.s,a,r,n)}),n}var Lw={FINGER_ROM(e,t){let n=t.subject.startsWith(`Left`)?`l`:`r`;return{cause:e.cause(`fingers_${n}`,t.worstFrame),hint:`fingers_${n}: a joint is past what a finger does (${t.subject}); keep the preset weights summing to at most 1 and do not turn a phalanx past its curl`}},FINGER_SELF(e,t){let n=t.subject.startsWith(`Left`)?`l`:`r`;return{cause:e.cause(`fingers_${n}`,t.worstFrame),hint:`fingers_${n}: two fingers lie in each other (${t.subject}); give them one preset so they curl side by side`}}},Rw=.5,zw=1,Bw=90,Vw={twist:1-Gs,flex:1,dev:1},Hw=(e,t)=>t[e].map(t=>t*Vw[e]),Uw=`wrist: deg on the frames a hand holds (a fit, a carry or a grip on); flex + toward the palm, dev + radial / - ulnar, twist at the wrist joint; [min, f, max, f], frames past the comfortable range and at the limit; grip: the grip a keyed carry of a thin body keeps (grip-choice.js), cost [it, today's] (comfort-priced wrist, reach and body over the keys); elevation [max deg, f] of the upper arm (90 level), raised: frames the elbow is over the shoulder`;function Ww(e,t,n,r){let{diag:i}=e.frames[n],a=e.baked??{};if((i[`hold_${t}`]?.w??0)>Rw||(i[`grip_${t}`]?.w??0)>Rw)return!0;for(let n of e.ctx.spec.fits??[])if(n.side===t&&(a[`w_${n.anchor}_${t}`]?.[r]??0)>Rw)return!0;return Object.keys(e.ctx.spec.objects??{}).some(n=>e.ctx.spec.objects[n]?.prop&&Og(e,n,r)===t)}function Gw(e,t){let n=e.index,r=e.restWorldRot,i=t.f0??0,a={};for(let[o,s]of[[`Left`,`l`],[`Right`,`r`]]){let c=n[`${o}Hand`],l=n[`${o}ForeArm`],u=n[`${o}Arm`],d={frames:0,past:0,limit:0,raised:0};t.frames.forEach(({s:n},a)=>{let f=a+i;if(!Ww(t,s,a,f))return;let p=U(H(n.P[c],n.P[l]),1/Math.max(1e-9,G(H(n.P[c],n.P[l])))),m=q(n.R[l],q(Y(r[l]),r[c])),h=ic(m,n.R[c],p,J(q(m,Y(n.R[c])),Xo(e,n,o).l));d.frames++;for(let e of[`flex`,`dev`,`twist`]){let t=Math.round(h[e]),n=d[e];d[e]=n?[Math.min(n[0],t),t<n[0]?f:n[1],Math.max(n[2],t),t>n[2]?f:n[3]]:[t,f,t,f]}let g=(e,t)=>[`flex`,`dev`,`twist`].some(n=>{let[r,i]=Hw(n,e);return h[n]<r+t||h[n]>i-t});g(Ws,-1)&&d.past++,g(Us,zw)&&d.limit++;let _=H(n.P[l],n.P[u]),v=Math.round(Math.acos(Math.max(-1,Math.min(1,-_[1]/Math.max(1e-9,G(_)))))*180/Math.PI);(!d.elevation||v>d.elevation[0])&&(d.elevation=[v,f]),v>Bw&&d.raised++}),d.frames&&(a[`hand_${s}`]=d)}for(let e of t.ctx.hold?.grips?.()??[])a[`hand_${e.hand}`]&&(a[`hand_${e.hand}`].grip={object:e.id,chose:e.name,cost:[e.cost,e.today]});return Object.keys(a).length?a:null}var Kw=.5,qw=.5,Jw=[`flex`,`dev`,`twist`],Yw={l:`Left`,r:`Right`},Xw={flex:e=>e>=0?`flex`:`extension`,dev:e=>e>=0?`radial deviation`:`ulnar deviation`,twist:()=>`twist`};function Zw(e){let t=null;for(let n of Jw){let[r,i]=Us[n],a=e[n],o=a>=0?i:r,s=a>=0?a-i:r-a;(!t||s>t.past)&&(t={axis:n,value:a,edge:o,past:s})}return t}function Qw(e,t,n,r){let{s:i,diag:a}=t.frames[r],o=a[`hold_${n}`];if((o?.w??0)>qw)return o;let s=Yw[n],c=e.index,l=c[`${s}Hand`],u=c[`${s}ForeArm`],d=e.restWorldRot,f=U(H(i.P[l],i.P[u]),1/Math.max(1e-9,G(H(i.P[l],i.P[u])))),p=q(i.R[u],q(Y(d[u]),d[l]));return ic(p,i.R[l],f,J(q(p,Y(i.R[l])),Xo(e,i,s).l))}function $w(e,t){let n=[],r=t.f0??0;for(let i of[`l`,`r`])t.frames.forEach((a,o)=>{if(!Ww(t,i,o,o+r))return;let s=Zw(Qw(e,t,i,o));if(s.past<=Kw)return;let c=Math.abs(s.edge);n.push({kind:`WRIST`,msg:`hand_${i} ${Xw[s.axis](s.value)} ${Math.round(Math.abs(s.value))}deg (limit ${Math.round(c)})`,frame:o,value:+Math.abs(s.value).toFixed(2),limit:c})});return n}function eT(e,t){let n=/^hand_([lr]) /.exec(t.subject)?.[1];if(!n)return null;let r=t.worstFrame,i=`at f${r}${t.count>1?` (f${t.first}-f${t.last}, ${t.count} frames)`:``}`,a=Math.round(e.out.ctx?.swivel?.[n]?.get(r)??0);if(Math.abs(a)>=1)return{cause:`fix.self elbow turn ${a}deg at f${r}`,hint:`${t.subject} ${i}: fix.self turned the elbow ${a} deg to keep the arm out of the body and the hand kept its turn, so the wrist took it; key elbow_${n} (the elbow pole) or the hand's target so the arm clears the body without the turn`};let o=(e.out.frames[e.rel(r)]?.diag[`hold_${n}`]?.w??0)>qw&&Object.keys(e.spec.objects??{}).find(t=>e.spec.props?.[e.spec.objects[t]?.prop]?.hand===n),s=e.fr(r).c.spine_pitch??0;return{cause:o?`objects.${o}.keys near f${r}`:e.cause(`armw_${n}`,r),hint:`${t.subject} ${i}: the arm cannot turn the hand that far from where the body stands; lean the upper body over the hand (spine_pitch ${Math.round(s)} at f${r}: try ${Math.round(s+20)}) or bring the body to it (root), ${o?`or key ${o} so the hand need not bend that far (its aim or pos)`:`or move what the hand reaches`}; repair: { rounds } tries leans of 10-30 deg here and keeps one that helps`}}var tT={WRIST:eT},nT=105,rT=75,iT=.3,aT=.1,oT=4,sT=6,cT=2,lT=.5,uT=180/Math.PI,dT={l:`Left`,r:`Right`},fT={"over the head":0,high:1,wing:2};function pT(e,{s:t,diag:n,c:r},i){let a=(n[`hold_${i}`]?.w??0)>lT&&!n[`hold_${i}`].second;if(!a&&!((r[`armw_${i}`]??0)>lT))return null;let o=e.index,s=t.P[o[`${dT[i]}Arm`]],c=t.P[o[`${dT[i]}ForeArm`]],l=t.P[o[`${dT[i]}Hand`]],u=o.Spine2??o.Hips,d=Lo(e,t,u,[0,1,0]),f=U(Lo(e,t,u,[1,0,0]),i===`l`?1:-1),p=Io(t,o.Head,e.landmarks.headCentre);if(W(H(l,p),d)>e.landmarks.headRadii[1]+aT)return null;let m=H(c,s),h=Math.acos(_o(-W(m,d)/G(m),-1,1))*uT,g=Math.atan2(W(m,f),-W(m,d))*uT;if(W(H(c,p),d)>0)return{kind:`over the head`,deg:h,held:a};if(h>nT)return{kind:`high`,deg:h,held:a};let _=H(l,t.P[o.Spine]),v=G(H(_,U(d,W(_,d))));return g>rT&&v<iT?{kind:`wing`,deg:g,held:a}:null}function mT(e,t,n,r,i){let a=e.ctx.spec,o=t=>e.timeMap?e.timeMap(t):t;for(let[s,c]of Vm(a)){if(a.props?.[c.prop]?.hand!==t)continue;let l=(e.ctx.hold?.entry?.(s)??c).keys,u=l.map((e,t)=>[t,e]).filter(([,e])=>o(e.f)>=n&&o(e.f)<=r),d=l.reduce((e,t,n)=>Math.abs(o(t.f)-i)<Math.abs(o(l[e].f)-i)?n:e,0);return{id:s,picks:u.length?u:[[d,l[d]]]}}return null}var hT=e=>Math.round(e*100)/100,gT=(e,t)=>t.map(([t,n])=>`objects.${e}.keys[${t}] (f${n.f})`).join(`, `);function _T(e,t,n){let r=n.k,i=r===`l`?1:-1,a=n.held&&mT(t,r,n.first,n.last,n.worst);if(a){let r=a.picks.filter(([,e])=>e.aim&&!(e.lean>=45));if(r.length)return`give ${gT(a.id,r)} lean 45 (tips the aim to the hand's side, the elbow stays down)`;let i=t.frames[Math.max(0,Math.min(t.frames.length-1,Math.round(n.worst-(t.f0??0))))],o=a.picks[0][1].pos,s=H(i.s.P[e.index.Spine2??e.index.Hips],o),c=Math.hypot(s[0],s[2])||1;return`move ${gT(a.id,a.picks)} pos by [${hT(.05*s[0]/c)}, -0.08, ${hT(.05*s[2]/c)}] (lower, nearer the chest)`}return`key elbow_${r} [${(n.kind===`wing`?[hT(.1*i),-1,.2]:[hT(.3*i),-1,n.mouth?.35:-.2]).join(`, `)}] from f${n.first} to f${n.last} (down${n.kind===`wing`?` and in`:` and a little out`}${n.mouth?`, in front of the chest`:``})`}var vT={"over the head":`upper arm wraps over the head`,high:`elbow over the shoulder`,wing:`elbow flared out to the side`};function yT(e,t){let n=[],r=t.f0??0,i=t=>Io(t,e.index.Head,e.landmarks.mouth);for(let a of[`l`,`r`]){let o=null,s=()=>{o&&o.n>=oT&&n.push(o),o=null};t.frames.forEach((t,n)=>{let c=pT(e,t,a),l=n+r;if(o&&(l-o.last>sT||c&&c.held!==o.held)&&s(),!c)return;let u=G(H(t.s.P[e.index[`${dT[a]}Hand`]],i(t.s)))<.25;o??={k:a,kind:c.kind,held:c.held,first:l,worst:l,deg:c.deg,n:0,mouth:!1},o.last=l,o.n++,o.mouth||=u,(fT[c.kind]<fT[o.kind]||c.kind===o.kind&&c.deg>o.deg)&&Object.assign(o,{kind:c.kind,deg:c.deg,worst:l})}),s()}return n.sort((e,t)=>fT[e.kind]-fT[t.kind]||t.n-e.n),n.slice(0,cT).map(n=>`ARM arm_${n.k} ${vT[n.kind]} f${n.first}-f${n.last} (worst f${n.worst}, upper arm ${Math.round(n.deg)}deg ${n.kind===`wing`?`out`:`up`}): ${_T(e,t,n)}`)}var bT=(e,t)=>` (${e}the knee would fold ${Math.round(t)}deg; it bends to 150deg and stops at 160deg)`;function xT(e,t,n,r,i){let a=t===`l`?`Left`:`Right`,o=e.fr(n).s.P,s=o[e.I[`${a}UpLeg`]],c=o[e.I[`${a}Leg`]],l=o[e.I[`${a}Foot`]],u=H(i,s),d=zo(go(s,c),go(c,l),150)+.002,f=U(K(u),Math.max(0,d-G(u))),p=u[1]+Math.sqrt(Math.max(0,u[1]*u[1]-W(u,u)+d*d));return u[1]<0?{cause:e.cause(`root`,n),hint:`root: raise ${Q(p)} m at f${n}${r}, or key foot_${t} farther from the hip (wider or more forward)`,fix:{channel:`root`,f:n,delta:[0,p,0]}}:{cause:e.cause(`foot_${t}`,n),hint:`foot_${t}: move ${kS(f)} m out from the hip at f${n}${r}, or raise root ${Q(p)} m`,fix:{channel:`foot_${t}`,f:n,delta:f}}}var ST=.003,CT=.25,wT=e=>/(^|_)l$|^Left/.test(e)?`l`:/(^|_)r$|^Right/.test(e)?`r`:null;function TT(e,t,n,r,i){let a=e.spec.anchors?.[t],o=e=>`/anchors/${t}/${e}`;if(a?.kind===`world`)return{path:o(`p`),delta:r};if(a?.kind===`body`)return{path:o(`p`),delta:J(X(-(e.fr(n).c.yaw??0)),r)};if([`bone`,`segment`,`prop`,`person`].includes(a?.kind))return{path:o(`offset`),delta:r};if(a?.kind!==`object`)return;let s=e.fr(n),c=Rd(e.out.ctx,a,t,{...s,diag:{...s.diag,frame:n}},i);return{path:o(`local`),delta:J(Y(c.R),r)}}function ET(e,t,n,r,i=``){let a=/^prop_(.+)$/.exec(t),o=a?e.spec.props?.[a[1]]?.hand:wT(t),s,c,l,u=r;if(/^(hand|farm|uarm)_/.test(t)||a){let t=e.hand(o,n);s=t.label,l=t.anchor?TT(e,t.anchor,n,r,o):t.ch===`hand_${o}`?{channel:t.ch,f:n,delta:r}:void 0;let i=t.anchor&&e.spec.anchors[t.anchor]?.kind===`object`?e.spec.anchors[t.anchor].object:null;i&&l&&(s=`anchors.${t.anchor}.local (a point on ${i}, in ${i}'s axes; ${i} stays)`,u=l.delta),c=t.anchor?`anchor ${t.anchor}${t.fit===null?``:` (fits[${t.fit}])`} via ${e.cause(t.ch,n)}`:e.cause(t.ch,n)}else/^(shin|foot|sole)_/.test(t)?(s=`foot_${o}`,c=e.cause(s,n),l={channel:s,f:n,delta:r}):(s=`root`,c=e.cause(`root`,n),l={channel:`root`,f:n,delta:r,.../^root held since /.test(c)?{hold:!0}:{}});return/ (walk|walkTo) /.test(` ${c}`)&&/step|start|end/.test(c)&&!/^anchor/.test(s)?{cause:c,hint:`walk path: ${s} needs ${kS(r)} m at f${n}${i}; change that walk's heading/turnDistance/step (or give one a { range: [lo, hi] })`}:{cause:c,hint:`${s}: move ${kS(u)} m at f${n}${i}`,fix:l}}var DT=e=>Sc.find(t=>t[0]===e);function OT(e,t,n,r){let[,i,a]=DT(n),{s:o}=e.fr(t),s=Cc(o.P[e.I[i]],o.P[e.I[a]]),c=s.map(e=>wc(e,r)),l=Math.min(...c);return{p:s[c.indexOf(l)],n:Ac(s[c.indexOf(l)],r),d:l}}function kT(e,t,n,r,i){let a=t.worstFrame,o=e.out.objectsAt(e.rel(a))[r];if(!o||!DT(n))return null;let{n:s}=OT(e,a,n,o);return ET(e,n,a,U(s,i),` (out of ${r})`)}function AT(e,t,n,r){let i=t.worstFrame,a=e.out.objectsAt(e.rel(i))[r];if(!a)return null;let o=ed(e.sk,e.fr(i).s,n.endsWith(`_l`)?`Left`:`Right`),s=td(o,a),c=t.worst-t.limit+ST;if(!(s.side>0))return s.topAt?ET(e,n,i,U(Ac(s.topAt,a),c),` (out of ${r}'s top)`):null;let l=Math.max(...o.filter(e=>wc(e,a)<0).map(e=>2*a.half[1]-J(Y(a.R),H(e,a.pos))[1]))+ST,u=U(Ac(s.sideAt,a),c);if(l>CT)return ET(e,n,i,u,` (out of ${r}'s side)`);let d=ET(e,n,i,J(a.R,[0,l,0]),` (over ${r}'s top; its ${t.worst.toFixed(3)} m is through a side)`);return d.hint+=/^walk path/.test(d.hint)?`; a higher lift raises the swing`:`; or move ${kS(u)} m out of that side`,d}function jT(e,t,n,r,i,a){return ET(e,n,t.worstFrame,U(K(r),i),` (away from the ${a})`)}function MT(e,t,n){let{s:r,diag:i}=e.fr(t),a=e.I;if(n.startsWith(`hand_`)){let e=n.endsWith(`l`)?`Left`:`Right`;return Cc(r.P[a[`${e}Hand`]],r.P[a[`${e}HandMiddle3`]],5)}return Object.entries(i.props?.[n.slice(5)]??{}).filter(([e,t])=>Array.isArray(t)&&e!==`origin`).map(([,e])=>e)}var NT={COLLIDE(e,t){let[,n,r]=/^(\S+) x (.+)$/.exec(t.subject)??[];if(/^foot_[lr]$/.test(n??``))return AT(e,t,n,r);let i=kT(e,t,n,r,t.worst-t.limit+ST);return i&&/^(hand|farm)_/.test(n)&&!e.spec.fix?.penetration&&t.worst-t.limit<=.05&&(i.hint+=`; or fix.penetration: 0.02 pushes shallow hand hits out`,e.spec.fix!==!1&&(i.fix={path:`/fix/penetration`,value:.02})),i},PERSON(e,t){let[,n,r]=/^(\S+) x person:(.+)$/.exec(t.subject)??[],i=DT(n),a=e.out?.ctx?.scene?.people?.[r];if(!i||!a)return null;let o=t.worstFrame,{s}=e.fr(o),c=Cc(s.P[e.I[i[1]]],s.P[e.I[i[2]]]),l=ld(a,o).map(([e,t,n,r])=>{let a=H(n,t),o=Math.max(W(a,a),1e-12);return c.map(n=>{let s=V(t,U(a,_o(W(H(n,t),a)/o,0,1)));return{other:e,p:n,q:s,depth:i[3]+r-G(H(n,s))}}).reduce((e,t)=>t.depth>e.depth?t:e)}).reduce((e,t)=>t.depth>e.depth?t:e),u=ET(e,n,o,U(G(H(l.p,l.q))>1e-6?K(H(l.p,l.q)):K([l.p[0]-l.q[0]||1,0,l.p[2]-l.q[2]]),t.worst-t.limit+ST),` (out of ${a.name}'s ${l.other})`);return{...u,hint:`${u.hint}; or, for a touch you mean, checks.allow [{ part: "${n}", object: "person:${r}", depth: ${Q(t.worst+ST)} }]`}},CLEARANCE(e,t){let n=(e.spec.checks?.clearance??[]).find(e=>t.subject.startsWith(`${e.name}:`));return n&&kT(e,t,n.part,n.object,n.min-t.worst+ST)},GROUND(e,t){let n=t.subject.startsWith(`Left`)?`l`:`r`,r=t.worstFrame,i=e.fr(r).c,a=e.fr(r).diag[`leg_fold_${n}`];if(a)return xT(e,n,r,bT(`the sole is in the floor because the knee is on its stop: `,a),i[`foot_${n}`]);let o=i[`fpitch_${n}`]?`, or less fpitch_${n} (now ${Q(i[`fpitch_${n}`])} deg; + lifts the heel)`:``;return{cause:e.cause(`foot_${n}`,r),hint:`foot_${n}: raise ${Q(t.worst+.001)} m at f${r} (foot_* is the ankle; it stands ${Dc(e.sk)} m above the floor)${o}`,fix:{channel:`foot_${n}`,f:r,delta:[0,t.worst+.001,0]}}},FACE(e,t){let n=t.subject.replace(/ into head$/,``),r=t.worstFrame,{s:i}=e.fr(r),a=Io(i,e.I.Head,e.sk.landmarks.headCentre);return jT(e,t,n,H(MT(e,r,n).reduce((t,n)=>Ec(e.sk,i,n)>Ec(e.sk,i,t)?n:t),a),t.worst-t.limit+ST,`head`)},BODY(e,t){let[,n,r]=/^(\S+) into (\S+)$/.exec(t.subject)??[],i=DT(r),a=t.worstFrame,{s:o}=e.fr(a),s=/^(hand|farm|uarm)_([lr])$/.exec(n??``),c=s&&Es(e.sk);if(c){let i=e.I[`${s[2]===`l`?`Left`:`Right`}${{hand:`Hand`,farm:`ForeArm`,uarm:`Arm`}[s[1]]}`],l=Hs(c,e.sk,o,i),u=l.p&&js(c,o,l.p,c.skip.get(i));if(u){let i=ET(e,n,a,U(u,t.worst-t.limit+ST),` (out of the ${r})`);return s[1]!==`hand`&&(i.hint+=`; or turn elbow_${s[2]} away from the ${r}`),i}}if(!i)return null;let l=o.P[e.I[i[1]]],u=o.P[e.I[i[2]]],d=H(u,l),f=e=>V(l,U(d,_o(W(H(e,l),d)/W(d,d),0,1))),p=MT(e,a,n).reduce((e,t)=>G(H(t,f(t)))<G(H(e,f(e)))?t:e);return jT(e,t,n,H(p,f(p)),t.worst-t.limit+ST,`torso`)},SELF(e,t){let n=t.worstFrame,{s:r}=e.fr(n),i=r.P,a=e.I;if(t.subject===`hands overlap`){let r=K(H(i[a.LeftHand],i[a.RightHand])),o=(t.worst-t.limit+ST)/2,s=ET(e,`hand_l`,n,U(r,o));return{cause:s.cause,hint:`${s.hint}; and ${ET(e,`hand_r`,n,U(r,-o)).hint}`,fix:ET(e,`hand_l`,n,U(r,2*o)).fix}}let o=t.subject===`shins touch`,s=o?.1:.135,[c,l]=o?[`Leg`,`Foot`]:[`UpLeg`,`Leg`],u=Tc(i[a[`Left${c}`]],i[a[`Left${l}`]],i[a[`Right${c}`]],i[a[`Right${l}`]]),d=H(i[a[`Left${l}`]],i[a[`Right${l}`]]);d[1]=0;let f=(s-u+ST)/2,p=K(d);return{cause:e.cause(`foot_l`,n),hint:`foot_l: move ${kS(U(p,f))} m and foot_r ${kS(U(p,-f))} m at f${n} (${o?`shins`:`thighs`} ${Q(u)} m apart, need ${s}); or spread knee_l/knee_r`,fix:{channel:`foot_l`,f:n,delta:U(p,2*f)}}},OBJECT(e,t){let[,n,r]=/^(\S+) into (.+)$/.exec(t.subject)??[],i=e.spec.objects?.[n]?.channel;if(!i)return null;let a=t=>e.out.baked[i]?.[t]??0,o=t.first>0?a(t.first-1):a(0);return{cause:e.cause(i,t.worstFrame),hint:`${i}: keep it within ${Q(o)} deg (it reaches ${Q(a(t.worstFrame))} at f${t.worstFrame}, ${Q(t.worst)} m into ${r}), or move ${r}`,fix:{channel:i,f:t.worstFrame,value:o}}},BALANCE(e,t){let n=t.worstFrame;if(t.subject===`no foot on the ground`)return{cause:e.cause(`root`,n),hint:`at f${n} lower foot_l or foot_r onto the ground, the floor or the top of an object under it (the ankle stands ${Dc(e.sk)} m above it), or declare checks.supports for the seat the hips rest on`};let r=Cu(e.out,Math.max(0,Math.min(e.out.frames.length-1,n-(e.out.f0??0))));if(r===`air`||r.margin>=0)return null;let i=-r.margin,a=(i-Math.min(i,Math.max(0,(t.limit??.08)-.01)))/i,o=[(r.near[0]-r.com[0])*a,0,(r.near[1]-r.com[2])*a];return{cause:e.cause(`root`,n),hint:`root: move ${kS(o)} m at f${n} (centre of mass ${Tu(r)}, toward the nearest edge of the support polygon), or step a foot under it`,fix:{channel:`root`,f:n,delta:o}}}},PT=.003,FT=.02,IT=.2;function LT(e,t,n,r,i=``){let a=t===`l`?`Left`:`Right`,{s:o}=e.fr(n),s=H(o.P[e.I[`${a}Hand`]],o.P[e.I[`${a}Arm`]]),c=Math.hypot(s[0],s[2])/Math.max(G(s),1e-9);if(c<.5)return null;let l=U(K([s[0],0,s[2]]),Math.min(IT,r/c));return{delta:l,hint:`body: move ${kS(l)} m toward the target at f${n}, ${e.cause(`root`,n)} (arm ${t} is at full reach)${i}`,fix:{channel:`root`,f:n,delta:l,hold:!0}}}var RT=(e,t,n)=>(e.fr(n).diag[`reach_over_${t}`]??0)>.001||(e.fr(n).diag[`arm_miss_${t}`]??0)>.002&&!e.fr(n).diag[`arm_fold_${t}`];function zT(e,t,n,r){let i=null;for(let[a,o]of Object.entries(e.fr(n).c))a===r||!RegExp(`^w_.+_${t}$`).test(a)||!(o>FT)||i&&o<=i.w||(i={ch:a,w:o});return i}function BT(e,t,n,r,i){let a=n.slice(-1),o=e.hand(a,r),s=o.anchor?zT(e,a,r,o.ch):null;if(!s)return null;let c=Array.isArray(t.at)?t.at[1]:t.at,l=e.bracket(s.ch,r).prev,u=l&&Math.abs(e.out.baked[s.ch]?.[Math.round(l.f)]??1)<=FT&&c>=r&&!(e.bracket(s.ch,r).next?.f<=c)?c:r,d=s.w/Math.max(1,(e.fr(r).c[o.ch]??1)+s.w),f=s.ch.replace(/^w_/,``).replace(/_[lr]$/,``);return{cause:e.cause(s.ch,r),hint:`${s.ch} is ${Q(s.w)} at f${r}, so anchor ${f} takes ${Math.round(d*100)}% of the hand target from ${o.label}: key ${s.ch} 0 at f${u}${i}`,fix:{channel:s.ch,f:u,value:0}}}function VT(e,t){let n=null;return(e.spec?.goals??[]).forEach((e,r)=>{let i=FS(e,r);t.subject.startsWith(`${i}:`)&&(!n||i.length>n.name.length)&&(n={goal:e,name:i,i:r})}),n}function HT(e,t,n){let r=[t,...e.out.ctx.scene?.objects?.[t]?.ancestors??[]].find(t=>cg(e.spec.objects?.[t],n));return r?e.spec.objects[r]:null}function UT(e,t,n){let[,r,i]=/^([a-z]+):(.+)$/s.exec(t)??[];if(r===`prop`)return e.spec.props?.[i.split(`.`)[0]]?.hand?`hand_${e.spec.props[i.split(`.`)[0]].hand}`:null;if(r===`object`){let t=HT(e,i.replace(/\.(center|top|base|rim)$/,``),n),r=t&&e.spec.props?.[t.prop]?.hand;return r?`hand_${r}`:null}if(r===`landmark`)return`root`;if(r!==`joint`&&r!==`bone`)return null;let a=Bl(e.sk,i).bone??``,o=/^Left/.test(a)?`l`:/^Right/.test(a)?`r`:null;return o&&/^(Left|Right)(Hand|ForeArm)/.test(a)?`hand_${o}`:o&&/^(Left|Right)(Foot|Toe|Leg)/.test(a)?`foot_${o}`:`root`}function WT(e,t,n,r){let i=t.slice(-1);if(!t.startsWith(`hand_`))return{channel:t,f:n,delta:r};let a=e.hand(i,n);return a.ch===`hand_${i}`?{channel:a.ch,f:n,delta:r}:a.anchor&&e.spec.anchors?.[a.anchor]?.kind===`world`?{path:`/anchors/${a.anchor}/p`,delta:r}:null}function GT(e,t,n,r,i,a){if(n===`moved`||n===`still`){let o=t[n],s=UT(e,o,r),c=VS(e.out,t,a),l=Zd(e.out,r,RS(o)),u=l&&c&&G(H(l,c))>.001?K(H(l,c)):[0,1,0];return s?[s,U(u,n===`still`?-i:i)]:null}let[o,s]=n===`near`?GS(e.out.ctx.scene,t):t[n],c=UT(e,o,r),l=UT(e,s,r),u=e=>e?.startsWith(`hand_`)?2:+!!e,d=u(c)>=u(l),f=d?c:l,p=d?1:-1;if(!f)return null;if(n===`above`)return[f,[0,p*i,0]];let m=Zd(e.out,r,o),h=Zd(e.out,r,s);return m&&h?[f,U(K(H(h,m)),p*i)]:null}var KT={GOAL(e,t){let n=e.spec&&VT(e,t),r=t.worstFrame;if(!n)return{cause:`goal ${t.subject.split(`:`)[0]}`,hint:`change the keys around f${r} until the goal holds`};let{goal:i,name:a,i:o}=n,s=PS(i)[0],c=t.worst+PT,l=eC(e.out,e.spec.goals,o);if(l.wait){let e=i.after??i.before;return{cause:`goal ${a}`,hint:`${a} ${l.wait}: make goal "${e}" hold${i.after!==void 0&&i.before!==void 0?` and "${i.before}"`:``} where this one needs it, or move at`}}let u=s===`speed`?`m/s`:`m`,d=s===`near`||s===`still`?`<=`:`>=`,f=` (goal "${a}" is ${Q(t.worst)} ${u} ${s===`still`?`off`:`short`}; needs ${d} ${IS(i,s)})`;if(s===`speed`){let t=UT(e,i.speed,r);return{cause:t?e.cause(t,r):`goal ${a}`,hint:`${i.speed} is too slow at f${r}: put its keys around f${r} closer in time, or farther apart in space${f}`}}let p=GT(e,i,s,r,c,l.a);if(!p){if(s===`still`&&i.still.startsWith(`object:`)){let e=i.still.slice(7).replace(/\.(center|top|base|rim)$/,``);return{cause:`objects.${e}`,hint:`${e} moves at f${r}, where it should stay: hold its hinge channel or keys until then, or start them later${f}`}}if(s===`still`)return{cause:`goal ${a}`,hint:`${i.still} moves at f${r} and nothing that follows the body moves it; name a joint, prop point or held object${f}`};if(s===`moved`&&!i.moved.startsWith(`object:`))return{cause:`goal ${a}`,hint:`${i.moved} does not move with the body at f${r}; name a joint, prop point or held object`};if(s===`moved`){let e=i.moved.slice(7).replace(/\.(center|top|base|rim)$/,``);return{cause:`objects.${e}`,hint:`${e} is not in a hand at f${r}, so nothing moves it: carry it (objects.${e} = { prop, grab }) or hinge it`}}return{cause:`goal ${a}`,hint:`neither ${i[s][0]} nor ${i[s][1]} moves with the body at f${r}; name a joint, prop point or held object`}}let[m,h]=p;if(m.startsWith(`hand_`)){let t=BT(e,i,m,r,f);if(t)return t;let n=RT(e,m.slice(-1),r)&<(e,m.slice(-1),r,c,f);if(n)return{cause:e.cause(`root`,r),hint:n.hint,fix:n.fix}}let g=ET(e,m,r,h,f),_=WT(e,m,r,h);return{cause:g.cause,hint:g.hint,..._?{fix:_}:{}}}},qT=.5;function JT(e,t,n,r,i=qT){if(!Number.isInteger(t)||!Number.isInteger(n)||n<t||!(r>0))return null;let a=t-1,o=n+1;if(a<0||o>e.length-1)return null;let s=e[a],c=e[o],l=o-a;if(!Number.isFinite(s)||!Number.isFinite(c))return null;let u=(c-s)/l+r*l/2,d=[],f=t;for(let i=t;i<=n;i++){if(!Number.isFinite(e[i]))return null;let n=i-a,o=s+u*n-r/2*n*n-e[i];d.push(o),Math.abs(o)>Math.abs(d[f-t])&&(f=i)}return Math.abs(d[f-t])>i?null:{from:a,to:o,v0:u,delta:d,worst:f}}function YT(e){let{from:t,to:n}=e,r=t+1,i=n-1,a=[];for(let e of[.25,.5,.75]){let o=Math.min(i,Math.max(r,Math.round(t+(n-t)*e)));a.includes(o)||a.push(o)}return a}function XT(e,t,n,r){let i=JT(e,t,n,r,1/0);if(!i||Math.abs(i.delta[i.worst-t])<=.5)return null;let a=i.to-i.from,o=Math.max(...Array.from(i.delta,(n,r)=>e[t+r]))-e[i.from];return{off:i.delta[i.worst-t],frames:a,apex:r*a*a/8,height:o,fits:o>0?Math.round(Math.sqrt(8*o/r)):0}}var ZT={Leg:[`UpLeg`,`Leg`,`Foot`,`knee`],ForeArm:[`Arm`,`ForeArm`,`Hand`,`elbow`]},QT=e=>e.startsWith(`Left`)?`l`:`r`,$T=e=>/^(w_|armw)/.test(e)?.5:/^(root|foot|hand)/.test(e)?1:/^(knee|elbow)/.test(e)?.2:.01;function eE(e,t,n){let r=QT(t),i=e.out.baked,a=[`root`,`yaw`,`pitch`];t===`Head`?a=[`head_yaw`,`head_pitch`,`spine_pitch`,`spine_yaw`,`root`,`yaw`]:/Hand|ForeArm/.test(t)?a=[`hand_${r}`,`armw_${r}`,`elbow_${r}`,`aswing_${r}`,`abend_${r}`,...Object.keys(i).filter(e=>RegExp(`^w_.+_${r}$`).test(e)),`spine_yaw`,`spine_pitch`,`root`,`yaw`]:/Foot|Leg/.test(t)&&(a=[`foot_${r}`,`knee_${r}`,`fpitch_${r}`,`root`]);let o=e=>{let t=i[e]?.[n-1],r=i[e]?.[n];return t===void 0||r===void 0||typeof t==`object`&&!Array.isArray(t)?0:(Array.isArray(t)?go(t,r):Math.abs(r-t))*$T(e)};return a.filter(e=>i[e]).sort((e,t)=>o(t)-o(e))}function tE(e,t,n){let r=t.subject.split(` `)[0],i=t.worstFrame,a=eE(e,r,i)[0]??`root`,{prev:o,next:s}=e.bracket(a,i),c=e.keys(a).find(e=>e.step&&Math.abs(e.f-i)<=1);if(c)return{cause:e.cause(a,i),hint:`${a}: a step key jumps at f${Math.round(c.f)}; ease it over 4+ frames (key the old value 4 frames earlier, drop the step)`};let l=Math.ceil((t.worst/t.limit)**+n*1.1*10)/10,u=Math.round(o?.f??i-4),d=Math.round(s?.f??i+4),f=Math.ceil((d-u)*(l-1)),p=/^w_(.+)_[lr]$/.exec(a);return{cause:e.cause(a,i),hint:`retime: stretch f${u}-f${d} by ${l}x (+${f} frames, move the keys from f${d} on later)${p?` - the hand switches to anchor ${p[1]} too fast`:``}; or fix.retime: true`,fix:e.spec.fix===!1?void 0:{path:`/fix/retime`,value:!0}}}function nE(e,t,n){let[r,i]=n.split(/:(.*)/s);if(r===`joint`)return t.s.P[e.I[i]];if(r===`prop`){let[e,n]=i.split(`.`);return t.diag.props?.[e]?.[n]}return Fd(e.out.ctx,i,t.s,t.diag,t.c)}function rE(e,t,n,r){let i=Hf(e.out.baked,t),a=r(e.fr(t)),o=null;for(let[s,c,l]of n){let n=r(dS(e.out.ctx,{...i,[s]:c},t))-a;n>1e-6&&(!o||n/l>o.gain/o.unit)&&(o={ch:s,value:c,gain:n,unit:l})}return{best:o,base:a,c0:i}}function iE(e,t){let n=e.out.f0??0,[,r=t.first,i=t.last]=/ f(\d+)-f(\d+)/.exec(t.subject)?.map(Number)??[],a=e.out.frames.map(t=>t.s.P[e.I.Hips][1]),o=9.81/(e.out.fps??24)**2,s=JT(a,r-n,i-n,o);if(!s){let e=XT(a,r-n,i-n,o);return e&&{presc:{...e,from:r-1,to:i+1}}}let c=e=>Math.round((s.delta[e-n-s.from-1]??0)*1e4)/1e4,l=e=>({f:e+n,dy:c(e+n)});return{...l(s.worst),from:s.from+n,to:s.to+n,dyAt:c,keys:YT(s).map(l)}}function aE(e,t,n){let r=Array.isArray(t.keys)?[]:[{op:`add`,path:`/keys`,value:[]}],i=new Set,a=e=>Math.round(e*1e4)/1e4;for(let{f:o,dy:s}of n.keys){let c=(t.keys??[]).findIndex(e=>Array.isArray(e?.set?.root)&&e.set.root.length===3&&Math.abs(e.f-o)<=2&&e.f>n.from&&e.f<n.to);if(c>=0&&i.has(c))continue;let l=c>=0?t.keys[c].set.root:e.fr(o).c.root,u=c>=0?n.dyAt(t.keys[c].f):s;if(!Array.isArray(l))continue;c>=0&&i.add(c);let d=[a(l[0]),a(l[1]+u),a(l[2])];r.push(c>=0?{op:`replace`,path:`/keys/${c}/set/root`,value:d}:{op:`add`,path:`/keys/-`,value:{f:o,set:{root:d}}})}let o=e=>(t.keys??[]).some(t=>Array.isArray(t?.set?.root)&&Math.abs(t.f-e)<=2);for(let t of[n.from,n.to])!o(t)&&Array.isArray(e.fr(t).c.root)&&r.push({op:`add`,path:`/keys/-`,value:{f:t,set:{root:e.fr(t).c.root.map(a)}}});return r}var oE=(e,t,n,r)=>e.fr(n).s.P[e.I[`${t===`l`?`Left`:`Right`}${ZT[r][0]}`]],sE={REACH(e,t){let[,n,r]=/^(leg|arm)_miss_([lr])$/.exec(t.subject)??[],i=t.worstFrame,a=t.worst+.002;if(n===`leg`){let n=e.fr(i).diag[`leg_fold_${r}`];if(n)return xT(e,r,i,bT(`the ankle target is ${Q(t.worst)} m inside the shin's reach: `,n),e.fr(i).c[`foot_${r}`]);let o=e.fr(i).c[`foot_${r}`]??[0,0,0],s=oE(e,r,i,`Leg`),c=H(o,s),l=go(s,o)-t.worst,u=c[1]*c[1]-W(c,c)+l*l,d=[c[0],0,c[2]],f=u>=0?`or root down ${Q(-c[1]-Math.sqrt(u)+.002)} m${t.worst<=.05?` (fix.reach does this when on)`:``}`:`or root ${kS(U(K(d),G(d)-l*.95))} m toward the foot (the foot is ${Q(G(d))} m sideways of the hip: the root and foot keys disagree)`;return{cause:e.cause(`foot_${r}`,i),hint:`foot_${r}: move ${kS(U(K(H(s,o)),a))} m toward the hip at f${i}, ${f}`,fix:{channel:`foot_${r}`,f:i,delta:U(K(H(s,o)),a)}}}let o=r===`l`?`Left`:`Right`,{s,diag:c}=e.fr(i),l=K(H(s.P[e.I[`${o}Hand`]],s.P[e.I[`${o}Arm`]])),u=c[`arm_fold_${r}`];if(u){let n=ET(e,`hand_${r}`,i,U(l,a),` (the hand target is ${Q(t.worst)} m inside the forearm's reach: the elbow would fold ${Math.round(u)}deg; it bends to 145deg and stops at 150deg)`);return{cause:n.cause,hint:`${n.hint}, or bring root ${kS(U([-l[0],0,-l[2]],a))} m back from it`,fix:n.fix}}let d=ET(e,`hand_${r}`,i,U(l,-a),``),f=e.hand(r,i).anchor,p=JSON.stringify([e.spec.goals??[],e.spec.checks?.contacts??[]]),m=f&&(e.spec.anchors?.[f]?.kind===`object`||p.includes(`"anchor:${f}"`)),h=e.spec.fits?.[e.hand(r,i).fit??-1],g=h?.effector?.prop&&e.fr(i).diag.props?.[h.effector.prop]?.[h.effector.point],_=g?go(g,V(nE(e,e.fr(i),`anchor:${f}`),h.offset??[0,0,0]))+.01:a,v=m&<(e,r,i,Math.min(a,_));return v?{cause:d.cause,hint:`${v.hint} (out of reach by ${Q(t.worst)} m), or ${d.hint}`,fix:v.fix}:{cause:d.cause,hint:`${d.hint} (out of reach by ${Q(t.worst)} m), or bring root ${kS(U([l[0],0,l[2]],a))} m closer`,fix:d.fix}},KNEE(e,t){let n=QT(t.subject),r=n===`l`?`Left`:`Right`,i=t.worstFrame,{s:a,c:o}=e.fr(i),s=a.P,c=e.I;if(/backward/.test(t.subject)){let t=H(s[c[`${r}ToeBase`]],s[c[`${r}Foot`]]);t[1]=0;let a=V(K(J(X(-(o.yaw??0)),t)),[0,.3,0]);return{cause:e.cause(`knee_${n}`,i),hint:`knee_${n}: key ${kS(K(a))} (body frame, along the foot) at f${i}; a knee pole is +z forward, +x the character's left`,fix:{channel:`knee_${n}`,f:i,value:K(a)}}}if(/ folds /.test(t.subject))return xT(e,n,i,` (the knee folds ${Q(t.worst)}deg, past its ${t.limit}deg stop; it bends freely to 150deg)`,s[c[`${r}Foot`]]);let l=s[c[`${r}UpLeg`]],u=s[c[`${r}Leg`]],d=s[c[`${r}Foot`]],f=go(l,u),p=go(u,d),m=(180-(t.limit-5))*Math.PI/180,h=Math.sqrt(f*f+p*p-2*f*p*Math.cos(m));return{cause:e.cause(`foot_${n}`,i),hint:`foot_${n}: move ${kS(U(K(H(d,l)),h-go(l,d)))} m away from the hip at f${i} (the knee folds ${Q(t.worst)} deg, limit ${t.limit})`,fix:{channel:`foot_${n}`,f:i,delta:U(K(H(d,l)),h-go(l,d))}}},ELBOW(e,t){let n=QT(t.subject),r=n===`l`?`Left`:`Right`,i=t.worstFrame,a=e.fr(i).s.P,o=e.I,s=a[o[`${r}Arm`]],c=a[o[`${r}ForeArm`]],l=a[o[`${r}Hand`]],u=U(K(H(l,s)),zo(go(s,c),go(c,l),145)-go(s,l));return ET(e,`hand_${n}`,i,u,` (the elbow folds ${Q(t.worst)}deg, past its ${t.limit}deg stop; it bends freely to 145deg)`)},FLIP(e,t){let[,n,r]=/^(Left|Right)(Leg|ForeArm) /.exec(t.subject)??[],i=t.worstFrame;if(!r)return null;let a=QT(n),[o,s,c,l]=ZT[r],u=e.I,d=+(/ over (\d+) frames$/.exec(t.subject)?.[1]??1),f=e.fr(i).diag,p=r===`ForeArm`&&(f[`arm_fold_${a}`]??f[`hold_${a}`]?.fold);if(p){let t=f[`hold_${a}`]?.fold&&Object.entries(e.spec.objects??{}).find(([,t])=>t.keys?.length&&e.spec.props?.[t.prop]?.hand===a)?.[0];return{cause:t?`objects.${t}.keys`:e.cause(e.hand(a,i).ch,i),hint:`the ${t?`keys of ${t} ask`:`hand target asks`} the elbow to fold ${Math.round(p)}deg at f${i}, past its 150deg stop, so the hand swings round the shoulder on the stop: move ${t?`the keyed pose`:`the target`} out from the shoulder (REACH says how far)`}}let m=t=>{let r=e.fr(t).s.P;return ko(H(r[u[`${n}${s}`]],r[u[`${n}${o}`]]),H(r[u[`${n}${c}`]],r[u[`${n}${s}`]]))},h=Array.from({length:Math.max(1,d-1)},(e,t)=>d>1?i-1-t:i).reduce((e,t)=>m(t)<m(e)?t:e),g=m(h),_=`${l}_${a}`,v=e.out.baked[_]?.[Math.max(0,i-1)];if(v&&G(v)<.5)return{cause:e.cause(_,i),hint:`${_}: the pole passes near zero (length ${Q(G(v))}) at f${i} while it turns between opposite keys; add an in-between pole key (e.g. the average direction, normalised) so it turns, not shrinks`};let y=g<12?`the limb is almost straight at f${h} (bend ${Q(g)} deg), so the pole cannot hold it: bring the ${r===`Leg`?`foot`:`hand`} target ~0.02 m toward the ${r===`Leg`?`hip`:`shoulder`}, or `:``;return{cause:e.cause(_,i),hint:`${_}: ${y}keep the pole on one side through f${i}${v?` (key ${kS(v)} there)`:``}`,fix:v&&{channel:_,f:i,value:v}}},SLIDE(e,t){let n=QT(t.subject),r=n===`l`?`Left`:`Right`,i=t.subject.includes(`heel`)?`heel`:`ball`,a=Math.max(0,t.first-1),o=t=>kc(e.sk,e.fr(t).s,r)[i],s=Math.hypot(o(t.last)[0]-o(a)[0],o(t.last)[2]-o(a)[2]),c=e.out.baked[`foot_${n}`]?.[a],l=e.out.baked[`fyaw_${n}`],u=e.out.baked[`foot_${n}`]?.[t.last];return l&&c&&u&&Math.hypot(u[0]-c[0],u[2]-c[2])<s/2&&Math.abs(l[t.last]-l[a])>1?{cause:e.cause(`fyaw_${n}`,t.worstFrame),hint:`fyaw_${n}: the flat foot turns ${Q(l[a])} -> ${Q(l[t.last])} deg over f${a}-f${t.last} and the ${i} slides ${Q(s)} m; key fyaw_${n} ${Q(l[a])} at f${t.last} so it turns once the foot is up, or lift the heel first (fpitch_${n} +) so it pivots on the ball`,fix:{channel:`fyaw_${n}`,f:t.last,value:l[a]}}:{cause:e.cause(`foot_${n}`,t.worstFrame),hint:`foot_${n}: hold it still over f${a}-f${t.last}${c?` (key ${kS(c)} at both ends)`:``}; the ${i} slides ${Q(s)} m${s<.01?`; fix.slide locks this when on`:``}`,fix:c&&{channel:`foot_${n}`,f:t.last,value:c}}},SPEED:(e,t)=>tE(e,t,1),POP:(e,t)=>tE(e,t,.5),ACC:(e,t)=>tE(e,t,.5),FLOAT(e,t){let n=`over f${t.first}-f${t.last} lower the root or key foot_l/foot_r back onto the ground, the floor or the top of an object under the foot (the ankle stands ${Dc(e.sk)} m above it); a jump needs the hips to rise and fall; a seat or ledge the hips rest on goes in checks.supports (a foot on an object's top needs none)`,r=iE(e,t);if(!r)return{cause:e.cause(`root`,t.worstFrame),hint:n};let i=r.presc,a=e=>(Math.round(e*100)/100).toFixed(2),o=i&&i.fits>=2&&i.fits!==i.frames;if(i)return{cause:e.cause(`root`,t.worstFrame),hint:`hips held ${a(Math.abs(i.off))} m ${i.off>0?`below`:`above`} a ballistic arc over ${i.frames} frames (f${i.from}-f${i.to}): either ${i.apex>i.height?`raise`:`lower`} the apex to ${a(i.apex)} m above takeoff${o?`, or ${i.fits<i.frames?`shorten`:`lengthen`} the air run to ${i.fits} frames for this apex (${a(i.height)} m)`:``}; or ${n}`};let{f:s,dy:c}=r;return{cause:e.cause(`root`,s),hint:`hips should be ${Math.round(Math.abs(c)*100)} cm ${c<0?`lower`:`higher`} at f${s} (ballistic arc from f${r.from} to f${r.to}): root ${kS([0,c,0])} m there${r.keys.length>1?` (keys at ${r.keys.map(e=>`f${e.f} ${kS([0,e.dy,0])}`).join(`, `)} follow the arc)`:``}; or ${n}`,fix:{channel:`root`,f:s,delta:[0,c,0],ops:t=>aE(e,t,r)}}},LENGTH:()=>({cause:`compiler`,hint:`a bone changed length: report the spec, this is a compiler fault`}),CONTACT(e,t){let n=(e.spec.checks?.contacts??[]).find(e=>t.subject.startsWith(`${e.name}:`)),r=t.worstFrame,i=e.rel(r);if(!n)return null;let a=NC(e.out,i,n.point),o=NC(e.out,i,n.target),s=H(o,a),c=/^prop:([^.]+)/.exec(n.point),l=c?e.spec.props?.[c[1]]?.hand:QT(n.point.slice(6)),{diag:u}=e.fr(r),d=Math.max(u[`reach_over_${l}`]??0,u[`arm_miss_${l}`]??0),f=/^anchor:(.+)$/.exec(n.target)?.[1],p=(e.spec.fits??[]).findIndex(e=>e.side===l&&e.anchor===f),m=p>=0?`fits[${p}] (${l} -> anchor ${f})`:ET(e,`hand_${l}`,r,s).cause,h=U(K([s[0],0,s[2]]),d+.01),g=u[`arm_fold_${l}`];if(d>.002&&g){let t=e.fr(r).s.P[e.I[`${l===`l`?`Left`:`Right`}Arm`]],n=U(K([t[0]-o[0],0,t[2]-o[2]]),d+.01);return{cause:m,hint:`inside the forearm's reach by ${Q(d)} m at f${r} (the elbow would fold ${Math.round(g)}deg; it stops at 150deg): bring root ${kS(n)} m back from ${f??`the target`}, or move the target out from the shoulder`,fix:{channel:`root`,f:r,delta:n}}}if(d>.002)return{cause:m,hint:`out of reach by ${Q(d)} m at f${r}: bring root ${kS(h)} m toward ${f??`the target`}, or move the target`,fix:{channel:`root`,f:r,delta:h}};let _=ET(e,`hand_${l}`,r,s);return{cause:m,hint:`${_.hint}${p<0&&f?`; or add fits: [{ side: "${l}", anchor: "${f}", effector: ${c?`{ prop: "${c[1]}", point: "${n.point.split(`.`)[1]}" }`:`{ joints: [...] }`} }]`:``}`,fix:_.fix}},ORIENT(e,t){let n=(e.spec.checks?.orient??[]).find(e=>t.subject.startsWith(`${e.name}:`)),r=t.worstFrame;if(!n)return null;let i=/^prop:([^.]+)/.exec(n.from),a=i?e.spec.props?.[i[1]]?.hand:QT(n.from.slice(6)),o=n.minCos??.64,s=t=>n.along===`up`?[0,1,0]:n.along===`face`?Lo(e.sk,t.s,e.I.Head,[0,0,1]):K(n.along),c=t=>W(K(H(nE(e,t,n.to),nE(e,t,n.from))),s(t)),l=Hf(e.out.baked,r),u=l[`wtwist_${a}`]??0,d=l[`wflex_${a}`]??0,{best:f,base:p}=rE(e,r,[[`wtwist_${a}`,_o(u+15,-85,85),15],[`wtwist_${a}`,_o(u-15,-85,85),15],[`wflex_${a}`,_o(d+15,-70,70),15],[`wflex_${a}`,_o(d-15,-70,70),15]],c);if(!f)return{cause:e.cause(`wtwist_${a}`,r),hint:`turn the prop another way: wrist twist/flex do not help at f${r} (cos ${Q(p)}, needs ${o}); change elbow_${a} or the prop points`};let m=f.ch.startsWith(`wtwist`)?u:d,h=f.ch.startsWith(`wtwist`)?85:70,g=_o(m+(f.value-m)*Math.min(4,(o-p+.03)/f.gain),-h,h);return{cause:e.cause(f.ch,r),hint:`${f.ch}: key ${Q(g)} deg at f${r} (now ${Q(m)}; cos ${Q(p)}, needs ${o})`,fix:{channel:f.ch,f:r,value:g}}},BELOW(e,t){let n=(e.spec.checks?.below??[]).find(e=>t.subject.startsWith(`${e.name}:`)),r=t.worstFrame;if(!n)return null;let i=QT(n.joint),a=`${/Leg/.test(n.joint)?`knee`:`elbow`}_${i}`,o=Hf(e.out.baked,r)[a]??[0,-1,-.3],s=t=>t.s.P[e.I[n.ref]][1]-t.s.P[e.I[n.joint]][1],c=(n.min??.08)+.01,l=Hf(e.out.baked,r),u=s(e.fr(r)),d=[[0,-1,0],[.5,-1,0],[-.5,-1,0],[0,-1,-.4],[0,-1,.4],[.5,-1,.5],[-.5,-1,.5],[.5,-1,-.4],[-.5,-1,-.4]].map(t=>({p:t,d:s(dS(e.out.ctx,{...l,[a]:t},r)),turn:ko(t,o)})),f=d.filter(e=>e.d>=c).sort((e,t)=>e.turn-t.turn)[0]??d.sort((e,t)=>t.d-e.d)[0];return f.d>u?{cause:e.cause(a,r),hint:`${a}: key ${kS(f.p)} (body frame: +y up, +z forward) at f${r} (${n.joint} ${Q(u)} m below ${n.ref} -> ${Q(f.d)}, needs ${n.min??.08})`,fix:{channel:a,f:r,value:f.p}}:{cause:e.cause(a,r),hint:`${a}: no pole change lowers ${n.joint} at f${r}; lower the hand target instead`}},APPEAR(e,t){let n=(e.spec.checks?.appear??[]).find(e=>t.subject.startsWith(`${e.name}:`)),r=t.worstFrame;if(!n)return null;let i=null;for(let t=Math.max(e.out.f0??0,r-24);t<=Math.min((e.out.f0??0)+e.out.frames.length-1,r+24);t++){let r=G(H(NC(e.out,e.rel(t),`joint:${n.joint}`),NC(e.out,e.rel(t),`anchor:${n.anchor}`)));(!i||r<i.d)&&(i={q:t,d:r})}let a=n.tol??.035;return{cause:e.cause(n.channel,r),hint:i.d<=a?`${n.channel}: move the step from f${r} to f${i.q} (${n.joint} ${Q(i.d)} m from ${n.anchor} there)`:`${n.joint} never gets within ${a} m of ${n.anchor} near f${r} (closest ${Q(i.d)} m at f${i.q}): hold its weight w_${n.anchor}_${QT(n.joint)} at 1 around the switch`}}},cE=.003,lE=24;function uE(e,t,n,r){let i=e.hand(t,n);if(i.ch===`hand_${t}`)return{channel:i.ch,f:n,delta:r};if(i.fit!==null&&i.fit!==void 0)return e.spec.fits[i.fit].offset?{path:`/fits/${i.fit}/offset`,delta:r}:{path:`/fits/${i.fit}/offset`,value:r};if(i.anchor&&e.spec.anchors?.[i.anchor]?.kind===`world`)return{path:`/anchors/${i.anchor}/p`,delta:r}}function dE(e,t,n,r,i){let a=ET(e,`hand_${t}`,n,r,i),o=uE(e,t,n,r);return o?{...a,fix:o}:a}function fE(e,t,n,r){let i=e.spec.anchors?.[e.hand(t,n).anchor],a=e.out.ctx.scene;return i?.kind===`object`&&[a.objects?.[i.object]?.ancestors,Jl(a)[i.object]?.ancestors,[i.object]].some(e=>e?.includes(r))}function pE(e,t){let n=J(Y(e.R),H(t,e.pos)),r=[0,e.half[1],0];return V(e.pos,J(e.R,n.map((t,n)=>_o(t,r[n]-e.half[n],r[n]+e.half[n]))))}var mE={REACH:(e,t)=>WC(e,t)??sE.REACH(e,t),GRAB(e,t){let n=t.subject.split(`:`)[0],r=t.worstFrame,i=e.spec?.objects?.[n],a={cause:`objects.${n}.grab`,hint:`${n}: move the hand to it by f${r}, or set objects.${n}.grab to the frame the hand arrives`};if(!e.out||!b_(i))return a;let o=null;for(let i=r-lE;i<=r+lE;i++){let a=rw(e.out,n,i);a!==null&&a<=t.limit&&(!o||Math.abs(i-r)<Math.abs(o[0]-r))&&(o=[i,a])}if(o)return{cause:a.cause,hint:`${n}: set objects.${n}.grab to ${o[0]} (the hand is ${(o[1]*100).toFixed(1)} cm from it there, ${(t.worst*100).toFixed(1)} cm at f${r})`,fix:{path:`/objects/${n}/grab`,value:o[0]}};let{sk:s,spec:c,scene:l}=e.out.ctx,u=w_(s,c,e.fr(r).s,i),d=sg(l,n).map(e=>pE(l.objects[e],u)).reduce((e,t)=>G(H(t,u))<G(H(e,u))?t:e),f=G(H(d,u)),p=U(H(d,u),f>1e-9?(f-t.limit/2)/f:0),m=dE(e,c.props[i.prop].hand,r,p,` (to ${n} at grab)`);return{...m,hint:`${m.hint}; or set objects.${n}.grab to the frame the hand arrives`}},COLLIDE(e,t){let[,n,r]=/^(\S+) x (.+)$/.exec(t.subject)??[],i=e.spec?.objects??{},a=b_(i[r])?r:b_(i[n])?n:null;if(!a||!e.out)return NT.COLLIDE(e,t);let o=i[a],s=e.spec.props[o.prop].hand,[c,l]=dg(e.out,o),u=t.worst-t.limit+cE,d=t.worstFrame,f=d>=c&&d<=l,p=Math.min(d,l),m=Dg(e.out,a,d)??[];if(a===r){let t=Sc.find(e=>e[0]===n),{s:r}=e.fr(d);if(!t||!m.length)return null;let i=Cc(r.P[e.I[t[1]]],r.P[e.I[t[2]]]),[o,c]=m.flatMap(e=>i.map(t=>[e,t])).reduce((e,t)=>wc(t[1],t[0])<wc(e[1],e[0])?t:e),l=Ac(c,o),p=/^(hand|farm|uarm)_([lr])$/.exec(n)?.[2];return f&&p&&p!==s&&fE(e,p,d,a)?ET(e,`hand_${p}`,d,U(l,u),` (out of ${a})`):f?dE(e,s,d,U(l,-u),` (${a} off ${n})`):ET(e,n,d,U(l,u),` (out of ${a})`)}let h=e.out.objectsAt(e.rel(d))[r];if(!h||!m.length)return null;let g=Dg(e.out,a,Math.max(c,t.first-1))??m,_=m.map((e,t)=>$C(e,h,H(g[t].pos,h.pos))).reduce((e,t)=>t.depth>e.depth?t:e);return dE(e,s,p,U(_.axis,_.depth-t.limit+cE),f?` (${a} out of ${r})`:` (${a} is put down in ${r}; it stays where the hand lets go at f${l})`)}},hE=.005,gE=e=>e.spec?.fix?.grasp===!1,_E={cause:`spec.fix.grasp false: the fingers stopped at the preset curl`,hint:`turn grasp physics on (fix.grasp true): the fingers close until they touch and the thing rests in the hand`,fix:{path:`/fix/grasp`,value:!0}};function vE(e,t,n){let{scene:r}=e.out.ctx,i=e.out.objectsAt?.(e.rel(n))??{};return sg(r,t).map(t=>({...r.objects[t],...e.out.ctx.objectPose?.(t,n)??i[t]??{}}))}var yE={FINGER_GAP(e,t){if(gE(e))return _E;let[,n,r]=/^(left|right) fingers off (\S+)$/.exec(t.subject)??[];if(!r||!e.out)return null;let i=n===`left`?`l`:`r`,a=n===`left`?`Left`:`Right`,o=t.worstFrame,{s}=e.fr(o),c=U(V(s.P[e.I[`${a}Hand`]],s.P[e.I[`${a}HandMiddle1`]]),.5),l=vE(e,r,o);if(!l.length)return null;let u=l.reduce((e,t)=>Fc(t,c)<Fc(e,c)?t:e),d=Fc(u,c);return ET(e,`hand_${i}`,o,U(Ic(u,c),-Math.max(0,d-.03)),` (onto ${r}: the fingers reach it from nearer)`)},FINGER_PEN(e,t){if(gE(e))return _E;let[,n,r]=/^(\S+) into (\S+)$/.exec(t.subject)??[];if(!r||!e.out||e.I[n]===void 0)return null;let i=n.startsWith(`Left`)?`l`:`r`,a=t.worstFrame,o=e.fr(a).s.P[e.I[n]],s=vE(e,r,a);if(!s.length)return null;let c=s.reduce((e,t)=>Fc(t,o)<Fc(e,o)?t:e);return ET(e,`hand_${i}`,a,U(Ic(c,o),t.worst-t.limit+hE),` (out of ${r})`)},THUMB_OFF(e,t){if(gE(e))return _E;let[,n,r]=/^(left|right) thumb off (\S+)$/.exec(t.subject)??[];if(!r)return null;let i=n===`left`?`l`:`r`;return{cause:e.cause(`fingers_${i}`,t.worstFrame),hint:`${r}: the thumb is ${(t.worst*100).toFixed(1)} cm off it; key fingers_${i} with the grip (or spherical) preset at 1 while the hand holds it, or set the hand so ${r} sits in the palm`}},SUPPORT(e,t){if(gE(e))return _E;let n=/^(\S+) not supported$/.exec(t.subject)?.[1],r=e.spec?.objects?.[n];if(!r||!e.out)return null;let i=e.out.ctx.scene.objects[sg(e.out.ctx.scene,n)[0]],a=i?Mc(i).kind:`box`,o=a===`sphere`?`spherical`:a===`cylinder`?`power`:`palm`;return r.grasp===o?{cause:`objects.${n}.grasp ${o}`,hint:`${n} rests on the fingers only: hold it nearer the palm (the hand lower under it) or with both hands`}:{cause:`objects.${n} (no grasp for a ${a})`,hint:`${n}: set objects.${n}.grasp to "${o}" (how a ${a} is held)`,fix:{path:`/objects/${n}/grasp`,value:o}}},CATCH(e,t){let[,n]=/^(\S+) missed by/.exec(t.subject)??[];if(!e.spec?.objects?.[n]||!e.out)return null;let r=t.worstFrame,i=e.spec.anchors?.[`${n}Catch0`]?.p;if(!i)return{cause:`objects.${n}.grab`,hint:`${n}: the hand is ${(t.worst*100).toFixed(1)} cm from it at f${r}; reach it earlier`};let a=null;for(let t=Math.max(0,r-30);t<r;t++){let r=_g(e.out,n,t)?.pos;r&&(!a||G(H(r,i))<a.d)&&(a={f:t,d:G(H(r,i))})}let o=a?r-a.f:0,s=`${n}: the hand gets there ${o} frame(s) after it passed (${(t.worst*100).toFixed(1)} cm off at f${r}); start catchObject ${o} frame(s) earlier`;return o>0?{cause:`use catchObject ${n} f0`,hint:s,fix:{ops:e=>{let t=(e.use??[]).findIndex(e=>e.skill===`catchObject`&&e.args?.object===n);return t<0?null:[{op:`replace`,path:`/use/${t}/f0`,value:Math.max(0,e.use[t].f0-o)}]}}}:{cause:`use catchObject ${n}`,hint:s}}},bE=[`add`,`remove`,`replace`,`move`,`test`],xE=e=>{throw Error(`MOTION_SPEC_INVALID: ${e}`)},SE=(e,t)=>JSON.stringify(e)===JSON.stringify(t),CE=e=>e.split(`/`).slice(1).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),wE=e=>e.map(e=>`/${String(e).replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`).join(``),TE=/^@[A-Za-z_]\w*=[^&]*(&[A-Za-z_]\w*=[^&]*)*$/,EE=e=>TE.test(e)?e.slice(1).split(`&`).map(e=>[e.slice(0,e.indexOf(`=`)),e.slice(e.indexOf(`=`)+1)]):null,DE=(e,t)=>typeof e==`object`&&!!e&&t.every(([t,n])=>Object.hasOwn(e,t)&&String(e[t])===n),OE=e=>typeof e==`object`&&!!e&&!Array.isArray(e),kE=e=>/^-?\d+(\.\d+)?$/.test(e)?Number(e):e,AE=[`name`,`skill`,`anchor`,`f`,`f0`,`side`,`type`];function jE(e,t,n){if(!Array.isArray(e)){let n=Object.keys(e);return n.length?`${t} has ${n.slice(0,8).join(`, `)}${n.length>8?`, ...`:``}`:`${t} is empty`}let r=n?.[0]??AE.find(t=>e.some(e=>e&&typeof e==`object`&&Object.hasOwn(e,t)));if(!r)return`${t} has ${e.length} entries`;let i=[...new Set(e.filter(e=>e&&Object.hasOwn(e,r)).map(e=>e[r]))],a=Number(n?.[1]),o=i.every(e=>typeof e==`number`)?(Number.isFinite(a)?[...i].sort((e,t)=>Math.abs(e-a)-Math.abs(t-a)):i).slice(0,8).sort((e,t)=>e-t):i.slice(0,8);return`${t} has ${e.length} entries; by ${r}: /${t}/@${r}=<${r}>, ${r} ${o.join(`, `)}${i.length>o.length?`, ...`:``}`}function ME(e,t,n,r,i,a){let o=EE(t),s=[];e.forEach((e,t)=>DE(e,o)&&s.push(t));let c=o.length===1&&o[0][0]===`f`;if(s.length>1&&!c){let n=AE.find(t=>!o.some(e=>e[0]===t)&&new Set(s.map(n=>e[n]?.[t])).size===s.length);xE(`${r}: ${s.length} ${i} entries have ${t.slice(1)}${n?` (${n} ${s.map(t=>e[t][n]).join(`, `)}; add &${n}=<${n}>)`:` (indices ${s.join(`, `)})`}`)}if(s.length){let t=(t,n)=>{let r=e[t];for(let e of n){if(typeof r!=`object`||!r||!Object.hasOwn(r,e))return!1;r=r[e]}return!0};return String(s.findLast(e=>t(e,n))??s.findLast(e=>t(e,n.slice(0,-1)))??s.at(-1))}if(!a)return-1;let l=Object.fromEntries(o.map(([e,t])=>[e,kE(t)]));return n.length>1&&(l[n[0]]={}),e.push(l),String(e.length-1)}function NE(e,t,n,r,i){let a=e,o=[];for(let e=0;e<t.length;e++){let s=t[e];if(Array.isArray(a)&&EE(s)&&e<t.length-1){let c=e?o[e-1]:`the spec`,l=ME(a,s,t.slice(e+1),n,c,!1);l===-1&&!r&&xE(`${n}: ${wE([...o,s])} matches nothing (${jE(a,c,EE(s)[0])})`),s=l===-1?ME(a,s,t.slice(e+1),n,c,!0):l,l===-1&&(o.created=!0,i?.push(`${n}: created ${wE(o)}/${s} (${t[e].slice(1)})`))}o.push(s),e<t.length-1&&(a=typeof a==`object`&&a?a[Array.isArray(a)?Number(s):s]:void 0)}return o}function PE(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let i=t[e],a=e?t[e-1]:`the spec`;(typeof r!=`object`||!r||!Object.hasOwn(r,Array.isArray(r)?Number(i):i)||Array.isArray(r)&&!/^\d+$/.test(i))&&xE(`${n}: ${wE(t.slice(0,e+1))} does not exist${r&&typeof r==`object`?` (${jE(r,a)})`:``}`),r=r[Array.isArray(r)?Number(i):i]}return(typeof r!=`object`||!r)&&xE(`${n}: ${wE(t.slice(0,-1))} is not an object or array`),r}function FE(e,t,n,r,i,a){let o=EE(t),s=e.flatMap((e,t)=>DE(e,o)?[t]:[]);if(n===`add`)return s.length&&xE(`${i}: ${a} already has an entry with ${t.slice(1)}; replace its fields or remove it first`),(typeof r!=`object`||!r||Array.isArray(r))&&xE(`${i}: add through a selector takes an object value`),e.push({...structuredClone(r),...Object.fromEntries(o.map(([e,t])=>[e,kE(t)]))}),null;if(s.length||xE(`${i}: ${a} has no entry with ${t.slice(1)} (${jE(e,a,o[0])})`),n===`remove`){for(let t of s.reverse())e.splice(t,1);return null}return ME(e,t,[],i,a,!1)}function IE(e,t,n,r){(!t||typeof t!=`object`||!bE.includes(t.op))&&xE(`patch[${n}]: op must be ${bE.join(`, `)}, got ${JSON.stringify(t?.op)}`);let i=`patch[${n}] (${t.op} ${t.path})`;if((typeof t.path!=`string`||t.path!==``&&!t.path.startsWith(`/`))&&xE(`${i}: path must be a JSON Pointer such as "/keys/0/f" or "/keys/@f=24/set/hand_l"`),t.op===`move`){(typeof t.from!=`string`||!t.from.startsWith(`/`))&&xE(`${i}: move needs from, a JSON Pointer such as "/keys/@f=120"`);let a=NE(e,CE(t.from),i,!1),o=a.at(-1),s=PE(e,a,i),c=a.at(-2)??`the spec`,l;if(Array.isArray(s)&&EE(o)){let e=s.flatMap((e,t)=>DE(e,EE(o))?[t]:[]);e.length||xE(`${i}: ${c} has no entry with ${o.slice(1)} (${jE(s,c,EE(o)[0])})`),l=e.map(e=>s[e]).reduce((e,t)=>Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].map(n=>[n,OE(e[n])&&OE(t[n])?{...e[n],...t[n]}:Array.isArray(e[n])&&Array.isArray(t[n])&&n===`step`?[...new Set([...e[n],...t[n]])]:Object.hasOwn(t,n)?t[n]:e[n]])));for(let t of e.reverse())s.splice(t,1)}else Object.hasOwn(s,Array.isArray(s)?Number(o):o)||xE(`${i}: ${t.from} does not exist (${jE(s,c)})`),l=s[Array.isArray(s)?Number(o):o],Array.isArray(s)?s.splice(Number(o),1):delete s[o];return IE(e,{op:`add`,path:t.path,value:l},n,r)}if(t.op!==`remove`&&!Object.hasOwn(t,`value`)&&xE(`${i}: needs a value`),t.path===``){if(t.op===`replace`)return structuredClone(t.value);if(t.op===`test`)return SE(e,t.value)||xE(`${i}: the spec differs from the test value`),e;xE(`${i}: ${t.op} needs a path below the spec`)}let a=t.op===`add`||t.op===`replace`&&!!r,o=NE(e,CE(t.path),i,a,r),s=PE(e,o,i),c=o[o.length-1],l=o.length>1?o[o.length-2]:`the spec`;if(Array.isArray(s)&&EE(c)){if(t.op===`replace`&&r&&!s.some(e=>DE(e,EE(c))))return r.push(`${i}: nothing had ${c.slice(1)}; added`),IE(e,{...t,op:`add`},n);if(c=FE(s,c,t.op,t.value,i,l),c===null)return e}if(Array.isArray(s)){if(c===`-`)return t.op!==`add`&&xE(`${i}: "-" (append) works with add only`),s.push(structuredClone(t.value)),e;let n=/^\d+$/.test(c)?Number(c):NaN,r=t.op===`add`?s.length:s.length-1;return n>=0&&n<=r||xE(`${i}: ${t.path} does not exist (${jE(s,l)})`),t.op===`add`?s.splice(n,0,structuredClone(t.value)):t.op===`remove`?s.splice(n,1):t.op===`replace`?s[n]=structuredClone(t.value):SE(s[n],t.value)||xE(`${i}: value is ${JSON.stringify(s[n])?.slice(0,60)}, not ${JSON.stringify(t.value)?.slice(0,60)}`),e}return t.op===`replace`&&r&&!Object.hasOwn(s,c)?o.created||r.push(`${i}: ${t.path} did not exist (${jE(s,l)}); added`):t.op!==`add`&&!Object.hasOwn(s,c)&&xE(`${i}: ${t.path} does not exist (${jE(s,l)})`),t.op===`remove`?delete s[c]:t.op===`test`?SE(s[c],t.value)||xE(`${i}: value is ${JSON.stringify(s[c])?.slice(0,60)}, not ${JSON.stringify(t.value)?.slice(0,60)}`):s[c]=structuredClone(t.value),e}function LE(e,t,n){return Array.isArray(t)||xE(`patch must be an array of { op, path, value }`),t.reduce((e,t,r)=>IE(e,t,r,n),structuredClone(e))}var RE=2,zE=e=>Array.isArray(e)?e.map(zE):typeof e==`number`?Math.round(e*1e4)/1e4:e,BE=e=>e.split(`/`).slice(1).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),VE=e=>e.map(e=>`/${String(e).replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`).join(``),HE=e=>typeof e==`number`&&Number.isFinite(e);function UE(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n||!Object.hasOwn(n,e))return;n=n[e]}return n}function WE(e,t){if(HE(e)&&HE(t))return e+t;if(Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every(HE)&&t.every(HE))return e.map((e,n)=>e+t[n])}function GE(e,t,n){let r=-1;return(e.keys??[]).forEach((i,a)=>{!i?.set||!Object.hasOwn(i.set,t)||!HE(i.f)||Math.abs(i.f-n)>RE||(r<0||Math.abs(i.f-n)<Math.abs(e.keys[r].f-n))&&(r=a)}),r}var KE=(e,t)=>HE(e)&&HE(t)?Math.abs(e-t)<=1e-6:Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>HE(e)&&HE(t[n])&&Math.abs(e-t[n])<=1e-6);function qE(e,t,n,r){let i=t.keys,a=e=>e>=0&&KE(i[e]?.set?.[n],i[r].set[n]),o=e?.keys?e.keys(n).map(e=>Number(/^keys\[(\d+)\]$/.exec(e.src)?.[1]??-1)):i.map((e,t)=>t).filter(e=>i[e]?.set&&Object.hasOwn(i[e].set,n)&&HE(i[e].f)).sort((e,t)=>i[e].f-i[t].f),s=o.indexOf(r);if(s<0)return[r];let c=s,l=s;for(;c>0&&a(o[c-1]);)--c;for(;l<o.length-1&&a(o[l+1]);)l+=1;return o.slice(c,l+1)}function JE(e,t,n,r){let i=/^use\[(\d+)\] standIdle$/.exec(r?.src??``),a=n.delta;if(!i||n.channel!==`root`||!Array.isArray(a)||Math.hypot(a[0],a[2])<Math.abs(a[1]))return null;let o=Number(i[1]),s=t.use?.[o],c=e.fr(r.f).c.root;if(s?.skill!==`standIdle`)return null;let l=Array.isArray(s.args?.at)?s.args.at:c&&[c[0],c[2]];if(!l)return null;let u=zE(l.map((e,t)=>e+(t===0?a[0]:t===l.length-1?a[2]:0)));return s.args?[{op:Object.hasOwn(s.args,`at`)?`replace`:`add`,path:`/use/${o}/args/at`,value:u}]:[{op:`add`,path:`/use/${o}/args`,value:{at:u}}]}function YE(e,t,n,r){let i=t.use?.[n],a=i?.args??{},o=r.delta,s=(e.fr(r.f).c.yaw??0)*Math.PI/180,c=o[0]*Math.sin(s)+o[2]*Math.cos(s);if(i?.skill!==`walkTo`||Math.abs(o[0]*Math.cos(s)-o[2]*Math.sin(s))>Math.abs(c))return null;let l=(e,t)=>[i.args?{op:Object.hasOwn(a,e)?`replace`:`add`,path:`/use/${n}/args/${e}`,value:zE(t)}:{op:`add`,path:`/use/${n}/args`,value:{[e]:zE(t)}}];if(a.steps===void 0&&Array.isArray(a.to))return l(`to`,a.to.map((e,t)=>e+(t===0?o[0]:t===a.to.length-1?o[2]:0)));let u=a.steps??8,d=u<=2?`firstStep`:`step`,f=(a[d]??(d===`step`?.5:.4))+c/Math.max(1,u-2);return u>=2&&f>.05?l(d,f):null}function XE(e,t,n){let r=e.keys(`root`),i=e=>/^keys\[\d+\]$/.test(e.src),a=r.findLastIndex(e=>e.f<=n.f);if(a<0||!i(r[a]))return null;let o=a,s=a;for(;o>0&&i(r[o-1]);)--o;for(;s<r.length-1&&i(r[s+1]);)s+=1;return r.slice(o,s+1).map(e=>{let r=Number(/\d+/.exec(e.src)[0]),i=t.keys?.[r]?.set?.root;return Array.isArray(i)&&i.length===3?{op:`replace`,path:`/keys/${r}/set/root`,value:zE([i[0]+n.delta[0],i[1],i[2]+n.delta[2]])}:null}).filter(Boolean)}function ZE(e,t,n){if(!Array.isArray(n.delta)||!e?.fr)return null;let r=e.bracket(`root`,n.f).prev,i=/^use\[(\d+)\] (standIdle|walkTo)\b/.exec(r?.src??``);if(i?.[2]===`standIdle`)return JE(e,t,n,r);if(i?.[2]===`walkTo`)return YE(e,t,Number(i[1]),n);let a=r&&XE(e,t,n);return a?.length?a:null}function QE(e,t,n){let{channel:r,f:i}=n;if(typeof r!=`string`||!HE(i))return null;if(n.hold)return ZE(e,t,n);let a=e=>n.value===void 0?WE(e,n.delta):n.value,o=GE(t,r,i);if(o>=0){let i=(n.delta===void 0?[o]:qE(e,t,r,o)).map(e=>{let n=a(t.keys[e].set[r]);return n===void 0?null:{op:`replace`,path:VE([`keys`,e,`set`,r]),value:zE(n)}});return i.includes(null)?null:i}if(!e?.fr)return null;let{prev:s,next:c}=e.bracket(r,i),l=s&&i-s.f<=RE?s:c&&c.f-i<=RE?c:null,u=n.delta!==void 0&&JE(e,t,n,l);if(u)return u;let d=a(e.fr(i).c[r]);return d===void 0?null:[{op:`add`,path:`/keys/-`,value:{f:Math.round(i),set:{[r]:zE(d)}}}]}function $E(e,t){if(typeof t.path!=`string`||!t.path.startsWith(`/`))return null;let n=BE(t.path),r=UE(e,n),i=t.delta===void 0?t.value:r===void 0&&t.path.endsWith(`/offset`)?t.delta:WE(r,t.delta);return i===void 0?null:r===void 0?UE(e,n.slice(0,-1))===void 0?n.length===2&&n[0]===`fix`?[{op:`add`,path:VE([n[0]]),value:{[n[1]]:zE(i)}}]:null:[{op:`add`,path:t.path,value:zE(i)}]:[{op:`replace`,path:t.path,value:zE(i)}]}function eD(e,t,n){let r=e.ops?e.ops(n):e.channel===void 0?e.path===void 0?null:$E(n,e):QE(t,n,e);if(!r)return null;try{return JSON.stringify(LE(n,r))===JSON.stringify(n)?null:r}catch{return null}}function tD(e,{X:t,userSpec:n}={}){if(!n||typeof n!=`object`)return e;for(let r of e)if(r.fix)try{let e=eD(r.fix,t,n);e&&(r.patch=e)}catch{}return e}var nD={...NT,...sE,...mE,...KT,...tT,...aS,...yE,...Lw};function rD(e){let t=new Map;for(let n of e.keys??[])for(let e of Object.keys(n.set??{}))t.has(e)||t.set(e,[]),t.get(e).push({f:n.f,src:n.src??`keys`,step:n.step?.includes(e)});for(let e of t.values())e.sort((e,t)=>e.f-t.f);return t}function iD(e,t,n){let r=rD(t),i={sk:e,out:t,spec:n,I:e.index,fr:e=>t.frames[Math.max(0,Math.min(t.frames.length-1,e-(t.f0??0)))],rel:e=>Math.max(0,Math.min(t.frames.length-1,e-(t.f0??0))),keys:e=>r.get(e)??[],bracket(e,t){let n=i.keys(e),r=null,a=null;for(let e of n)if(e.f<=t)r=e;else{a=e;break}return{prev:r,next:a}},cause(e,t){let{prev:n,next:r}=i.bracket(e,t);if(!n&&!r)return`${e} (not keyed)`;let a=n&&t-n.f<=2?n:r&&r.f-t<=2?r:null;return a?`${a.src} f${Math.round(a.f)} ${e}`:r?n?`${e} between ${n.src} f${Math.round(n.f)} and ${r.src===n.src?``:`${r.src} `}f${Math.round(r.f)}`:`${e} before ${r.src} f${Math.round(r.f)}`:`${e} held since ${n.src} f${Math.round(n.f)}`},hand(e,t){let r=i.fr(t).c;if(!(r[`armw_${e}`]>.5))return{label:`arm ${e} (FK: aswing_${e}/abend_${e}, or armw_${e} 1 and hand_${e})`,ch:`aswing_${e}`};let a=null;for(let[t,n]of Object.entries(r)){let r=/^w_(.+)_([lr])$/.exec(t);r&&r[2]===e&&n>.5&&(!a||n>a.w)&&(a={w:n,anchor:r[1],ch:t})}if(!a)return{label:`hand_${e}`,ch:`hand_${e}`};let o=(n.fits??[]).findIndex(t=>t.anchor===a.anchor&&t.side===e);return{label:`anchor ${a.anchor}`,ch:a.ch,anchor:a.anchor,fit:o>=0?o:null}}};return i}function aD(e,t,n,r,{limit:i=16,userSpec:a}={}){if(!r.length)return r;let o=iD(e,t,n);for(let e of r.slice(0,i))try{let t=nD[e.kind]?.(o,e);t&&(e.cause=t.cause,e.hint=t.hint),t?.fix&&Object.defineProperty(e,"fix",{value:t.fix,enumerable:!1,configurable:!0})}catch(t){e.cause=`unknown`,e.hint=`no hint (${t.message})`}return tD(r,{X:o,userSpec:a})}var oD=new Set([`ORIENT`,`BELOW`,`CLEARANCE`]),sD=e=>Math.max(0,oD.has(e.kind)?e.limit-e.worst:e.worst-e.limit),cD=e=>e.count*(1+Math.min(3,sD(e)/Math.max(Math.abs(e.limit),.01))),lD=e=>Math.round(cD(e)*100)/100,uD=/(?<![\w\-.[])[-+]?\d+(\.\d+)?|\bf\d+\b/g,dD=e=>{let t=e.subject.indexOf(`: `),n=t>=0?e.subject.slice(0,t+2):``;return`${e.kind} ${n}${e.subject.slice(n.length).replace(uD,e=>e[0]===`f`?`f#`:`#`)}`};function fD(e){for(let t of e)t.excess=Math.round(sD(t)*1e4)/1e4,t.severity=lD(t);return e.sort((e,t)=>(t.kind===`GOAL`)-(e.kind===`GOAL`)||t.severity-e.severity||t.count-e.count)}function pD(e){let t=new Map;for(let n of e){let e=dD({kind:n.kind,subject:n.msg}),r=t.get(e)??{kind:n.kind,subject:n.msg,count:0,worst:n.value,worstFrame:n.frame,first:n.frame,last:n.frame,limit:n.limit};r.count++,r.first=Math.min(r.first,n.frame),r.last=Math.max(r.last,n.frame),(oD.has(n.kind)?n.value<r.worst:n.value>r.worst)&&(r.worst=n.value,r.worstFrame=n.frame,r.subject=n.msg),t.set(e,r)}return fD([...t.values()])}function mD(e,t,n,r={}){let i=n.checks??{},a=tC(t,n.goals??[]),o=[...sd(e,t,{allow:i.allow,limits:i.limits,mouthPoints:i.mouthPoints}),...zC(t,i),...aw(e,t,n),...Tw(e,t),...Iw(e,t),...rS(e,t),...Wu(t,i),...Ku(e,t,i,{...rd,...i.limits}),...$w(e,t),...ud(e,t,i),...a.issues];if(t.f0)for(let e of o)e.frame+=t.f0;let s=pD(o);r.explain!==!1&&aD(e,t,n,s,{userSpec:r.userSpec});let c=yT(e,t);return{ok:o.length===0,total:o.length,problems:s.length,...n.goals?{goals:a.results}:{},groups:s,...c.length?{warnings:c}:{}}}var hD=[`contacts`,`orient`,`below`,`clearance`,`appear`];function gD(e){let t=e?.checks;if(!t||typeof t!=`object`||!hD.some(e=>Array.isArray(t[e])&&t[e].some(e=>e&&typeof e==`object`&&e.name===void 0)))return e;let n={...t};for(let e of hD)Array.isArray(t[e])&&(n[e]=t[e].map((t,n)=>t&&typeof t==`object`&&t.name===void 0?{...t,name:`${e}[${n}]`}:t));return{...e,checks:n}}var _D=(e,t)=>({...t,...e?{description:e}:{}}),vD=(e,t)=>_D(e,{type:`number`,...t}),yD=(e,t)=>_D(e,{type:`integer`,...t}),bD=(e,t)=>_D(e,{type:`string`,...t}),xD=(e,t)=>_D(e,{type:`boolean`,...t}),SD=(e,t)=>_D(t,{$ref:`#/$defs/${e}`}),CD=e=>_D(e,{enum:[`l`,`r`]}),wD=(e,t)=>_D(t,{type:`array`,prefixItems:[e,e],minItems:2,maxItems:2}),TD={vec3:{type:`array`,items:{type:`number`},minItems:3,maxItems:3},frameSpan:{type:`array`,items:{type:`integer`,minimum:0},minItems:2,maxItems:2,description:`[f0, f1] inclusive`},ref:{type:`string`,pattern:`^(${Ml.join(`|`)}):.+$`,description:`a point ref (topic refs)`},checkRef:{type:`string`,pattern:`^(joint|prop|anchor):.+$`,description:`joint:<Bone> | prop:<prop>.<point> | anchor:<name>`},part:{type:`string`,description:`a body capsule: ${Sc.map(e=>e[0]).join(`, `)}; allow matches a prefix (hand = hand_l and hand_r)`},when:{oneOf:[{type:`string`,description:`a weight channel: active where it is > 0.99`},{$ref:`#/$defs/frameSpan`}]}},ED={f:yD(`frame`,{minimum:0}),set:{type:`object`,description:`{ channel: value } (topic channels)`},step:{type:`array`,items:{type:`string`},description:`channels that jump at f instead of easing in`},src:bD(`written by the skills expander; leave it out`)},DD={skill:bD(`a skill name (topic skills)`),args:{type:`object`,description:`the skill's args (topic skills with name)`},f0:yD(`first frame`,{minimum:0})},OD={type:{const:`walk`},f0:yD(`first frame; needs a standing pose keyed before it`,{minimum:0}),steps:yD(`footsteps`,{minimum:1,default:8}),step:vD(`stride, m`,{default:.5}),period:yD(`frames per step`,{default:20}),swing:yD(`frames a foot is in the air`,{default:14}),halfWidth:vD(`feet half-width, m`,{default:.08}),lift:vD(`foot lift, m`,{default:.08}),heading:wD({type:`number`},`[h0, h1] degrees; ${Zc.yaw}`),turnDistance:vD(`m walked while the heading turns h0 -> h1`,{default:.4}),pelvisHigh:vD(`hips offset over the stance foot, m`),pelvisLow:vD(`hips offset at double support, m`),firstStep:vD(`first stride, m`,{default:.4}),armSwing:vD(`degrees`,{default:14}),vary:vD(`0..2, uneven steps as people walk (build-up, slow stop, left/right, turns) around the averages above; 0 = every step period frames, step m`,{default:1,minimum:0,maximum:2})},kD={schema:{const:`cozyclay.motion-spec.v1`},fps:{const:24},frames:{oneOf:[yD(null,{minimum:1,maximum:2e4}),{const:`auto`,description:`the last skill end, generator end or key f, plus 1 (open values at their upper bound); the stored spec keeps the number`}]},label:bD(`a short name for the take`),keys:{type:`array`,items:{$ref:`#/$defs/key`}},anchors:{type:`object`,description:`name -> anchor (topic anchors)`},props:{type:`object`,description:`name -> held prop (topic props)`},fits:{type:`array`,description:`topic props`},objects:{type:`object`,description:`scene object id -> hinge, carry, switch, follow or free (topic objects)`},generators:{type:`array`,items:{$ref:`#/$defs/walk`}},checks:{type:`object`,description:`topic checks`},fix:{oneOf:[{const:!1},{type:`object`}],description:`topic fix`},use:{type:`array`,items:{$ref:`#/$defs/use`}},channels:{type:`array`,items:{type:`string`},description:`extra numeric channels your keys set`},detourRadius:vD(`m; a hand moving between targets arcs around the torso this far out`,{default:.25}),search:{type:`object`,properties:{budget:yD(`compiles at most`,{minimum:1,maximum:64,default:32})},additionalProperties:!1},goals:{type:`array`,description:`topic goals`},flow:{oneOf:[{const:!1},{type:`object`}]},idle:{const:!1,description:`held poses do not breathe`}},AD={p:SD(`vec3`,`world: a world point (m); body: root-relative, ${Zc.pole}`),bone:bD(`bone name`),offset:SD(`vec3`,`world offset, m`),from:bD(`bone`),to:bD(`bone`),t:vD(`0 = from .. 1 = to`,{default:.5}),tMin:vD(`with reach: the lowest t to slide back to`,{default:.15}),reach:CD("slide toward `from` until this arm reaches"),object:bD(`scene object id`),local:SD(`vec3`,`point in the object's frame, m`),name:{const:`mouth`},prop:bD(`a prop held by the other hand`),point:bD(`a point of that prop, or origin`),person:bD(`a character id`),socket:bD(`a socket of the object`),grasp:{enum:Kc,description:`the hand takes it by a socket`}},jD=e=>SD(`vec3`,`${e} [d, l, n] on the palm axes (d to the middle finger, l to the thumb side, n = d x l), m`),MD={world:[`p`],body:[`p`],bone:[`bone`],segment:[`from`,`to`],object:[`object`],landmark:[`name`],prop:[`prop`,`point`],person:[`person`,`bone`]},ND={hand:CD(),origin:{type:`array`,items:{type:`string`},minItems:1,description:`bones whose mean is the prop origin`},points:{type:`object`,additionalProperties:jD(`point:`),description:`name -> point`}},PD={side:CD(),anchor:bD(`an anchor name`),effector:{oneOf:[{type:`object`,properties:{prop:bD(),point:bD()},required:[`prop`,`point`]},{type:`object`,properties:{joints:{type:`array`,items:{type:`string`}}},required:[`joints`]}],description:`the hand point fitted onto the anchor`},offset:SD(`vec3`,`world offset, m`),orient:{type:`boolean`,description:`false: no grip turn`}},FD={f:yD(),pos:SD(`vec3`),rot:{type:`array`,items:{type:`number`},minItems:4,maxItems:4,description:`quat xyzw`},aim:SD(`vec3`,`or rot: +Y dir`),roll:vD(`deg about aim`),lean:vD(`aim tilt`,{minimum:0,maximum:45})},ID={type:`object`,properties:{at:yD(),onto:bD(),bounce:vD(null,{default:.25,minimum:0,maximum:.6}),tumble:{type:`boolean`},v:{oneOf:[{$ref:`#/$defs/vec3`},{const:`hand`}],description:`m/s`}},required:[`at`],additionalProperties:!1},LD={description:`as carry, any frame`},RD={keys:LD,fall:LD,spring:LD},zD={type:`object`,properties:Object.fromEntries(Object.entries(yh).map(([e,t])=>[e,vD(null,{default:t.default,minimum:t.min,maximum:t.max})])),additionalProperties:!1},BD={pivot:SD(`vec3`,`world`),axis:SD(`vec3`,`default +Y`),channel:bD(`angle, deg`),prop:bD(`spec.props name`),at:SD(`vec3`,`palm offset [d, l, n]`),along:SD(`vec3`,`+Y on palm`),visible:bD(`channel: shown > 0.5`),level:bD(`channel: 0..4`),grab:yD(`hand takes it`,{default:0}),release:yD(`let go, else end`),keys:{type:`array`,items:{type:`object`,properties:Object.fromEntries(El.map(e=>[e,FD[e]])),required:[`f`,`pos`],additionalProperties:!1},description:`world pose; hand follows`},fall:{...ID,description:`or a list`},grasp:{enum:Kc},mass:vD(`kg`,{minimum:.01,maximum:60}),spring:zD,follow:SD(`ref`),offset:SD(`vec3`),aim:{oneOf:[{enum:[`face`,`up`]},{$ref:`#/$defs/vec3`},{$ref:`#/$defs/ref`}],default:`up`}},VD={name:bD(`the QA group's name`),point:SD(`checkRef`),target:SD(`checkRef`),tol:vD(`m; default contacts 0.01, appear 0.035, supports 0.04`),when:SD(`when`),from:SD(`checkRef`),to:SD(`checkRef`),along:{oneOf:[{enum:[`face`,`up`]},{$ref:`#/$defs/vec3`}]},minCos:vD(`default 0.64`),joint:bD(`bone`),ref:bD(`bone`),min:vD(`m; below default 0.08`),part:SD(`part`),object:bD(`scene object id`),frames:SD(`frameSpan`),channel:bD(`a visibility channel`),anchor:bD(`an anchor name`),depth:vD(`allowed depth, m`)},HD={contacts:[`point`,`target`],orient:[`from`,`to`,`along`],below:[`joint`,`ref`],clearance:[`part`,`object`,`min`],appear:[`channel`,`joint`,`anchor`],supports:[`object`],allow:[`part`,`object`,`depth`]},UD={limits:{type:`object`,properties:Object.fromEntries(Object.entries(rd).map(([e,t])=>[e,vD(null,{default:t})])),additionalProperties:!1},mouthPoints:{type:`array`,items:bD(`prop.point`),description:`prop points allowed at the mouth`}},WD={name:bD(),near:wD({$ref:`#/$defs/ref`},`distance <= tol`),above:wD({$ref:`#/$defs/ref`},`a.y - b.y >= by`),moved:bD("a ref or an object id: an object's base moves at least `by` from the scene pose; any other point (prop:, joint:, landmark:, anchor:) at least `by` from where it is at at[0] (at: [f0, f1])"),still:bD("a ref or an object id: stays within `tol` of where moved measures from (an object: its scene pose; a point: where it is at at[0], at: [f0, f1])"),speed:bD("a point ref: its speed reaches `by` m/s (mode any by default)"),tol:vD(`m; near default 0.05, still 0.01`),by:vD(`above m, default 0; moved m, default 0.05; speed m/s, needed`),at:{oneOf:[yD(null,{minimum:0}),{$ref:`#/$defs/frameSpan`}],description:`absolute frame or span`},mode:{enum:[`all`,`any`],description:"every frame of `at`, or one; default all, speed any"},after:bD(`a goal's name: at starts after the first frame that goal holds`),before:bD(`a goal's name: at ends before the first frame that goal holds`)},GD={name:bD(`the key of the answer`),distance:wD({$ref:`#/$defs/ref`},`min/max/mean/first/last m`),position:SD(`ref`,`world points`),frames:SD(`frameSpan`,`absolute, default the whole take`),every:yD(`position: every n frames (<= 16 rows)`,{minimum:1})},KD={reach:xD(`wrist targets past reach go onto it softly; hips lower for near-miss ankles`,{default:!0}),slide:xD(`lifts sunk soles; a planted heel or ball drifting under 1 cm stays put; a heel-up foot pivots on its ball`,{default:!0}),penetration:{oneOf:[{type:`boolean`},{type:`number`,minimum:0,maximum:.05}],default:0,description:`push hands out of boxes up to this depth, m (true = 0.02)`},self:xD(`arms kept out of the body's skin (wrists, elbows)`,{default:!0}),retime:xD(`speed spikes borrow frames from the neighbouring keys`,{default:!1}),stance:xD(`a standIdle stance in a scene body slides out of it (observations.placed)`,{default:!0}),grasp:xD(`fingers close on what the hand holds; it rests in the hand`,{default:!0}),person:xD(`arms kept out of the other characters (QA PERSON)`,{default:!0})},qD={joint:`joint:<Bone>`,bone:`bone:<Bone> (= joint:)`,prop:`prop:<prop>.<point> (origin exists)`,anchor:`anchor:<name>`,landmark:`landmark:mouth`,object:`object:<id>[.center|.top|.base|.rim], a body or group; bare = its surface (distance)`,person:`person:<id>.<Bone>`},JD=e=>e.f0+16+(e.steps??8)*(e.period??20)+18,YD=e=>({type:`array`,items:{type:`number`},minItems:2,maxItems:2,description:e}),XD=e=>Object.fromEntries(e.map(e=>[e,bD(e===`car`?`car prefix: fills <car>_Seat_Driver, _Seat_Driver_Back, _Door_L/R, _Door_Handle, _Steering_Wheel`:`scene object id (overrides the car default)`)])),ZD=Object.fromEntries(Dl.filter(e=>e!==`type`&&e!==`f0`).map(e=>[e,OD[e]])),QD={standIdle:{args:{at:YD(`[x, z] world m; default the root keyed before f0, else within reach of the next reachGrip's anchor (output.observations.placed); a stance in a body slides out of it`),heading:vD(`degrees (yaw); default the keyed yaw`),until:yD(`hold the pose to this frame`)},needs:`args.at, or a root keyed before f0`,frames:`1 (to args.until when given)`,adds:[`keys: a standing pose, FK arms down`],example:{f0:0,args:{at:[0,0],heading:0}},place:{at:.03}},walkTo:{args:{to:YD(`[x, z] world m: the heading turns toward it and the steps cover the distance (given steps, the stride or the step count and cadence is fitted to it in a natural gait, or the walk is refused)`),...ZD,heading:{oneOf:[vD(),OD.heading],description:`degrees: h1, or [h0, h1]`},arrive:yD(`with to and no steps/period/step/swing: the frame to end by (feet together); the engine picks the cadence (observations.planned)`)},needs:`a standing pose keyed before f0`,frames:`16 + steps * period + 18`,adds:[`keys: a walk ending feet together`],example:{f0:10,args:{to:[.5,1.5]}},tune:{lift:.01,halfWidth:.01,firstStep:.01,step:.01},place:{firstStep:.03,step:.03}},reachGrip:{args:{anchor:bD(`not ending in _l/_r`),side:CD(`the hand`),reach:yD(`frames to reach`,{default:20}),hold:yD(`frames held`,{default:22}),release:yD(`frames to let go`,{default:12}),elbow:SD(`vec3`,`pole`),fingers:{enum:Gc,default:`grip`},define:{type:`object`,description:`defines anchor args.anchor`},orient:{type:`boolean`,description:`false: no grip turn`}},required:[`anchor`,`side`],needs:`args.anchor in anchors or define`,frames:`reach + hold + release (54)`,adds:[`props.<anchor>Grip (fingers point)`,`fits: fingers on the anchor`,`checks.contacts "fingers on <anchor>"`,`checks.allow hand on its object`,`keys: w_<anchor>_<side>, fingers_<side>, armw_<side>`],example:{f0:10,args:{anchor:`bar`,side:`r`,define:{kind:`world`,p:[-.2,1.2,.33]}}},tune:{reach:2,release:2}},sitInSeat:{args:{...XD([`car`,`seat`,`seatBack`,`wheel`]),offset:{...SD(`vec3`,`hips from the seat top, seat frame`),default:[0,.17,.02]},floor:vD(`floor y under the feet, m`)},needs:`args.car or args.seat (a scene box)`,frames:`1`,adds:[`keys: seated, hands at the wheel`,`checks.supports seat`,`checks.allow seat, back, wheel`],example:{f0:0,args:{car:`Car`}}},exitCar:{args:{...XD([`car`,`seat`,`door`,`handle`]),side:CD(`driver door side, default l`),channel:bD(`the door hinge channel`,{default:`door`})},needs:`seated in the car before f0 (sitInSeat); a car on the ground (seat base y 0.4)`,frames:`246`,adds:[`objects: door and handle hinges`,`anchors handle, lthigh, rthigh`,`props.grip`,`fits, checks.contacts, checks.allow`],example:{f0:0,args:{car:`Car`}}},flip:{args:{kind:{enum:[`back`,`front`,`cartwheel`],default:`back`,description:`a standing back or front tuck, or a cartwheel`},travel:vD(`back/front: m along the heading at landing (default back -0.25, front 0.4)`),side:CD(`cartwheel: toward the character's l (default) or r`),heading:vD(`degrees (yaw); default the keyed yaw`)},needs:`a standing pose keyed before f0`,frames:`back/front 58 (one turn, the hips 0.5 m up); cartwheel 68`,adds:[`keys every frame: back/front crouch, push-off, a ballistic tucked flight turning the whole body (pitch to -360 back, +360 front) and a landing that stands up`,`cartwheel: a side step, then the whole body rolls 360 like a wheel on the straddled legs and the arms overhead, the hands planted in turn`,`whole-body pitch and roll take full turns in any key (no range); past 60 deg the knee and elbow poles and the feet turn with the body`],example:{f0:10,args:{kind:`back`}}},smokeCigarette:{args:{until:yD(`hold to this frame; default the last frame; under f0+264 the beats are paced to fit`),kit:{type:`object`,properties:{cig:bD(`the cigarette kit's rootId (object.createKit)`),lighter:bD(`the lighter kit's rootId`),exhale:bD(`the exhale kit's rootId (or an effect): it follows the mouth`)},required:[`cig`,`lighter`],additionalProperties:!1,description:`kits the skill carries and lights: it adds their spec.objects entries itself`}},needs:`a stand or squat keyed before f0`,frames:`265 nominal; fits 199..264 by pacing`,adds:[`anchors lpocket, rpocket, hold, mouth, flame`,`props cig, lighter`,`channels cig_vis, lit_vis, flame_vis, ember_vis, exhale, ember`,`checks contacts, orient, below, appear, mouthPoints`],example:{f0:0,args:{}}},hitReaction:{args:{dir:YD(`[x, z] the way the body is thrown`),from:bD(`or what hits it: object:<id> | person:<id> (thrown away from it)`),speed:vD(`launch speed, m/s (a shove 2, a car at 30 km/h about 8)`,{default:4,exclusiveMinimum:0}),land:{enum:[`back`,`front`],description:`default: back when hit from the front`}},needs:`a pose; dir or from`,frames:`~40`,adds:[`keys: thrown to rest`],example:{f0:10,args:{dir:[0,-1],speed:3}}},throwObject:{args:{object:bD(`the carried object's id (objects.<id>.prop on the hand's prop)`),side:CD(`the throwing hand (default r)`),to:{type:`array`,items:{type:`number`},minItems:3,maxItems:3,description:`[x, y, z] world m: where it lands`},arc:{enum:[`low`,`high`],description:`launch angle: low 20 deg, high 50 deg (default low)`}},required:[`object`,`to`],needs:`the object in that hand (its objects entry on the hand's prop)`,frames:`24 (wind-up, swing, release at f0+18, follow-through)`,adds:[`keys: wind-up, swing, follow-through`,`objects.<id>: release and fall { v: "hand" } when the entry leaves them out`,`goals: <id> lands at the target`],example:{f0:40,args:{object:`ball`,to:[0,0,5]}}},catchObject:{args:{object:bD(`the flying object's id (objects.<id>.fall { at, v })`),side:{enum:[`r`,`both`],description:`the right hand, or both (a thing over 1 kg takes both)`}},required:[`object`],needs:`the object flying: objects.<id>.fall { at, v }`,frames:`to the catch (the first frame in reach, at least 10 from f0) + 14`,adds:[`keys: reach, close, give with it`,`objects.<id>: prop, grab, grasp when the entry leaves them out`,`props.<id>Catch`],example:{f0:0,args:{object:`ball`}}}},$D={_l:`_r`,_r:`_l`},eO=/^(yaw|roll|spine_yaw|spine_roll|head_yaw|head_roll|fyaw_[lr]|wtwist_[lr]|wflex_[lr])$/,tO=/^(root|foot_[lr]|hand_[lr])$/,nO=/^(knee|elbow)_[lr]$/,rO=/^(yaw|fyaw_[lr])$/,iO=e=>e&&typeof e==`object`?structuredClone(e):e,aO=e=>e.replace(/_(l|r)$/,e=>$D[e]).replace(/^(Left|Right)/,e=>e===`Left`?`Right`:`Left`),oO=()=>({origin:[0,0,0],yaw:0,mirror:!1,negate:new Set,names:{}}),sO=(e,t)=>V(e.origin,J(X(e.yaw),e.mirror?[-t[0],t[1],t[2]]:t)),cO=(e,t)=>e.mirror?[-t[0],t[1],t[2]]:t.slice();function lO(e,t){if(!e.mirror)return t;let n=/^w_(.+)_([lr])$/.exec(t);return n?`w_${e.names[n[1]]??n[1]}_${n[2]===`l`?`r`:`l`}`:/_[lr]$/.test(t)?aO(t):t}function uO(e,t){let n={};for(let[r,i]of Object.entries(t)){let t=iO(i);tO.test(r)?t=sO(e,t):nO.test(r)?t=cO(e,t):typeof t==`number`&&(e.mirror&&(eO.test(r)||e.negate.has(r))&&(t=-t),rO.test(r)&&(t+=e.yaw)),n[lO(e,r)]=t}return n}function dO(e,t=0,n=oO()){let r=[],i=e=>lO(n,e);return{state:e,keys:r,frame:n,at(i,a){let o=uO(n,a);Object.assign(e,iO(o)),r.push({f:t+i,set:o})},hold(n,...a){r.push({f:t+n,set:Object.fromEntries(a.filter(t=>e[i(t)]!==void 0).map(t=>[i(t),iO(e[i(t)])]))})},step(n,a,o){let s=i(a);r.push({f:t+n-1,set:{[s]:e[s]}}),e[s]=o,r.push({f:t+n,set:{[s]:o},step:[s]})}}}var fO=(e,t)=>{throw Error(`MOTION_SPEC_INVALID: ${e}: ${t}`)};function pO(e,t,n){let r=e.scene?.objects?.[n];return r||fO(e.tag,`args.${t} "${n}" is not a scene object`),r}var mO=e=>Math.atan2(e[0][2],e[2][2])*180/Math.PI,hO=.01,gO=.12,_O=.8,vO=.01,yO=.15,bO=.62,xO=[`Left`,`Right`].flatMap(e=>[[`${e}UpLeg`,`${e}Leg`,.07],[`${e}Leg`,`${e}Foot`,.05],[`${e}Foot`,`${e}ToeBase`,.045],[`${e}ToeBase`,`${e}Toe_End`,.04]]).concat([[`LeftUpLeg`,`RightUpLeg`,.095],[`Hips`,`Spine2`,.12]]),SO=[[0,-1],[1,0],[-1,0],[Math.SQRT1_2,-Math.SQRT1_2],[-Math.SQRT1_2,-Math.SQRT1_2]];function CO(e,t,n){let r=e.index,i=e.restWorldPos,a=i[r.Hips],o=X(n),s=e=>V([t[0],0,t[1]],J(o,[e[0]-a[0],e[1],e[2]-a[2]])),c=(e,t,n)=>[0,.25,.5,.75,1].map(r=>[V(e,H(t,e).map(e=>e*r)),n]),l=[`Left`,`Right`].flatMap(e=>{let t=i[r[`${e}Arm`]],n=Math.sign(t[0]-a[0])*.04;return c(s(t),s([t[0]+n,t[1]-bO,t[2]]),.045)});return xO.filter(([e,t])=>r[e]!==void 0&&r[t]!==void 0).flatMap(([e,t,n])=>c(s(i[r[e]]),s(i[r[t]]),n)).concat(l)}var wO=e=>Object.values(e?.objects??{}).filter(e=>e.half&&e.pos&&e.R&&e.pos[1]+2*e.half[1]*e.R[1][1]>gO);function TO(e,t,n,r){let i=1/0;for(let[a,o]of CO(e,n,r))for(let e of t)i=Math.min(i,wc(a,e)-o-hO);return i}function EO(e,t,n,r){let i=wO(t);if(!i.length||TO(e,i,n,r)>=0)return null;let a=X(r);for(let t=vO;t<=.600000001;t+=vO)for(let[o,s]of SO){let c=J(a,[o*t,0,s*t]),l=[n[0]+c[0],n[1]+c[2]];if(TO(e,i,l,r)>=0)return{at:l.map(e=>+e.toFixed(4)),moved:+t.toFixed(2)}}return null}function DO(e,t,n,r,i=new Set){let a=wO({objects:Object.fromEntries(Object.entries(t?.objects??{}).filter(([e])=>!i.has(e)))});return a.length?TO(e,a,n,r):1/0}function OO(e,t){if(t?.kind===`world`&&Array.isArray(t.p))return t.p;if(t?.kind!==`object`||!e)return null;let n=e.objects?.[t.object]??e.groups?.[t.object];if(!n)return null;if(!t.grasp||t.local)return V(n.pos,J(n.R,t.local??[0,0,0]));let r=sg(e,t.object).map(t=>e.objects[t]).filter(e=>e?.half).map(e=>V(e.pos,J(e.R,[0,e.half[1],0])));return r.reduce((e,t)=>V(e,t.map(e=>e/r.length)),[0,0,0])}function kO(e){let{sk:t,scene:n,use:r=[],index:i=-1}=e,a=r.slice(i+1).find(e=>e?.skill===`reachGrip`),o=OO(n,a&&(a.args?.define??e.anchors?.[a.args?.anchor]));if(!o)return null;let s=t.index,c=t.restWorldPos,l=a.args.side===`l`?`Left`:`Right`,u=c[s.Hips],d=c[s[`${l}Arm`]],f=G(H(c[s[`${l}ForeArm`]],d))+G(H(c[s[`${l}Hand`]],c[s[`${l}ForeArm`]]))+G(H(c[s[`${l}HandMiddle2`]],c[s[`${l}Hand`]])),p=d[1]-o[1],m=Math.max(yO,Math.sqrt(Math.max(0,(_O*f)**2-p*p))),h=e.args.heading??e.state?.yaw??0,g=X(h),_=wO(n),v=J(g,[d[0]-u[0],0,d[2]-u[2]+m]),y=[o[0]-v[0],o[2]-v[2]],b=0,x=y;for(;b<=.600000001&&TO(t,_,x,h)<0;b+=vO){let e=J(g,[0,0,-(b+vO)]);x=[y[0]+e[0],y[1]+e[2]]}return{at:x.map(e=>+e.toFixed(4)),heading:h,anchor:a.args.anchor,moved:+b.toFixed(2)}}function AO(e){let t=Fy(e,1/0);return[(t.foot_l[0]+t.foot_r[0])/2,(t.foot_l[2]+t.foot_r[2])/2]}var jO=e=>Math.round(e*100)/100,MO=e=>`[${e.map(jO).join(`, `)}]`,NO=[.3,.85],PO=[.18,.85],FO=[1,1.8],IO=.47,LO=[.7,1.4],RO=.1,zO=20,BO=.5,VO=.12,HO=1.7,UO=Math.cos(Math.PI/3),WO=.65,GO=.05,KO=e=>{let t=e.restWorldPos,n=e.index;return G(H(t[n.LeftLeg],t[n.LeftUpLeg]))+G(H(t[n.LeftFoot],t[n.LeftLeg]))};function qO(e,t){let n=e.scene,r=new Set,i=e=>{let t=n?.objects?.[e]?.ancestors?.at(-1)??e;for(let e of sg(n,t))r.add(e)};for(let t of(e.use??[]).filter((t,n)=>n!==e.index&&t?.f0>=e.f0&&t?.skill===`sitInSeat`))for(let e of[t.args?.seat,t.args?.seatBack,t.args?.car].filter(e=>typeof e==`string`))i(e);for(let[i,a]of Object.entries(e.objects??{}))if(Number.isFinite(a?.grab)&&a.grab<=t&&!(a.release<e.f0))for(let e of sg(n,i))r.add(e);return r}function JO(e,t){let n=e.R,r=t[0]-e.pos[0],i=t[1]-e.pos[2],a=n[0][0]*r+n[2][0]*i,o=n[0][2]*r+n[2][2]*i,s=Math.max(-e.half[0],Math.min(e.half[0],a)),c=Math.max(-e.half[2],Math.min(e.half[2],o)),l=[e.pos[0]+n[0][0]*s+n[0][2]*c,e.pos[2]+n[2][0]*s+n[2][2]*c];return[Math.hypot(t[0]-l[0],t[1]-l[1]),l]}function YO(e,t,n,r,i,a,o){let s=[t[0]+n[0]*r,t[1]+n[1]*r],c=KO(e.sk),l=Object.entries(e.scene?.objects??{}).filter(([e,t])=>!i.has(e)&&t.half&&t.pos&&t.R&&t.pos[1]<HO&&t.pos[1]+2*t.half[1]*t.R[1][1]>VO).map(([e,t])=>{let[n,r]=JO(t,s);return{id:e,o:t,dist:n,q:r,low:t.pos[1]+2*t.half[1]*t.R[1][1]<WO*c}}).filter(e=>e.dist<a&&(e.dist<1e-6||(e.q[0]-s[0])*n[0]+(e.q[1]-s[1])*n[1]>=UO*e.dist)).sort((e,t)=>e.dist-t.dist);if(!l.length)return null;let u=e=>[t[0]+n[0]*e,t[1]+n[1]*e],d=new Set(Object.keys(e.scene.objects).filter(e=>!l.some(t=>t.id===e&&!t.low))),f=t=>l.some(e=>e.low&&JO(e.o,u(t))[0]<a)||l.some(e=>!e.low)&&DO(e.sk,e.scene,u(t),o,d)<GO;if(!f(r))return null;let p=r;for(;p>0&&f(p);)p-=.01;return p>.1?{t:p,at:u(p),near:l[0].id,gap:JO(l[0].o,u(p))[0]}:null}var XO=(e,t)=>Math.min(e.fit.last??1/0,...(e.use??[]).filter((t,n)=>n!==e.index&&t?.f0>e.f0).map(e=>e.f0),...e.keys.filter(e=>e.f>t&&/^keys\[/.test(e.src??``)).map(e=>e.f),...(e.fit.busy??[]).filter(e=>e>t));function ZO(e,t,n,r,i){let{args:a,tag:o,sk:s}=e,c=t.steps,l=Array.isArray(a.heading)?a.heading[1]:a.heading,u=l===void 0?0:Math.abs(((l-i)%360+540)%360-180);if(u>zO)return e.fit.refusals.push(`${o}: heading ${l} points ${Math.round(u)} deg away from to ${MO(a.to)} (it lies at heading ${Math.round(i)}), so the walk would not go there; with to the walk turns toward it by itself: leave heading out, or give heading without to to walk that way`),{gen:t};let d=t.period??20,f=t.swing??14,p=t.step??.5,m=t.firstStep??.4;if(a.steps===void 0||a.arrive!==void 0||!(c>=2)||![c,d,f,p,m].every(Number.isFinite))return{gen:t};let h=[Math.sin(i*Math.PI/180),Math.cos(i*Math.PI/180)],g=!e.fit.noStop?.has(e.index)&&YO(e,n,h,r,qO(e,e.f0+16+c*d+18),BO*KO(s),i),_=g&&QO(e,t,n,h,g.t,g);return _&&!_.refuse&&e.fit.stopped?.add(e.index),(!_||_.refuse)&&(_=QO(e,t,n,h,r,null)),_.refuse&&e.fit.refusals.push(_.refuse),{gen:_.gen,..._.adjust?{adjust:_.adjust}:{}}}function QO(e,t,n,r,i,a){let{args:o,tag:s,sk:c}=e,l=t.steps,u=t.period??20,d=t.swing??14,f=t.step??.5,p=t.firstStep??.4,m=a?`${MO(a.at)}, ${jO(a.gap)} m before ${a.near} (to ${MO(o.to)} is against it)`:`to ${MO(o.to)}`,h=t=>{let i=AO(Iy(t,e.keys,c,s));return{end:i,along:(i[0]-n[0])*r[0]+(i[1]-n[1])*r[1]}},{end:g,along:_}=h(t);if(Math.abs(i-_)<=.1)return{gen:t};let v=e.fps??24,y=KO(c),b=IO*y,x=l*u,S=e=>(e>=3?NO:PO).map(e=>jO(e*y)),C=Math.ceil(v/FO[1]),w=Math.floor(v/FO[0]),T=e.fit.stretch===!0&&!(e.use??[]).some((t,n)=>n!==e.index&&t?.f0>e.f0)&&!e.keys.some(t=>t.f>e.f0&&/^keys\[/.test(t.src??``)),E=_-p-(l-2)*f,D=o.firstStep===void 0?p/f:0,O=(e,t)=>{let n=t??(T||e===l?u:Math.min(Math.max(w,u),Math.floor(x/e))),r=e>=3?`step`:`firstStep`,a=e>=3?(i-E-(D?0:p))/(D+e-2):i-E,o=e>=3&&D?D*a:p,[s,c]=S(e),d=a*n/v/b,f=(e,[t,n])=>e>=t&&e<=n;return{n:e,p:n,name:r,value:a,ratio:d,ok:f(a,[s,c])&&f(o,S(2))&&(n===u||f(n,[C,w]))}},k=O(l),ee=Math.min(60,Math.ceil(i/S(3)[0])+2),A=k.ok&&k.ratio>=LO[0]&&k.ratio<=LO[1]?k:null,te,ne,re=e=>Math.abs(Math.log(e.ratio))+RO*Math.abs(e.n-l),ie=e=>e.filter(e=>e.ok).sort((e,t)=>re(e)-re(t)||e.n-t.n)[0],ae=Array.from({length:ee-1},(e,t)=>t+2);if(A||=ie(ae.map(e=>O(e))),!A&&!T&&(te=XO(e,e.f0+16+x),A=ie(ae.filter(e=>e>l).map(t=>O(t,Math.min(u,Math.floor((te-e.f0-34)/t)))).filter(e=>e.p>=C&&e.n*e.p>x))),!A){let[e,n]=S(l),r=Math.min(n,Math.max(e,k.value)),a=r*u/v/b,o=l>=3&&D?D*r:p,s={...t,[k.name]:jO(r),...l>=3&&D?{firstStep:jO(o)}:{}},c=a>=LO[0]&&a<=LO[1]&&o>=S(2)[0]&&o<=S(2)[1]?i-h(s).along:1/0;Math.abs(c)<=.1&&({pick:A,short:ne}={pick:{...k,value:jO(r),ratio:a},short:c})}let[oe,se]=S(3),ce=`a natural gait (step ${oe}..${se} m, ${FO[0]}..${FO[1]} steps a second: period ${C}..${w} at ${v} fps`,le=`${jO(Math.abs(i-_))} m ${_<i?`short of`:`past`} ${a?`the point ${MO(a.at)} clear of ${a.near} before to ${MO(o.to)}`:`to ${MO(o.to)}`} (${jO(i)} m away)`;if(!A){let n=2+Math.ceil((i-E-p)/se-1e-9),r=e.f0+16+n*C+18;return{gen:t,refuse:`${s}: steps ${l} at period ${u} (${x} frames of stepping) walk ${jO(_)} m and end at ${MO(g)}, ${le}; ${_<i?`in ${ce}) that takes ${n} steps and ${n*C} frames of stepping or more (the walk would end at f${r} or later, not f${e.f0+16+x+18}): leave steps${o.step===void 0?``:` and step`} out (walkTo picks the count), or give steps: ${n} and room for the walk before what follows`:`no natural step count ends there: leave steps out (walkTo picks the count)`}`}}let ue=A.p===u?{}:{period:A.p,swing:Math.max(2,Math.min(A.p-1,Math.round(d*A.p/u)))},de=A.n>=3&&D>0,fe=e=>({[A.name]:jO(e),...de?{firstStep:jO(D*e)}:{}}),pe={...t,steps:A.n,...ue,...fe(A.value)},me=ne??i-h(pe).along;ne===void 0&&Math.abs(me)>.02&&(pe={...pe,...fe(A.value+me/(A.n>=3?D+A.n-2:1))});let he=pe[A.name],ge=A.name===`step`?f:p,_e=e.f0+16+x+18,ve=e.f0+16+A.n*A.p+18,ye=[A.n!==l&&`steps ${l} -> ${A.n}`,ue.period&&`period ${u} -> ${ue.period} (swing ${d} -> ${ue.swing})`,`${A.name} ${ge} -> ${he} m`,de&&pe.firstStep!==p&&`firstStep ${p} -> ${pe.firstStep} m`].filter(Boolean).join(`, `),be=ve===_e?``:`; it ends f${ve}, not f${_e} (${T?`nothing follows it`:ve>_e?`nothing uses f${_e+1}-f${ve}`:`the pose holds to f${_e}`})`,xe=`steps ${l} would need a ${k.name} of ${jO(k.value)} m at ${jO(v/u)} steps a second`,Se=ne===void 0?A.n===l&&!ue.period?` (at ${A.name} ${ge} they walk ${jO(_)} of ${jO(i)} m)`:` in ${ce}; ${xe})${be}`:` (${ce}; ${xe})`,Ce=ne===void 0?`end at ${m}`:`end ${jO(Math.abs(ne))} m ${ne>0?`short of`:`past`} ${m}, the ${ne>0?`longest`:`shortest`} natural step`,we={args:{...A.n===l?{}:{steps:A.n},...ue,[A.name]:he,...de&&pe.firstStep!==p?{firstStep:pe.firstStep}:{}},note:`${s}: ${ye}, so steps ${A.n} ${Ce}${Se}`};return{gen:pe,adjust:we}}var $O=.65,ek=.75,tk=.75,nk=.025,rk=.1,ik=.08,ak=.12,ok=.4,sk=.3,ck=[.15,.3,.45,.6,.7,.8,.9],lk=e=>e*e*e*(10-15*e+6*e*e),uk=.9,dk=.7,fk=(e,t)=>{let n=Math.min(1,Math.max(0,e));return n<dk?uk*lk((n/dk)**+t):uk+.09999999999999998*lk((n-dk)/.30000000000000004)},pk=e=>[...new Map(ck.map(t=>Math.round(t*e)).filter(t=>t>0&&t<e).map(t=>[t,[fk(t/e,$O),fk(t/e,ek)]])).entries()].map(([e,[t,n]])=>[e,t,n]),mk=180/Math.PI,hk=(e,t,n)=>Math.max(t,Math.min(n,e));function gk(e,t){let n=_k(e,t),r=e.sk.index;return!!n&&n[1]>=e.sk.restWorldPos[r.LeftLeg][1]+rk}function _k(e,t){if(t?.kind===`world`&&Array.isArray(t.p))return t.p.map(Number);let n=t?.kind===`object`?e.scene?.objects?.[t.object]:null;return!n||[t.object,...n.ancestors??[]].some(t=>vk(e,t))?null:V(n.pos,J(n.R,t.local??[0,n.half?.[1]??0,0]))}function vk(e,t){let n=e.objects?.[t];return!n||typeof n!=`object`?!1:n.follow!==void 0||n.hinge!==void 0||Math.min(...(n.keys??[]).map(e=>e.f).filter(Number.isFinite),n.fall?.at??1/0)<(e.until??1/0)}var yk=new WeakMap;function bk(e){if(!yk.has(e)){let t=Mo(e),n=e.index;is(e,t,`Right`,{}),yk.set(e,G(H(t.P[n.RightHandThumb4],t.P[n.RightHandIndex4])))}return yk.get(e)}function xk(e,t){let n=e.scene?.objects??{};if(t?.kind===`object`)return n[t.object]?.half?n[t.object]:null;if(t?.kind!==`world`||!Array.isArray(t.p))return null;let r=t.p.map(Number);return Object.values(n).filter(e=>e.half&&wc(r,e)<=.01).sort((e,t)=>wc(r,e)-wc(r,t))[0]??null}function Sk(e,t,n,r){let i=n[0]-t[0],a=n[2]-t[2],o=Math.hypot(i,a);if(o<1e-6)return!1;let s=[t[0]+i/o*ik,t[1],t[2]+a/o*ik];return Object.entries(e.scene?.objects??{}).some(([e,t])=>{if(!t.half||r.has(e)||r.has(t.parent))return!1;let n=H(s,[0,ak,0]);return wc(s,t)>0&&wc(n,t)<=0})}function Ck(e,t,n){let r=xk(e,t),i=_k(e,t)??(r&&V(r.pos,J(r.R,[0,r.half[1],0])));if(!r||!i||2*Math.min(...r.half)+nk>bk(e.sk))return!1;let a=new Set(Object.entries(e.scene.objects).filter(([,e])=>e===r).map(([e])=>e));return!(Array.isArray(n.root)&&Sk(e,i,n.root,a))}function wk(e,t,n){let r=_k(e,t),i=n.root;if(!r||!Array.isArray(i))return null;let a=e.sk.restWorldPos,o=e.sk.index,s=[i[0],i[1]+a[o.Head][1]-a[o.Hips][1],i[2]],c=[r[0]-s[0],r[1]-s[1],r[2]-s[2]],l=Math.hypot(c[0],c[2]);if(l<.05)return null;let u=Math.atan2(c[0],c[2])*mk-(n.yaw??0)-(n.spine_yaw??0);for(;u>180;)u-=360;for(;u<-180;)u+=360;let d=Math.atan2(-c[1],l)*mk-(n.pitch??0)-(n.spine_pitch??0);return{head_yaw:hk(tk*u,-60,60),head_pitch:hk(tk*d,-30,50)}}var Tk=(e,t,n)=>e.some(e=>e.f>=t&&e.f<=n&&(e.set?.head_yaw!==void 0||e.set?.head_pitch!==void 0)),Ek=(e,t)=>Jc[e]?Jc[e].map((e,n)=>n===2&&t===`r`?-e:e):[0,0,0];function Dk(e){let{sk:t,args:n,state:r}=e,i=t.index,a=t.restWorldPos,o=a[i.LeftFoot][1],s=n.heading??r.yaw??0,c=n.at??(r.root?[r.root[0],r.root[2]]:null),l=null;if(!c){let t=kO(e);t||fO(e.tag,`needs args.at: [x, z] (no root is keyed before f0), or a reachGrip after it to stand within reach of`),{at:c,heading:s}=t,l={at:c,heading:s,why:`within reach of anchor ${t.anchor}`}}else if(n.at&&e.place!==!1){let n=EO(t,e.scene,[c[0],c[c.length-1]],s);n&&(c=n.at,l={at:c,heading:s,why:`moved ${n.moved} m out of a scene body`})}let u=[c[0],0,c[c.length-1]],d=X(s),f=e=>{let t=V(u,J(d,e));return t[1]=o,t},p={root:[u[0],a[i.Hips][1]-.01,u[2]],yaw:s,pitch:0,roll:0,spine_yaw:0,spine_pitch:0,spine_roll:0,head_yaw:0,head_pitch:0,foot_l:f([.09,0,-.03]),foot_r:f([-.09,0,.03]),fyaw_l:s,fyaw_r:s,fpitch_l:0,fpitch_r:0,knee_l:[.05,0,1],knee_r:[-.05,0,1],armw_l:0,armw_r:0,aswing_l:0,aswing_r:0,abend_l:0,abend_r:0,arm_hang:1},m=[{f:e.f0,set:p}];return n.until!==void 0&&m.push({f:n.until,set:structuredClone(p)}),{keys:m,end:n.until??e.f0,...l?{placed:l}:{}}}function Ok(e){let{args:t,state:n}=e;(!n.foot_l||!n.foot_r||!n.root)&&fO(e.tag,`needs a standing pose keyed before f0 (use standIdle or another skill first)`);let r={type:`walk`,f0:e.f0,...t},i,a,o;delete r.to,delete r.arrive;let s=n.yaw??0,c=t.step??.5,l=t.firstStep??.4;if(t.to){a=[(n.foot_l[0]+n.foot_r[0])/2,(n.foot_l[2]+n.foot_r[2])/2];let u=t.to[0]-a[0],d=t.to[t.to.length-1]-a[1],f=Math.hypot(u,d);for(o=Math.atan2(u,d)*180/Math.PI;o-s>180;)o-=360;for(;o-s<-180;)o+=360;r.heading=t.heading??[s,o],r.steps=t.steps??Math.max(2,2+Math.round((f-l)/c)),typeof r.heading==`number`&&(r.heading=[s,r.heading]),e.fit&&f>.1&&({gen:r,adjust:i}=ZO(e,r,a,f,o))}typeof r.heading==`number`&&(r.heading=[s,r.heading]);let u=Iy(r,e.keys,e.sk,e.tag),d=JD(r),f=e.frames-1,p=t.to&&AO(u),m=p?Math.hypot(p[0]-t.to[0],p[1]-t.to[t.to.length-1]):0,h={...m>.1?{placed:{at:p.map(jO),heading:Math.round(r.heading?.[1]??s),why:`ends ${jO(m)} m from to ${MO(t.to)}`}}:{},...i?{adjust:i}:{}};return d>f&&Math.max(...u.filter(e=>e.f<d).map(e=>e.f))<=f?{keys:u.filter(e=>e.f<=f),end:f,cut:`settle cut at f${f} (hold to the end)`,...h}:{keys:u,end:d,...h}}function kk(e={},t,n,r){let i=t=>e[t]&&JSON.stringify(e[t])!==JSON.stringify(r);if(!i(t))return t;let a=`${t}_${n}`;for(let e=2;i(a);e++)a=`${t}_${n}${e}`;return a}var Ak=(e,t)=>{let n=e?.objects??{};if(!t||n[t]||t.startsWith(`person:`))return t?[t]:[];let r=Object.keys(n).filter(e=>n[e].ancestors?.includes(t));return r.length?r:[t]};function jk(e){let{args:t,state:n}=e,r=t.side,i=t.anchor;r!==`l`&&r!==`r`&&fO(e.tag,`args.side must be "l" or "r", got ${JSON.stringify(r)}`),(typeof i!=`string`||/_[lr]$/.test(i))&&fO(e.tag,`args.anchor must name an anchor (not ending in _l/_r)`);let a=t.reach??20,o=t.hold??22,s=t.release??12,c=(t.define??e.anchors?.[i])?.grasp,l=t.fingers??qc[c]??`grip`,u=`w_${i}_${r}`,d=`fingers_${r}`,f=`armw_${r}`,p=`elbow_${r}`,m=!(n[f]>.5),h=e.frames-1,g=e.f0+a<=h&&e.f0+a+o+s>h,_=Math.min(a+o,h-e.f0);for(let[e,t]of[[u,0],[d,{[l]:0}],[f,0]])n[e]===void 0&&(n[e]=t);let v=a+o+s,y={...e,until:e.f0+a},b=!Tk(e.keys??[],e.f0,e.f0+v)&&wk(y,t.define??e.anchors?.[i],n),x=b?{head_yaw:n.head_yaw??0,head_pitch:n.head_pitch??0}:null,S=dO(n,e.f0);S.hold(0,u,d,f,p,...b?[`head_yaw`,`head_pitch`]:[]);let C=t.define??e.anchors?.[i],w=n[u],T=n[f],E=(e,t,n)=>e+(t-e)*n;if(gk(y,C))for(let[e,t,n]of pk(a))S.at(e,{[u]:E(w,1,t),[f]:E(T,1,n)});let D=Math.round(ok*a);D>0&&D<a&&Ck(y,C,n)&&S.hold(D,d),b&&S.at(Math.max(1,Math.round(sk*a)),b),S.at(a,{[u]:1,[d]:{...n[d],[l]:1},[f]:1,...t.elbow?{[p]:t.elbow}:{}}),S.hold(_,u,d,f,p,...b?[`head_yaw`,`head_pitch`]:[]),g||S.at(v,{[u]:0,[d]:{...n[d],[l]:0},...m?{[f]:0}:{},...x??{}});let O=r===`l`?`Left`:`Right`,k={hand:r,origin:[`${O}HandIndex2`,`${O}HandMiddle2`],points:{fingers:Ek(c,r)}},ee=kk(e.props,`${i}Grip`,r,k),A=t.define?{[i]:t.define}:{},te=t.define??e.anchors?.[i],ne=te?.kind===`object`?te.object:te?.kind===`person`?`person:${te.person}`:null;return{keys:S.keys,end:g?h:e.f0+a+o+s,...g?{cut:`${_<a+o?`hold`:`release`} cut at f${h} (hold to the end)`}:{},anchors:A,props:{[ee]:k},fits:[{side:r,anchor:i,effector:{prop:ee,point:`fingers`},...t.orient===!1?{orient:!1}:{}}],checks:{contacts:[{name:`fingers on ${i}`,point:`prop:${ee}.fingers`,target:`anchor:${i}`,tol:.04,when:u}],allow:Ak(e.scene,ne).map(e=>({part:`hand`,object:e,depth:.04}))}}}var Mk=[.54,.4,-.075],Nk=.4,Pk=1.0427487182617188,Fk=new Set([`l`,`r`]);function Ik(e,t=`l`){let n=e.car;return{seat:e.seat??(n&&`${n}_Seat_Driver`),seatBack:e.seatBack??(n&&`${n}_Seat_Driver_Back`),door:e.door??(n&&`${n}_Door_${t.toUpperCase()}`),handle:e.handle??(n&&`${n}_Door_Handle`),wheel:e.wheel??(n&&`${n}_Steering_Wheel`)}}function Lk(e,t,n){let r=pO(e,`seat`,t);Math.abs(r.pos[1]-Nk)>.05&&fO(e.tag,`seat "${t}" stands at y ${r.pos[1]}; the car skills are tuned for a seat base at y ${Nk} (a car on the ground)`);let i=oO();i.yaw=mO(r.R),i.mirror=n===`r`;let a=H(r.pos,J(X(i.yaw),i.mirror?[-Mk[0],Mk[1],Mk[2]]:Mk));return i.origin=[a[0],0,a[2]],i.names={lthigh:`rthigh`,rthigh:`lthigh`},i}var Rk=[[`hand`,`thigh*`,.07],[`farm`,`thigh*`,.07],[`hand`,`hips`,.07],[`farm`,`hips`,.07],[`hand_l`,`hand_r`,.035]].map(([e,t,n])=>({part:e,object:t,depth:n})),zk=e=>({A:e.restWorldPos[e.index.LeftFoot][1],H:t=>t+(e.restWorldPos[e.index.Hips][1]-Pk)});function Bk(e){let{args:t,sk:n}=e,r=Ik(t),i=pO(e,`seat`,r.seat),{A:a}=zk(n),o=mO(i.R),s=e=>J(X(o),e),c=t.offset??[0,.17,.02],l=t.floor??i.pos[1],u=V(V(i.pos,J(i.R,[0,2*i.half[1],0])),s(c)),d=e=>{let t=V(u,s([e,0,.452]));return t[1]=l+a,t},f=e=>V(u,s([e,.348,.324])),p={root:u,yaw:o,pitch:0,spine_pitch:-12,spine_yaw:0,spine_roll:0,head_yaw:0,head_pitch:10,foot_l:d(.17),foot_r:d(-.17),fyaw_l:o,fyaw_r:o,fpitch_l:0,fpitch_r:0,knee_l:[.15,.2,1],knee_r:[-.15,.2,1],armw_l:1,armw_r:1,hand_l:f(.22),hand_r:f(-.22),elbow_l:[.6,-1,-.3],elbow_r:[-.6,-1,-.3],aswing_l:0,aswing_r:0,abend_l:0,abend_r:0,wtwist_l:0,wtwist_r:0,wflex_l:0,wflex_r:0},m=[{part:`torso_lo`,object:r.seat,depth:.04},{part:`hips`,object:r.seat,depth:.04},{part:`thigh`,object:r.seat,depth:.045}];return r.seatBack&&e.scene.objects[r.seatBack]&&m.push({part:`torso`,object:r.seatBack,depth:.03}),r.wheel&&e.scene.objects[r.wheel]&&m.push({part:`hand`,object:r.wheel,depth:.05}),{keys:[{f:e.f0,set:p}],checks:{supports:[{object:r.seat,part:`hips`,tol:.04}],allow:m},end:e.f0}}function Vk(e){let t=e.args.side??`l`;Fk.has(t)||fO(e.tag,`args.side must be "l" or "r", got ${JSON.stringify(t)}`);let n=Ik(e.args,t),r=Lk(e,n.seat,t),i=e.args.channel??`door`;for(let[t,r]of[[`door`,n.door],[`handle`,n.handle]])pO(e,t,r);r.negate.add(i);let a={[i]:0,w_handle_l:0,w_lthigh_l:0,w_rthigh_r:0,fingers_l:{grip:0,fist:0}},o=dO(e.state,e.f0,r),s={};for(let[t,n]of Object.entries(a))e.state[lO(r,t)]===void 0&&(s[t]=n);Object.keys(s).length&&o.at(0,s),Hk(o,i,zk(e.sk));let c=e.scene.objects[n.door],l=(r.mirror?-1:1)*c.half[0],u={pivot:V(c.pos,J(c.R,[l,0,c.half[2]])),axis:[0,1,0],channel:i},d=e=>r.mirror?aO(e):e,f=e=>r.mirror?{lthigh:`rthigh`,rthigh:`lthigh`}[e]??e:e,p=(e,t)=>({kind:`segment`,from:d(`${e}UpLeg`),to:d(`${e}Leg`),t:.45,tMin:.15,offset:[0,.07,0],reach:r.mirror?t===`l`?`r`:`l`:t}),m=r.mirror?`r`:`l`;return{keys:o.keys,objects:{[n.door]:u,[n.handle]:u},anchors:{handle:{kind:`object`,object:n.handle,local:cO(r,[-.005,.015,0])},[f(`lthigh`)]:p(`Left`,`l`),[f(`rthigh`)]:p(`Right`,`r`)},props:{grip:{hand:m,origin:[d(`LeftHandIndex2`),d(`LeftHandMiddle2`)],points:{fingers:[0,0,0]}}},fits:[{side:m,anchor:`handle`,effector:{prop:`grip`,point:`fingers`}}],checks:{contacts:[{name:`fingers on the door handle`,point:`prop:grip.fingers`,target:`anchor:handle`,tol:.04,when:`w_handle_${m}`}],allow:[{part:`hand`,object:n.door,depth:.03},{part:`hand`,object:n.handle,depth:.04},...Rk]},end:e.f0+246}}function Hk(e,t,{A:n,H:r}){e.hold(12,`w_handle_l`,`fingers_l`,`head_yaw`,`spine_yaw`,`spine_roll`,`elbow_l`,`hand_l`),e.at(32,{w_handle_l:1,fingers_l:{grip:1,fist:0},head_yaw:35,spine_yaw:10,spine_roll:-8,elbow_l:[.3,-1,-.6],hand_l:[1,.96,.06]}),e.hold(32,t),e.at(38,{[t]:-3}),e.at(50,{[t]:-10,spine_roll:-16,spine_yaw:14}),e.hold(54,`w_handle_l`,`fingers_l`,`w_lthigh_l`,`elbow_l`,t),e.at(66,{w_handle_l:0,fingers_l:{grip:0,fist:0},[t]:-10}),e.at(70,{w_lthigh_l:1,elbow_l:[.5,-.3,-1],spine_roll:-3,spine_yaw:6}),e.at(84,{[t]:-68,head_yaw:40}),e.hold(64,`w_rthigh_r`,`elbow_r`,`spine_pitch`),e.at(80,{w_rthigh_r:1,elbow_r:[-.5,-.3,-1],spine_roll:0,spine_yaw:0,spine_pitch:0}),e.hold(84,`yaw`,`root`,`foot_l`,`foot_r`,`fyaw_l`,`fyaw_r`,`knee_l`,`knee_r`),e.at(92,{foot_r:[.4,Nk+n+.03,.36],fyaw_r:15}),e.at(97,{foot_l:[.96,.62,.32],fyaw_l:40,knee_l:[.5,.4,1],yaw:30,root:[.64,.915,-.06]}),e.at(101,{foot_r:[.56,Nk+n,.34],fyaw_r:35}),e.at(105,{foot_l:[1.18,.5,.1],fyaw_l:60}),e.at(116,{foot_l:[1.28,n,-.12],fyaw_l:75,knee_l:[.4,.5,1],yaw:62,root:[.82,.9,-.06],head_yaw:20,knee_r:[.1,.6,1],spine_pitch:10}),e.hold(120,`foot_r`,`fyaw_r`),e.at(129,{foot_r:[.94,.64,.36],fyaw_r:65,knee_r:[0,.5,1],yaw:80,root:[.86,.9,-.03]}),e.at(135,{foot_r:[1.18,.5,.26],fyaw_r:85}),e.hold(142,`foot_l`,`fyaw_l`),e.at(144,{foot_r:[1.29,n,.22],fyaw_r:90,knee_r:[-.1,.4,1],yaw:90,root:[.88,.9,.02],head_yaw:0,knee_l:[.1,.4,1],spine_pitch:16}),e.hold(144,`head_pitch`,`pitch`,`elbow_l`,`elbow_r`),e.at(152,{spine_pitch:28,head_pitch:-8,root:[.91,.9,.02],elbow_l:[.6,-.2,-1],elbow_r:[-.6,-.2,-1]}),e.at(162,{spine_pitch:50,pitch:22,head_pitch:-36,root:[.99,.91,.02]}),e.at(174,{root:[1.09,.96,.02],spine_pitch:36,pitch:12,head_pitch:-24}),e.hold(166,`armw_l`,`armw_r`),e.at(186,{root:[1.19,r(1),.02],spine_pitch:12,pitch:3,head_pitch:-8,armw_l:0,armw_r:0}),e.hold(187,`w_lthigh_l`,`w_rthigh_r`),e.at(190,{w_lthigh_l:0,w_rthigh_r:0}),e.at(196,{root:[1.21,r(1.005),.02],spine_pitch:0,pitch:0,head_pitch:0}),e.at(205,{root:[1.26,r(.985),.165]}),e.hold(208,`foot_l`,`fyaw_l`),e.at(212,{root:[1.3,r(.985),.16]}),e.at(214,{foot_l:[1.4,n+.06,-.12]}),e.at(220,{foot_l:[1.535,n,-.132],fyaw_l:110,root:[1.38,r(.98),.05]}),e.at(230,{root:[1.5,r(.975),-.08]}),e.hold(232,`foot_r`,`fyaw_r`),e.at(236,{root:[1.52,r(.975),-.085]}),e.at(239,{foot_r:[1.53,n+.07,.09]}),e.at(246,{foot_r:[1.765,n,-.048],fyaw_r:125,yaw:110,root:[1.62,r(.98),-.08]})}var Uk=[`cig`,`lighter`,`exhale`],Wk={follow:`landmark:mouth`,aim:`face`,visible:`exhale`},Gk={cig:`cigarette`,lighter:`lighter`},Kk=.7,qk=[-.05,.07,.1],Jk=.88,Yk=.2,Xk=[.245,.08,.02],Zk={l:[.13,-.035,.08],r:[-.13,-.035,.08]};function Qk(e,t){return Object.entries(e?.objects??{}).map(([e,t])=>[e,t,!0]).concat(Object.entries(e?.others??{}).map(([e,t])=>[e,t,!1])).filter(([,e])=>e.ancestors?.includes(t))}function $k(e,t,n){let r=t[n];return(typeof r!=`string`||!Jl(e.scene)[r])&&fO(e.tag,`args.kit.${n} ${JSON.stringify(r)} is not a group in the scene; object.createKit { kit: "${Gk[n]}" } answers its rootId`),r}var eA={cig:.03,lighter:.045},tA=.07,nA=.04;function rA(e,t){let n=e.args.kit;if(n===void 0)return null;(!n||typeof n!=`object`||Array.isArray(n))&&fO(e.tag,`args.kit must be { cig, lighter, exhale? } (kit root ids), got ${JSON.stringify(n)}`);for(let t of Object.keys(n))Uk.includes(t)||fO(e.tag,`args.kit has unknown field "${t}"; fields: ${Uk.join(`, `)}`);let r=$k(e,n,`cig`),i=$k(e,n,`lighter`),a={[r]:{prop:`cig`,grab:t.cig,at:[0,0,0],along:[0,0,1],visible:`cig_vis`},[i]:{prop:`lighter`,grab:t.lit,release:t.unlit,at:[0,0,0],along:[0,1,0],visible:`lit_vis`}};for(let[t,n,i]of Qk(e.scene,r))i&&n.glow||!i&&n.renderer===`light`?a[t]={visible:`ember_vis`,level:`ember`}:!i&&n.renderer===`effect`&&(a[t]={visible:`ember_vis`});for(let[t,n,r]of Qk(e.scene,i))(r&&n.glow||!r&&n.renderer===`light`)&&(a[t]={visible:`flame_vis`});n.exhale!==void 0&&((typeof n.exhale!=`string`||!(e.scene?.others?.[n.exhale]||e.scene?.objects?.[n.exhale]||Jl(e.scene)[n.exhale]))&&fO(e.tag,`args.kit.exhale ${JSON.stringify(n.exhale)} is not a scene object; object.createKit { kit: "exhale" } answers its rootId (it follows the mouth)`),a[n.exhale]={...Wk});let o=e=>t.squat?tA:e;return{objects:a,allow:[[`thigh_r`,r,o(eA.cig)],[`thigh_l`,i,o(eA.lighter)],[`hips`,r,o(eA.cig)],[`hips`,i,o(eA.lighter)],...t.squat?[[`shin`,r,tA],[`shin`,i,tA],[`hand_l`,`thigh_l`,nA],[`hand_r`,`thigh_r`,nA],[`hand`,`hips`,nA]]:[]].map(([e,t,n])=>({part:e,object:t,depth:n}))}}function iA(e){let{sk:t,state:n}=e,r=t.index,i=t.restWorldPos;if(!(n.root[1]<Kk*i[r.Hips][1]))return null;let{s:a}=y_(t,n),o=n.yaw??0,s=a.P[r.RightArm],c=e=>J(X(-o),H(e,n.root)),l=G(H(i[r.RightForeArm],i[r.RightArm]))+G(H(i[r.RightHand],i[r.RightForeArm])),u=V(a.P[r.RightLeg],J(X(o),qk)),d=G(H(u,s)),f=c(d>Jk*l?V(s,U(H(u,s),Jk*l/d)):u),p=V(c(Io(a,r.Head,t.landmarks.mouth)),[0,0,Yk]),m=Bs(t),h=(e,r)=>{let i=V(n.root,J(X(o),[r*Xk[0],Xk[1],Xk[2]]));return c(m?Rs(m.body,t,a,i,zs,m.skip):i)},g=e=>e.map(e=>Math.round(e*1e3)/1e3);return{hold:g(f),mouthOut:g(p),lpocket:g(h(`Left`,1)),rpocket:g(h(`Right`,-1))}}var aA={TW_M:40,FX_M:0,TW_H:0,FX_H:10,TW_L:-80,FX_L:-50},oA=15,sA=20,cA=[[`hand_l`,`hand_r`,.045],[`hand_r`,`hand_l`,.045],[`farm_r`,`hand_l`,.02],[`hand_l`,`farm_r`,.02]].map(([e,t,n])=>({part:e,object:t,depth:n})),lA=[.4,-1,.6],uA=[-.4,-1,-.3],dA=[.9,-.6,.3],fA=[`armw_r`,`armw_l`,`w_rpocket_r`,`w_lpocket_l`,`w_hold_r`,`w_mouth_r`,`w_flame_l`,`elbow_r`,`elbow_l`,`wtwist_r`,`wflex_r`,`wtwist_l`,`wflex_l`,`head_pitch`,`head_yaw`,`spine_pitch`,`root`,`fingers_l`,`fingers_r`,`cig_vis`,`lit_vis`,`flame_vis`,`ember_vis`,`exhale`,`ember`],pA=264,mA=.75,hA=Math.ceil(pA*mA),gA=e=>(e/24).toFixed(1),_A={armw_r:0,armw_l:0,w_rpocket_r:0,w_lpocket_l:0,w_hold_r:0,w_mouth_r:0,w_flame_l:0,elbow_r:[-.5,-.4,-1],elbow_l:[.5,-.4,-1],wtwist_r:0,wflex_r:0,wtwist_l:0,wflex_l:0,head_pitch:0,head_yaw:0,spine_pitch:0,fingers_l:{grip:0,fist:0},fingers_r:{cigarette:0},cig_vis:0,lit_vis:0,flame_vis:0,ember_vis:0,exhale:0,ember:0};function vA(e){let t=e.args.until??(e.auto?e.f0+pA:e.frames-1),n=t-e.f0;n<hA&&fO(e.tag,`needs frames f${e.f0}..f${e.f0+hA} at least: 199 frames, ${gA(199)} s at 24 fps, paced ${mA} (265 frames, ${gA(265)} s, at its own pace); it has f${e.f0}..f${t}, `+(e.args.until===void 0?`so set frames >= ${e.f0+hA+1} or frames: "auto"`:`so set args.until >= ${e.f0+hA}`)),Array.isArray(e.state.root)||fO(e.tag,`needs a pose keyed before f0 (root): standing or squatting`);let r=Object.fromEntries(Object.entries(_A).filter(([t])=>e.state[t]===void 0));Object.keys(r).length&&Object.assign(e.state,structuredClone(r)),e.state.head_yaw=0;let i=e.state.head_pitch,a=(e.state.pitch??0)+e.state.spine_pitch,o=e=>e+i,s=a?J(So(a),lA):lA,c=a?J(So(a),uA):uA,l=iA(e),u=e.self?l?sA:oA:aA.FX_M;l&&(e.state.w_mouthOut_r=0);let d=n<pA?n/pA:1,f=e=>Math.round(e*d),p=dO(e.state,e.f0),m=d===1?p:{...p,at:(e,t)=>p.at(f(e),t),hold:(e,...t)=>p.hold(f(e),...t),step:(e,t,n)=>p.step(f(e),t,n)},h=e.state.root.slice(),g=e.state.yaw??0,_=(e,t)=>{m.hold(e,`w_mouth_r`,`w_hold_r`,`wtwist_r`,`wflex_r`,`elbow_r`,`head_pitch`,`root`,...l?[`w_mouthOut_r`]:[]),l&&m.at(Math.round((e+t)/2),{w_hold_r:0,w_mouthOut_r:1,w_mouth_r:0}),m.at(t,{w_mouth_r:1,w_hold_r:0,...l?{w_mouthOut_r:0}:{},wtwist_r:aA.TW_M,wflex_r:u,elbow_r:s,head_pitch:o(6),root:h})},v=(e,t)=>{m.hold(e,`w_mouth_r`,`w_hold_r`,`wtwist_r`,`wflex_r`,`elbow_r`,`head_pitch`,...l?[`w_mouthOut_r`]:[]),l&&m.at(Math.round((e+t)/2),{w_mouth_r:0,w_mouthOut_r:1,w_hold_r:0}),m.at(t,{w_mouth_r:0,w_hold_r:1,...l?{w_mouthOut_r:0}:{},wtwist_r:aA.TW_H,wflex_r:aA.FX_H,elbow_r:c,head_pitch:o(0)})};m.hold(0,...fA),m.at(2,{w_rpocket_r:1,elbow_r:[-.5,-.4,-1]}),m.hold(6,`armw_r`,`w_rpocket_r`,`elbow_r`,`fingers_r`),m.at(20,{armw_r:1}),m.at(28,{fingers_r:{cigarette:1}}),m.step(28,`cig_vis`,1),m.hold(36,`w_rpocket_r`,`w_mouth_r`,`wtwist_r`,`wflex_r`,`elbow_r`,`head_pitch`),m.at(58,{w_rpocket_r:0,w_mouth_r:1,wtwist_r:aA.TW_M,wflex_r:u,elbow_r:s,head_pitch:o(6)}),m.at(2,{w_lpocket_l:1,elbow_l:[.5,-.4,-1]}),m.hold(12,`armw_l`,`w_lpocket_l`,`elbow_l`,`fingers_l`),m.at(26,{armw_l:1}),m.at(34,{fingers_l:{grip:0,fist:1}}),m.step(35,`lit_vis`,1),m.hold(44,`w_lpocket_l`,`w_flame_l`,`wtwist_l`,`wflex_l`,`elbow_l`),m.at(60,{w_lpocket_l:0,w_flame_l:1,wtwist_l:aA.TW_L,wflex_l:aA.FX_L,elbow_l:dA}),m.step(63,`flame_vis`,1),m.step(73,`ember_vis`,1),m.step(79,`flame_vis`,0),m.step(73,`ember`,1),m.at(80,{ember:2}),m.hold(90,`ember`),m.at(104,{ember:.6}),m.hold(194,`ember`),m.at(200,{ember:2}),m.hold(212,`ember`),m.at(224,{ember:.6}),m.step(116,`exhale`,1),m.step(138,`exhale`,0),m.step(238,`exhale`,1),m.step(260,`exhale`,0),m.hold(80,`w_flame_l`,`w_lpocket_l`,`wtwist_l`,`wflex_l`,`elbow_l`);let y=l&&e.self?8:0;m.at(y?96+y:l?100:96,{w_flame_l:0,w_lpocket_l:1,wtwist_l:0,wflex_l:0,elbow_l:[.5,-.4,-1]}),m.hold(101+y,`fingers_l`),m.step(102+y,`lit_vis`,0),m.hold(104+y,`armw_l`,`w_lpocket_l`),m.at(112,{fingers_l:{grip:0,fist:0}}),m.at(120,{armw_l:0,w_lpocket_l:1}),m.at(123,{w_lpocket_l:0}),v(92,114),m.at(124,{head_pitch:o(-14)}),m.at(140,{head_pitch:o(0)});let b=[Math.cos(g*Math.PI/180),0,-Math.sin(g*Math.PI/180)];m.hold(120,`root`,`head_yaw`),m.at(146,{root:h.map((e,t)=>e+.03*b[t]-(t===1?.005:0)),head_yaw:-22}),m.at(168,{head_yaw:0}),_(170,194),v(212,236),m.at(246,{head_pitch:o(-14)}),m.at(264,{head_pitch:o(0)}),p.hold(n,...fA,...l?[`w_mouthOut_r`]:[]);let x=!!l&&e.self,S=rA(e,{cig:e.f0+f(28),lit:e.f0+f(35),unlit:e.f0+f(x?110:102),squat:x});return{keys:p.keys,end:t,...d<1?{paced:Math.floor(d*100)/100}:{},channels:[`exhale`,`ember`],...S?{objects:S.objects}:{},anchors:{lpocket:{kind:`body`,p:e.self&&l?.lpocket||Zk.l},rpocket:{kind:`body`,p:e.self&&l?.rpocket||Zk.r},hold:{kind:`body`,p:l?.hold??[-.24,.03,.06]},...l?{mouthOut:{kind:`body`,p:l.mouthOut}}:{},mouth:{kind:`landmark`,name:`mouth`},flame:{kind:`prop`,prop:`cig`,point:`tip`,offset:[0,-.02,0]}},props:{cig:{hand:`r`,origin:[`RightHandIndex2`,`RightHandMiddle2`],points:{filter:[0,0,-.026],tip:[0,0,.058]}},lighter:{hand:`l`,origin:[`LeftHand`,`LeftHandMiddle1`],points:{body:[.01,0,0],flame:[.01,.036,0]}}},fits:[{side:`r`,anchor:`mouth`,effector:{prop:`cig`,point:`filter`}},{side:`l`,anchor:`flame`,effector:{prop:`lighter`,point:`flame`}}],checks:{contacts:[{name:`filter on the lips`,point:`prop:cig.filter`,target:`anchor:mouth`,tol:.01,when:`w_mouth_r`},{name:`flame under the cigarette tip`,point:`prop:lighter.flame`,target:`anchor:flame`,tol:.01,when:`flame_vis`}],orient:[{name:`lit end points away from the face`,from:`prop:cig.filter`,to:`prop:cig.tip`,along:`face`,minCos:.64,when:`w_mouth_r`},{name:`lighter upright`,from:`prop:lighter.body`,to:`prop:lighter.flame`,along:`up`,minCos:.85,when:`flame_vis`}],below:[{name:`no chicken-wing elbow`,joint:`RightForeArm`,ref:`RightArm`,min:.08,when:`w_mouth_r`}],appear:[{name:`cigarette from the right pocket`,channel:`cig_vis`,joint:`RightHand`,anchor:`rpocket`,tol:.035},{name:`lighter from the left pocket`,channel:`lit_vis`,joint:`LeftHand`,anchor:`lpocket`,tol:.035}],mouthPoints:[`cig.filter`],allow:[...S?.allow??[],...cA]}}}var yA=9.81/576,bA=10,xA=5,SA=6,CA=14,wA=50,TA=e=>Math.min(1,Math.max(0,e)),EA=e=>{let t=TA(e);return t*t*(3-2*t)},DA=(e,t,n)=>e+(t-e)*n,OA=(e,t,n)=>e.map((e,r)=>e+(t[r]-e)*n),kA=(e,t,n,r,i)=>EA((e-t)/(n-t))-EA((e-r)/(i-r)),AA={l:1,r:-1},jA=(e,t,n)=>q(X(e),q(So(t),Co(n))),MA=(e,t,n,r,i)=>J(Y(v_(e,t,n)?.R??X(e)),J(r,i));function NA(e,t,n,r,i,a){let o=v_(e.h,n,r);if(!o)return{fyaw:e.h,fpitch:a};let s=e.toe[t],c=J(i,J(So(a),s)),l=J(Y(o.R),c),u=Math.atan2(-s[1],s[2]),d=180/Math.PI,f=Math.asin(Math.max(-1,Math.min(1,-l[1]/Math.hypot(...l))))-u;return{fyaw:e.h+Math.atan2(l[0],l[2])*d,fpitch:Math.max(-60,Math.min(90,f*d))}}function PA(e){let{sk:t,args:n,state:r}=e,i=t.index,a=t.restWorldPos;(!r.foot_l||!r.foot_r||!r.root)&&fO(e.tag,`needs a standing pose keyed before f0 (use standIdle or another skill first)`);let o=n.heading??r.yaw??0,s=X(o),c=a[i.Hips],l=go(a[i.LeftUpLeg],a[i.LeftLeg])+go(a[i.LeftLeg],a[i.LeftFoot]),u=go(a[i.LeftArm],a[i.LeftForeArm])+go(a[i.LeftForeArm],a[i.LeftHand]);return{h:o,R:s,F:J(s,[0,0,1]),L:J(s,[1,0,0]),ank:a[i.LeftFoot][1],y0:c[1]-.01,leg:l,arm:u,feet:{l:r.foot_l.slice(),r:r.foot_r.slice()},root:r.root.slice(),hipOff:{l:H(a[i.LeftUpLeg],c),r:H(a[i.RightUpLeg],c)},shoulder:{l:H(a[i.LeftArm],c),r:H(a[i.RightArm],c)},toe:{l:H(a[i.LeftToeBase],a[i.LeftFoot]),r:H(a[i.RightToeBase],a[i.RightFoot])}}}function FA(e,t,n){let{args:r}=e,i=(n===`back`?-1:1)*360,a=r.travel??(n===`back`?-.25:.4),o=t.y0+.05,s=t.y0-.02,c=Math.max(10,Math.round(Math.sqrt(.9/yA)+Math.sqrt(2*(o+.5-.05-s)/yA))),l=(s-o+yA*c*c/2)/c,u=l-yA*c,d=o-l*xA/2,f=s+u*SA/2,p=a/(xA/2+c+SA/2),m=e.f0,h=m+bA,g=h+xA,_=g+c,v=_+SA,y=v+CA,b=e=>V(t.feet[e],U(t.F,a)),x=e=>V(t.feet[e],J(t.R,t.toe[e])),S=e=>{let n,r;if(e<=h)n=DA(t.root[1],d,EA((e-m)/bA)),r=0;else if(e<=g){let t=e-h;n=d+l/xA*t*t/2,r=p/xA*t*t/2}else if(e<=_){let t=e-g;n=o+l*t-yA*t*t/2,r=p*xA/2+p*t}else if(e<=v){let t=e-_;n=s+u*t-u/SA*t*t/2,r=p*xA/2+p*c+p*t-p/SA*t*t/2}else n=DA(f,t.y0,EA((e-v)/CA)),r=a;return V([t.root[0],n,t.root[2]],U(t.F,r))},C=e=>i*EA((e-g+2)/(c+5)),w=e=>jA(t.h,C(e),0),T=(e,t)=>J(Y(w(e)),H(t,S(e))),E={l:T(g,Vv(x(`l`),t.h,wA,t.feet.l)),r:T(g,Vv(x(`r`),t.h,wA,t.feet.r))},D={l:T(_,b(`l`)),r:T(_,b(`r`))},O=[];for(let e=m;e<=y+1;e++){let n=e>y?0:C(e),r=jA(t.h,n,0),i=S(e),a=(e-g)/c,o=e>g&&e<_?kA(a,.12,.34,.6,.82):0,s={root:i,yaw:t.h,pitch:n,roll:0,armw_l:0,armw_r:0,fyaw_l:t.h,fyaw_r:t.h};for(let c of[`l`,`r`]){let l,u;if(e<=h)l=t.feet[c],u=0;else if(e<=g)u=wA*EA((e-h)/xA),l=Vv(x(c),t.h,u,t.feet[c]);else if(e<_){let e=1-EA(a/.2),n=EA((a-.72)/.28),s=V(t.hipOff[c],OA([0,-t.leg*.97,0],[AA[c]*.02,-.24,.16],o));l=V(i,J(r,V(V(U(E[c],e),U(D[c],n)),U(s,1-e-n)))),u=DA(DA(wA,30,EA(a/.2)),0,EA((a-.7)/.3))}else l=b(c),u=0;let d=e>g&&e<_?NA(t,c,n,0,r,u):{fyaw:t.h,fpitch:u};Object.assign(s,{[`foot_${c}`]:l,[`fpitch_${c}`]:d.fpitch,[`fyaw_${c}`]:d.fyaw,[`knee_${c}`]:MA(t.h,n,0,r,[AA[c]*.05,.5*o,1])})}O.push({f:e,set:s})}let k=n===`back`?[-12,18]:[10,25];for(let[e,t,n,r,i]of[[m,0,0,0,0],[h,-45,15,20,0],[g,160,5,-8,k[0]],[Math.round(g+.3*c),55,85,32,k[1]],[Math.round(g+.62*c),55,85,32,k[1]],[_,75,25,22,0],[v,70,25,28,0],[y,0,0,0,0]])O.push({f:e,set:{aswing_l:t,aswing_r:t,abend_l:n,abend_r:n,spine_pitch:r,head_pitch:i}});return{keys:O,end:y+1}}function IA(e,t){let{args:n}=e,r=n.side===`r`?-1:1,i=-r,a=e.f0,o=a+12,s=o+34,c=s+14,l=r>0?`l`:`r`,u=l===`l`?`r`:`l`,d={foot:e=>V(t.hipOff[e],[AA[e]*.3,-t.leg*.93,0]),hand:e=>V(t.shoulder[e],[AA[e]*.32,t.arm*.88,0])},f={foot:t.ank,hand:.1},p=[[`foot`,l],[`hand`,l],[`hand`,u],[`foot`,u],[`foot`,l]],m=e=>e<=o?0:e<=s?i*360*EA((e-o)/34):i*360,h=(e,n,r,i)=>V(n,J(jA(t.h,0,m(e)),d[r](i))),g=jA(t.h,0,0),_=H(t.feet[u],J(g,d.foot(u))),v=h(o,_,`foot`,l);v[1]=t.ank;let y=[],b={foot:{l:[],r:[]},hand:{l:[],r:[]}},x=0,S=t.feet[l].slice(),C=o;b.foot[u].push({a,b:o,p:t.feet[u]});for(let e=a;e<=c+1;e++){if(e<=o){y.push(OA(t.root,_,EA((e-a)/12)));continue}e===o+1&&(S=v.slice());let n=H(S,J(jA(t.h,0,m(e)),d[p[x][0]](p[x][1]))),r=p[x+1];if(r&&e<=s){let i=h(e,n,...r);if(i[1]<=f[r[0]]){let a=h(e-1,y.at(-1),...r),o=a[1]-f[r[0]],s=i[1]-f[r[0]],c=OA(a,i,o>0?o/(o-s):1);b[p[x][0]][p[x][1]].push({a:C,b:e,p:S}),x++,C=e,S=[c[0],f[r[0]],c[2]],n=H(S,J(jA(t.h,0,m(e)),d[r[0]](r[1])))}}y.push(n)}b[p[x][0]][p[x][1]].push({a:C,b:c+1,p:S});let w=p[p.length-2];x>=p.length-1&&(b[w[0]][w[1]].at(-1).b=c+1);let T=y.map((e,t)=>{let n=[0,0,0],r=0;for(let e=-3;e<=3;e++){let i=Math.min(y.length-1,Math.max(0,t+e)),a=Math.exp(-(e*e)/4);n=V(n,U(y[i],a)),r+=a}return U(n,1/r)}),E=e=>e<=s?T[e-a]:V(T[s-a],[0,(t.y0-T[s-a][1])*EA((e-s)/14),0]),D=(e,t,n)=>{let r=H(e,t),i=Math.hypot(...r);return i>n?V(t,U(r,n/i)):e},O=(e,n,r,i)=>{for(let a of b[e][n]){if(r>=a.a-6&&r<=a.b)return OA(i,a.p,EA((r-a.a+6)/6));if(r>a.b&&r<=a.b+10){let i=J(Y(jA(t.h,0,m(a.b))),H(a.p,E(a.b))),o=V(E(r),J(jA(t.h,0,m(r)),OA(i,d[e](n),EA((r-a.b-1)/9))));return OA(a.p,o,EA((r-a.b)/8))}}return i},k=(e,t,n)=>b[e][t].some(e=>n>=e.a&&n<=e.b),ee=Object.fromEntries([`l`,`r`].map(e=>{let n=k(`foot`,e,s)?b.foot[e].at(-1).p.slice():h(s,E(s),`foot`,e);return n[1]=t.ank,[e,n]})),A=[];for(let e=a;e<=c+1;e++){let n=e===c+1?0:m(e),r=jA(t.h,0,m(e)),i=E(e),u={root:i,yaw:t.h,pitch:0,roll:n};for(let c of[`l`,`r`]){let d;if(e<=o&&c===l){let n=EA((e-a-1)/8);d=V(OA(t.feet[c],v,n),[0,.07*Math.sin(Math.PI*n),0])}else if(e>s)d=ee[c];else{let n=EA((e-s+4)/4);d=D(OA(O(`foot`,c,e,h(e,i,`foot`,c)),ee[c],n),V(i,J(r,t.hipOff[c])),t.leg*.995)}let f=e>o&&e<=s?NA(t,c,0,m(e),r,0):{fyaw:t.h,fpitch:0};Object.assign(u,{[`foot_${c}`]:d,[`fyaw_${c}`]:f.fyaw,[`fpitch_${c}`]:f.fpitch,[`knee_${c}`]:MA(t.h,0,n,r,[AA[c]*.05,0,1]),[`hand_${c}`]:D(e>o&&e<=s?O(`hand`,c,e,h(e,i,`hand`,c)):h(e,i,`hand`,c),V(i,J(r,t.shoulder[c])),t.arm*.995),[`elbow_${c}`]:MA(t.h,0,n,r,[AA[c]*.4,0,-1]),[`armw_${c}`]:e<=o?0:e<=s?EA((e-o)/6):1-EA((e-s)/8)})}u.arm_rest=e<=o?DA(72,-56,EA((e-a)/12)):e<=s?-56:DA(-56,72,EA((e-s)/14)),A.push({f:e,set:u})}return{keys:A,end:c+1}}function LA(e){let t=e.args.kind??`back`;[`back`,`front`,`cartwheel`].includes(t)||fO(e.tag,`kind must be "back", "front" or "cartwheel", got ${JSON.stringify(t)}`);let n=PA(e);return t===`cartwheel`?IA(e,n):FA(e,n,t)}var RA=9.81,zA=24,BA=.75,VA={back:.16,front:.11},HA=.25,UA=.12,WA=.25,GA=e=>e-UA*(1-Math.exp(-e/UA)),KA=(e,t,n)=>t+n*Math.log1p(Math.exp((e-t)/n)),qA=3/zA,JA=.03,YA=.25,XA=e=>{let t=Math.min(1,Math.max(0,e));return t*t*t*(t*(6*t-15)+10)},ZA=e=>(e+540)%360-180,QA=e=>e.map(e=>Math.round(e*1e3)/1e3),$A=e=>Math.round(e*10)/10;function ej(e,t,n){let r=null,i=null;for(let a of e){let e=a.set?.[t];Array.isArray(e)&&(a.f<=n&&(!r||a.f>=r.f)&&(r={f:a.f,v:e}),a.f>n&&(!i||a.f<i.f)&&(i={f:a.f,v:e}))}if(!r||!i)return r?.v;let a=(n-r.f)/(i.f-r.f);return r.v.map((e,t)=>e+(i.v[t]-e)*a)}function tj(e,t){let{args:n,scene:r}=e,i=n.dir;if(!i&&typeof n.from==`string`){let[a,o]=n.from.split(/:(.*)/s),s=a===`object`?r?.objects?.[o]?.pos:a===`person`?hd(r,o,`Hips`,e.f0):null;s||fO(e.tag,`args.from "${n.from}" must be object:<id> of a scene body or person:<id> of a character with an installed take`),i=[t[0]-s[0],t[2]-s[2]]}(!Array.isArray(i)||i.length!==2||!(Math.hypot(i[0],i[1])>1e-6))&&fO(e.tag,`needs args.dir: [x, z] (the way the body is thrown) or args.from: object:<id> | person:<id> (what hits it)`);let a=Math.hypot(i[0],i[1]);return[i[0]/a,i[1]/a]}function nj(e){let{sk:t,args:n,state:r}=e,i=t.index,a=t.restWorldPos;r.root||fO(e.tag,`needs a pose keyed before f0 (standIdle, a walk, ...)`);let o=ej(e.keys,`root`,e.f0)??r.root.slice(),s={};for(let t of[`l`,`r`]){let n=ej(e.keys,`foot_${t}`,e.f0),r=ej(e.keys,`foot_${t}`,e.f0-1);n&&(s[t]={at:n,v:r?n.map((e,t)=>e-r[t]):[0,0,0]})}let c=r.yaw??0,[l,u]=tj(e,o),d=n.speed??4;Number.isFinite(d)&&d>0||fO(e.tag,`args.speed must be a launch speed above 0 m/s, got ${JSON.stringify(n.speed)}`);let f=Math.min(2.5,Math.max(.8,.3*d)),p=J(X(c),[0,0,1]),m=(n.land??(l*p[0]+u*p[2]<=0?`back`:`front`))===`back`,h=Math.atan2(l,u)*180/Math.PI,g=ZA((m?h+180:h)-c),_=m?-90:90,v=m?VA.back:VA.front,y=o[1],b=e=>y+f*GA(e)-.5*RA*e*e,x=e=>f*(1-Math.exp(-e/UA))-RA*e,S=0,C=(f+Math.sqrt(f*f+2*RA*Math.max(0,y-v)))/RA+1;for(let e=0;e<60;e++){let e=(S+C)/2;b(e)+x(e)*qA/2>v-JA||x(e)>0?S=e:C=e}let w=S,T=Math.min(0,x(w)),E=b(w),D=w+qA,O=d/(BA*RA),k=D+O,ee=e=>e<w?b(e):e<D?E+T*(e-w)-T/(2*qA)*(e-w)**2:v-JA*(1-XA((e-D)/YA)),A=a[i.LeftFoot][1],te=a[i.Hips][1],ne=m?1:-1,re=.9*Math.hypot(...[0,1,2].map(e=>a[i.LeftFoot][e]-a[i.Hips][e])),ie=e.f0+Math.ceil((k+.6)*zA),ae=[];for(let t=e.f0;t<=ie;t++){let n=(t-e.f0)/zA,r=n<D,i=Math.min(Math.max(0,n-D),O),a=r?d*GA(n):d*GA(D)+d*i-.5*BA*RA*i*i,f=ee(n),p=[o[0]+l*a,f,o[2]+u*a],h=Math.max(.35,.9*D),v=c+g*XA(n/Math.max(HA,h)),y=_*XA(n/h),b=(e=>J(X(v),J(So(y),e))),x=XA(n/UA)*Math.exp(-n/.18)*Math.sin(2*Math.PI*n/.55),S=XA(n/.3)*Math.exp(-n/.45)*Math.sin(2*Math.PI*n/.6),C=XA((n-D)/.3),w=-(te-A)+.06*(1-C)+(m?.03:.01)*C,T=XA(n/WA),E=A+.01+(!m&&!r&&i<O?.04:0),k=(n,r,i)=>{let a=V(p,b([r,w,i])),o=p[1]-.05;m&&(a[1]=o-.05*Math.log1p(Math.exp((o-a[1])/.05))),a[1]=KA(a[1],E,.03);let c=s[n];if(!c)return a;let l=c.at.map((n,r)=>n+c.v[r]*(t-e.f0)*(1-T));return l[1]=Math.max(c.at[1],l[1]),ie(a.map((e,t)=>l[t]+(e-l[t])*T))},ie=e=>{let t=e.map((e,t)=>e-p[t]),n=Math.hypot(...t),r=re-.02*Math.log1p(Math.exp((re-n)/.02));return n>1e-9?p.map((e,i)=>e+t[i]*(1+(r/n-1)*T)):e},oe=v_(0,y,0),se=oe?J(oe.R,[0,1,0]):[0,1,0],ce=Math.atan2(se[2],se[1])*180/Math.PI,le=J(So(-ce),[0,-Math.sin(y*Math.PI/180),Math.max(.05,Math.cos(y*Math.PI/180))]),ue={root:QA(p),yaw:$A(v),pitch:$A(y),roll:0,foot_l:QA(k(`l`,.11,.04+.1*S*T-(m?.1:0)*C)),foot_r:QA(k(`r`,-.11,.04-.1*S*T-(m?.1:0)*C)),fyaw_l:$A(v),fyaw_r:$A(v),fpitch_l:$A(m?-50*C:-.5*ce),fpitch_r:$A(m?-50*C:-.5*ce),knee_l:QA([.05,le[1],le[2]]),knee_r:QA([-.05,le[1],le[2]]),spine_pitch:$A(ne*22*x*Math.min(1,d/4)),spine_yaw:0,spine_roll:$A(10*S*(1-C)),head_pitch:$A(ne*30*x*Math.min(1,d/4)+(m?-8:8)*C),head_roll:$A(12*C),arm_rest:$A(72-22*C),aswing_l:$A(ne*45*S+8*C),aswing_r:$A(-ne*35*S-8*C),abend_l:$A(25+30*S*S),abend_r:$A(30+25*S*S)};t===e.f0&&Object.assign(ue,{armw_l:0,armw_r:0,fingers_l:{relaxed:1},fingers_r:{relaxed:1}}),ae.push({f:t,set:ue})}return{keys:ae,end:ie}}var rj=20,ij=50,aj=10,oj=8,sj=10,cj=8,lj=.25,uj=.42,dj=.22,fj=.09,pj=.25,mj=e=>e.map(e=>Math.round(e*1e3)/1e3);function hj(e,t){let n=Object.entries(e?.objects??{}).filter(([e,n])=>e===t||n.ancestors?.includes(t)).map(([,e])=>e),r=e?.objects?.[t]?.pos??n[0]?.ancestorPoses?.[0]?.pos;return!r||!n.length?0:r[1]-Math.min(...n.map(e=>e.pos[1]))}function gj(e){let{args:t,state:n,sk:r,scene:i,tag:a}=e,o=t.object,s=t.side??`r`,c=e.objects?.[o];s!==`l`&&s!==`r`&&fO(a,`args.side must be "l" or "r", got ${JSON.stringify(s)}`),(!c?.prop||e.props?.[c.prop]?.hand!==s)&&fO(a,`args.object "${o}" must be carried by the ${s===`r`?`right`:`left`} hand (objects.${o}.prop on a prop with hand "${s}")`),(!Array.isArray(t.to)||t.to.length!==3)&&fO(a,`args.to must be [x, y, z] world m (where it lands)`);let l=(t.arc===`high`?ij:rj)*Math.PI/180,u=e.fps??24,d=s===`l`?`Left`:`Right`,f=r.restWorldPos,p=V(n.root??f[r.index.Hips],J(X(n.yaw??0),H(f[r.index[`${d}Arm`]],f[r.index.Hips]))),m=[t.to[0]-p[0],0,t.to[2]-p[2]],h=G(m);h<.5&&fO(a,`args.to is ${h.toFixed(2)} m from the shoulder; throw it at least 0.5 m`);let g=U(m,1/h),_=V(p,V(U(g,uj),[0,dj,0])),v=V(_,U(g,fj)),y=t.to[1]+hj(i,o),b=G([t.to[0]-v[0],0,t.to[2]-v[2]]),x=y-v[1],S=2*Math.cos(l)**2*(b*Math.tan(l)-x);S>0||fO(a,`args.to is too high for a ${t.arc??`low`} arc from the hand; use arc "high" or a lower point`);let C=Math.sqrt(Ah*b*b/S),w=V(U(g,C*Math.cos(l)),[0,C*Math.sin(l),0]),T=(w[1]+Math.sqrt(w[1]**2+2*Ah*Math.max(0,v[1]-y)))/Ah,E=e.f0+aj+oj,D=Math.min(e.frames-1,E+Math.ceil(T*u)+cj),O=U([g[2],0,-g[0]],s===`r`?-1:1),k=`hand_${s}`,ee=`armw_${s}`,A=V(p,V(V(U(g,-.12),U(O,pj)),[0,-.05,0])),te=V(p,V(V(U(O,.32),U(g,.12)),[0,.08,0])),ne=V(_,U(w,.45/u)),re=V(p,V(U(g,.46),[0,-.1,0])),ie=V(p,V(V(U(g,.3),U(O,-.15)),[0,-.4,0])),ae=`fingers_${s}`,oe=qc[c.grasp]??`grip`,se={...n[ae],[oe]:1},ce={...n[ae],[oe]:0},le=[{f:e.f0,set:{[ee]:n[ee]??0,[ae]:se,...n[k]?{[k]:n[k]}:{}}},{f:E,set:{[ae]:se}},{f:E+3,set:{[ae]:ce}},{f:e.f0+aj,set:{[ee]:1,[k]:mj(A)}},{f:e.f0+aj+Math.round(oj/2),set:{[ee]:1,[k]:mj(te)}},{f:E-1,set:{[ee]:1,[k]:mj(H(_,U(w,1/u)))}},{f:E,set:{[ee]:1,[k]:mj(_)}},{f:E+1,set:{[ee]:1,[k]:mj(ne)}},{f:E+3,set:{[ee]:1,[k]:mj(re)}},{f:E+sj,set:{[ee]:1,[k]:mj(ie)}}],ue=`${o}Target`;return{keys:le,end:E+sj,anchors:{[ue]:{kind:`world`,p:mj([t.to[0],y,t.to[2]])}},fills:{[o]:{release:E,fall:{at:E,v:mj(w)}}},goals:[{name:`${o} lands at the target`,near:[`object:${o}`,`anchor:${ue}`],at:D,tol:lj}],throw:{release:E,speed:Math.round(C*100)/100,v:mj(w),flight:Math.round(T*100)/100}}}var _j=[.35,.65],vj=.15,yj=10,bj=20,xj=2,Sj=6,Cj=8,wj=1,Tj=e=>e.map(e=>Math.round(e*1e3)/1e3),Ej=(e,t,n)=>Math.min(n,Math.max(t,e));function Dj(e,t,n){let r=e.restWorldPos,i=t.root??r[e.index.Hips],a=X(t.yaw??0);return{hips:i,shoulder:V(i,J(a,H(r[e.index[`${n}Arm`]],r[e.index.Hips]))),head:V(i,J(a,H(r[e.index.Head],r[e.index.Hips]))),fwd:J(a,[0,0,1])}}function Oj(e){let{args:t,state:n,sk:r,scene:i,tag:a}=e,o=t.object,s=t.side??`r`,c=e.objects?.[o],l=e.fps??24;s!==`r`&&s!==`both`&&fO(a,`args.side must be "r" or "both", got ${JSON.stringify(s)}`);let u=Array.isArray(c?.fall)?c.fall[0]:c?.fall;Array.isArray(u?.v)||fO(a,`args.object "${o}" must fly: objects.${o}.fall { at, v: [vx, vy, vz] }`);let d=Dj(r,n,`Right`),f={spec:{objects:{[o]:{fall:c.fall}},fps:l},scene:i,timeMap:null},p=e=>$h(f,o,e)?.pos,m=null,h=null;for(let t=u.at+1;t<e.frames;t++){let e=p(t),n=G(H(e,d.shoulder)),r=W(H(e,d.hips),d.fwd),i=Math.max(0,_j[0]-n,n-_j[1],vj-r,d.hips[1]-.1-e[1],e[1]-d.head[1]);if((!h||i<h.off)&&(h={f:t,p:e,off:i}),i===0){m={f:t,p:e};break}}m||fO(a,`${o} never comes within reach of the right hand (in front of the chest, ${_j[0]}-${_j[1]} m from the shoulder): nearest at f${h.f}, [${Tj(h.p).join(`, `)}], ${h.off.toFixed(2)} m out; move the body (standIdle at) or the throw`);let g=Math.max(m.f,e.f0+yj+xj),_=m.p,v=U(H(p(m.f),p(m.f-1)),l),y=G(v),b=Bx({objects:e.objects},i,o),x=Ej(.08+.02*b*y,.08,.15),S=K(v),C=e=>1-(1-e)**3,w=[_,...Array.from({length:Sj},(e,t)=>V(_,U(S,x*C((t+1)/Sj)))),V(_,U(S,x*.4))],T=Math.max(e.f0,g-xj-bj),E=s===`both`||b>wj,D=Math.max(0,...Object.values(i.objects).filter(e=>e===i.objects[o]||e.ancestors?.includes(o)).map(e=>Math.max(...e.half))),O=J(X(n.yaw??0),[1,0,0]),k={keys:[],end:g+Sj+Cj,props:{},anchors:{},fits:[],channels:[],fills:{[o]:{prop:`${o}Catch`,grab:g,grasp:`spherical`}},catch:{contact:g,point:Tj(_),speed:Math.round(y*100)/100,give:Math.round(x*1e3)/1e3,hands:E?2:1}};for(let e of E?[`r`,`l`]:[`r`]){let t=e===`l`?`Left`:`Right`,r=e===`r`?`${o}Catch`:`${o}CatchL`,i=e===`r`?[0,0,0]:U(O,2*D+.04),a=`armw_${e}`,s=`fingers_${e}`,c={...n[s],spherical:0},l={...n[s],spherical:1},u=w.map((e,t)=>`${r}${t}`),d=t=>`w_${u[t]}_${e}`;k.keys.push({f:T,set:{[a]:n[a]??0,[d(0)]:0,[s]:c,[`elbow_${e}`]:e===`r`?[-1,-.5,-.5]:[1,-.5,-.5]}},...pk(g-xj-T).map(([e,t,r])=>({f:T+e,set:{[d(0)]:t,[a]:(n[a]??0)+(1-(n[a]??0))*r}})),{f:g-xj,set:{[a]:1,[d(0)]:1,[s]:c}},{f:g,set:{[d(0)]:1,[s]:l}},...w.slice(1).flatMap((e,t)=>{let n=t+1,r=n<=Sj?g+n:g+Sj+Cj;return[{f:n<=Sj?r-1:g+Sj,set:{[d(n-1)]:1,[d(n)]:0}},{f:r,set:{[d(n-1)]:0,[d(n)]:1}}]})),k.props[r]={hand:e,origin:[`${t}HandIndex2`,`${t}HandMiddle2`],points:{fingers:[0,0,0]}},u.forEach((t,n)=>{k.anchors[t]={kind:`world`,p:Tj(V(w[n],i))},k.fits.push({side:e,anchor:t,effector:{prop:r,point:`fingers`}}),k.channels.push(d(n))})}return k}var kj={standIdle:Dk,sitInSeat:Bk,exitCar:Vk,walkTo:Ok,reachGrip:jk,smokeCigarette:vA,flip:LA,hitReaction:nj,throwObject:gj,catchObject:Oj},Aj=Object.keys(kj),jj=e=>{throw Error(`MOTION_SPEC_INVALID: ${e}`)},Mj=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Nj(e,t,n,r){for(let[i,a]of Object.entries(t??{}))e[i]&&!Mj(e[i],a)&&jj(`${r} defines ${n}.${i} differently from an earlier skill; rename one or define it yourself in spec.${n}`),e[i]=a}function Pj(e,t){for(let[n,r]of Object.entries(t??{})){if(n===`limits`&&r&&typeof r==`object`&&!Array.isArray(r)){e.limits={...e.limits,...r};continue}if(!Array.isArray(r)||e[n]!==void 0&&!Array.isArray(e[n])){e[n]=r;continue}let t=e[n]??(e[n]=[]);for(let e of r)t.some(t=>Mj(t,e))||t.push(e)}}var Fj=e=>!!e&&typeof e==`object`&&!Array.isArray(e)&&(e.range??e.search)!==void 0,Ij=e=>e.description?` (${e.description})`:``;function Lj(e,t,n){return!n||t===void 0||Fj(t)?null:n.enum&&!n.enum.includes(t)?`${e} must be one of ${n.enum.map(e=>JSON.stringify(e)).join(`, `)}${Ij(n)}, got ${Z(t)}${il(String(t),n.enum.map(String))}`:(n.type===`number`||n.type===`integer`)&&!Number.isFinite(t)?`${e} must be a number${Ij(n)}, got ${Z(t)}`:n.type===`string`&&typeof t!=`string`?`${e} must be a string${Ij(n)}, got ${Z(t)}`:n.type===`boolean`&&typeof t!=`boolean`?`${e} must be true or false${Ij(n)}, got ${Z(t)}`:n.type===`array`&&n.items?.type===`number`&&!(Array.isArray(t)&&t.length>=(n.minItems??0)&&t.every(e=>Number.isFinite(e)||Fj(e)))?`${e} must be ${n.minItems===2?`[x, z]`:n.minItems===3?`[x, y, z]`:`an array of numbers`}${Ij(n)}, got ${Z(t)}`:null}function Rj(e,t=!1){if(!Array.isArray(e.use))return[`spec.use must be an array of { skill, args, f0 }`];let n=[];return e.use.forEach((r,i)=>{if(!r||typeof r!=`object`||Array.isArray(r))return n.push(`use[${i}] must be { skill, args, f0 }, got ${Z(r)}`);if(!kj[r.skill])return n.push(`use[${i}].skill "${r.skill}" is not a skill${il(String(r.skill),Aj)} (skills: ${Aj.join(`, `)})`);if(!t)for(let e of Object.keys(r))yl.includes(e)||n.push(`use[${i}] has unknown field "${e}"${tl(e,yl)}; an entry is { skill, args, f0 }`);if(r.args!==void 0&&(!r.args||typeof r.args!=`object`||Array.isArray(r.args)))n.push(`use[${i}].args must be an object, got ${JSON.stringify(r.args)}`);else if(!t){let e=QD[r.skill],t=Object.keys(e.args);for(let[a,o]of Object.entries(r.args??{}))if(!t.includes(a))n.push(`use[${i}].args.${a} is not an arg of ${r.skill}${tl(a,t)} (args: ${t.join(`, `)})`);else{let t=Lj(`use[${i}].args.${a}`,o,e.args[a]);t&&n.push(t)}for(let t of e.required??[])r.args?.[t]===void 0&&n.push(`use[${i}] ${r.skill} needs args.${t}${Ij(e.args[t])}`)}(!Number.isInteger(r.f0)||r.f0<0)&&n.push(`use[${i}].f0 must be an integer frame within 0..${e.frames-1}, got ${JSON.stringify(r.f0)}`)}),n}function zj(e,{sk:t,scene:n,lenient:r=!1,auto:i=!1,fit:a}){if(!e.use?.length)return{spec:e,used:[]};let o=Rj(e,r);o.length&&jj(o.join(`
|
|
8
|
+
`));let s=(e.keys??[]).map((e,t)=>({...e,src:`keys[${t}]`})),c={anchors:{},props:{},objects:{},fits:[],checks:{},channels:[],fills:{},goals:[]},l=[],u=[];e.use.forEach((r,o)=>{let d=`use[${o}] ${r.skill}`;r.f0>e.frames-1&&jj(`use[${o}].f0 must be an integer frame within 0..${e.frames-1}, got ${JSON.stringify(r.f0)}`);let f=[...l,...s],p={sk:t,scene:n,frames:e.frames,fps:e.fps??24,auto:i,fit:a,props:{...c.props,...e.props},self:e.fix!==!1&&e.fix?.self!==!1,f0:r.f0,args:structuredClone(r.args??{}),tag:d,keys:f,use:e.use,index:o,place:Ax(e.fix).stance,state:structuredClone(Fy(f,r.f0)),anchors:{...c.anchors,...e.anchors},objects:{...c.objects,...e.objects}},m=kj[r.skill](p),h=Math.max(m.end??r.f0,...m.keys.map(e=>e.f));h>e.frames-1&&jj(`${d} needs ${h-r.f0} frames from f${r.f0} (to f${h}), past the last frame f${e.frames-1}; set frames >= ${h+1} or frames: "auto"`),l.push(...m.keys.map(e=>({...e,src:e.src??d}))),Nj(c.anchors,m.anchors,`anchors`,d),Nj(c.props,m.props,`props`,d),Nj(c.objects,m.objects,`objects`,d);for(let e of m.fits??[])c.fits.some(t=>Mj(t,e))||c.fits.push(e);for(let e of m.channels??[])c.channels.includes(e)||c.channels.push(e);Pj(c.checks,m.checks);for(let[e,t]of Object.entries(m.fills??{}))c.fills[e]={...c.fills[e],...t};c.goals.push(...m.goals??[]),u.push({skill:r.skill,f0:r.f0,end:m.end,...m.paced?{paced:m.paced}:{},...m.cut?{cut:m.cut}:{},...m.placed?{placed:m.placed}:{},...m.adjust?{adjust:m.adjust}:{}})});let d={...e,keys:[...l,...s],anchors:{...c.anchors,...e.anchors},props:{...c.props,...e.props},objects:{...c.objects,...e.objects}},f=[...new Set([...c.channels,...Array.isArray(e.channels)?e.channels:[]])];f.length&&(d.channels=f);let p=e.fits??[];d.fits=[...c.fits.filter(e=>!p.some(t=>t.side===e.side&&t.anchor===e.anchor)),...p],Pj(c.checks,e.checks),d.checks=c.checks;for(let[e,t]of Object.entries(c.fills))d.objects[e]&&(d.objects[e]={...t,...d.objects[e]});return c.goals.length&&(d.goals=[...c.goals,...e.goals??[]]),delete d.use,{spec:d,used:u}}var Bj=new Set([`f`,`f0`,`steps`,`period`,`swing`,`until`,`reach`,`hold`,`release`]),Vj=e=>e&&typeof e==`object`&&!Array.isArray(e)&&(e.range??e.search)!==void 0&&Object.keys(e).every(e=>[`range`,`search`,`int`].includes(e)),Hj=e=>e.reduce((e,t)=>typeof t==`number`?`${e}[${t}]`:e?`${e}.${t}`:t,``);function Uj(e){let t=[],n=(e,r)=>{if(Vj(e)){let n=e.range??e.search;if(!(Array.isArray(n)&&n.length===2&&n.every(Number.isFinite)&&n[0]<n[1]))throw Error(`MOTION_SPEC_INVALID: ${Hj(r)} range must be [lo, hi] with lo < hi, got ${JSON.stringify(n)}`);t.push({path:r,lo:n[0],hi:n[1],int:e.int??Bj.has(r[r.length-1])});return}if(Array.isArray(e))e.forEach((e,t)=>n(e,[...r,t]));else if(e&&typeof e==`object`)for(let[t,i]of Object.entries(e))n(i,[...r,t])};for(let[t,r]of Object.entries(e??{}))[`schema`,`fps`,`frames`,`search`].includes(t)||n(r,[t]);return t}var Wj=(e,t)=>{let n=Math.min(e.hi,Math.max(e.lo,t));return e.int?Math.round(n):Math.round(n*1e4)/1e4};function Gj(e,t,n){let r=structuredClone(e);return t.forEach((e,t)=>{let i=r;for(let t of e.path.slice(0,-1))i=i[t];i[e.path[e.path.length-1]]=n[t]}),r}var Kj=e=>e.groups.reduce((e,t)=>e+cD(t),0);function qj(e,t,n,r,i){let a=n=>r(Gj(e,t,n)),o=a(n),s=e=>JSON.stringify({...e,keys:void 0,generators:void 0}),c=e=>Vf(Ly(e,i),e.frames,Rf(e.flow)),l=c(o),u=1/0,d=-1/0;for(let r=0;r<t.length;r++)for(let i of[t[r].lo,t[r].hi]){let f=a(n.map((e,n)=>n===r?Wj(t[r],i):e));if(s(f)!==s(o))return null;let p=c(f);for(let t of new Set([...Object.keys(l),...Object.keys(p)])){let n=l[t],r=p[t];for(let t=0;t<e.frames;t++)JSON.stringify(n?.[t])!==JSON.stringify(r?.[t])&&(u=Math.min(u,t),d=Math.max(d,t))}}return u>d?null:[Math.max(0,u-8),Math.min(e.frames-1,d+8)]}var Jj=[2,3,5,7,11,13,17,19,23,29],Yj=(e,t)=>Array.from({length:t},(t,n)=>{let r=1,i=0,a=e,o=Jj[n%Jj.length];for(;a>0;)r/=o,i+=a%o*r,a=Math.floor(a/o);return i});function Xj(e,t,{sk:n,scene:r},i){let a=performance.now(),o=Math.max(1,Math.min(64,Math.round(e.search?.budget??32))),s=t.map(e=>Wj(e,(e.lo+e.hi)/2)),c=qj(e,t,s,i,n),l=new Map,u=0,d=null,f=a=>{let s=a.join(`,`);if(l.has(s))return l.get(s);if(u>=o)return 1/0;u++;let f;try{let o=i(Gj(e,t,a));f=Kj(mD(n,fS({fps:24,...o},{sk:n,scene:r},{window:c}),o,{explain:!1}))}catch(e){if(!/MOTION_SPEC_INVALID/.test(e.message))throw e;f=1e9}return l.set(s,f),(!d||f<d.cost)&&(d={values:a,cost:f}),f},p=()=>d?.cost===0||u>=o,m=e=>t.map((t,n)=>Wj(t,t.lo+(t.hi-t.lo)*e[n]));f(s);let h=t.length===1?[4,3,5,2,6,1,7,0,8].map(e=>[e/8]):Array.from({length:Math.min(o>>1,8*t.length)},(e,n)=>Yj(n+1,t.length));for(let e of h){if(p())break;f(m(e))}let g=t.map(e=>(e.hi-e.lo)/8);for(;!p()&&g.some((e,n)=>e>(t[n].int?.5:(t[n].hi-t[n].lo)*.001));){let e=!1;for(let n=0;n<t.length&&!p();n++)for(let r of[-1,1]){let i=d.values.slice();i[n]=Wj(t[n],i[n]+r*g[n]);let a=d.cost;f(i),d.cost<a&&(e=!0)}e||(g=g.map(e=>e/2))}return{spec:Gj(e,t,d.values),search:{values:Object.fromEntries(t.map((e,t)=>[Hj(e.path),d.values[t]])),evals:u,cost:Math.round(d.cost*100)/100,window:c,ms:Math.round(performance.now()-a)}}}var Zj=2e4;function Qj(e){let t=structuredClone(e);for(let n of Uj(e)){let e=t;for(let t of n.path.slice(0,-1))e=e[t];e[n.path[n.path.length-1]]=n.hi}return t}function $j(e,{sk:t,scene:n,lenient:r=!1}={}){if(e?.frames!==`auto`)return e;let{spec:i,used:a}=zj({...Qj(e),frames:Zj},{sk:t,scene:n,lenient:r,auto:!0}),o=[...Array.isArray(i.keys)?i.keys.map(e=>e?.f):[],...a.map(e=>e.end),...Array.isArray(i.generators)?i.generators.map(e=>e&&Number.isFinite(e.f0)?JD(e):null):[]];return{...e,frames:Math.max(0,...o.filter(Number.isFinite))+1}}var eM=new WeakSet;function tM(e){return eM.add(e),e}var nM=e=>Array.isArray(e)?`[${e.map(nM).join(`,`)}]`:e&&typeof e==`object`?`{${Object.keys(e).sort().filter(t=>e[t]!==void 0).map(t=>`${JSON.stringify(t)}:${nM(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`;function rM(e){let t=14695981039346656037n;for(let n of new TextEncoder().encode(nM(e)))t=BigInt.asUintN(64,(t^BigInt(n))*1099511628211n);return`spec-${t.toString(16).padStart(16,`0`).slice(0,12)}`}function iM(e=64){let t=new Map,n=Math.max(1,e),r=(e,r)=>{for(t.delete(e),t.set(e,r);t.size>n;)t.delete(t.keys().next().value);return r},i=e=>t.has(e)?r(e,t.get(e)):null;return{put(e){let n=rM(e),i=t.get(n);return r(n,{...i,spec:structuredClone(e),framesAuto:eM.has(e)||i?.framesAuto===!0}),n},get(e){let t=i(e);return t?.spec?{...structuredClone(t.spec),...t.framesAuto?{frames:`auto`}:{}}:null},keepParts(e,n){r(e,{...t.get(e),parts:n})},parts(e){return i(e)?.parts??null}}}var aM=12,oM=4,sM=3,cM=5e-4,lM=e=>Math.round(e*1e3)/1e3,uM=e=>Math.round(e*10)/10,dM=e=>e.map(lM);function fM(e,t,n){let r=e.frameCount-1,i=e.timeMap??(e=>e),a=t.map((e,t)=>({beat:e.skill,src:`use[${t}]`,f:[e.f0,e.end??e.f0]}));(n.generators??[]).forEach((e,t)=>a.push({beat:e.type,src:`generators[${t}]`,f:[e.f0,e.f0+16+(e.steps??8)*(e.period??20)+18]}));let o=e=>a.some(t=>e>=t.f[0]&&e<=t.f[1]),s=[...new Set((n.keys??[]).map(e=>e.f))].filter(e=>Number.isFinite(e)&&!o(e)).sort((e,t)=>e-t),c=null;for(let e of s)c&&!a.some(t=>t.src!==`keys`&&t.f[1]>c.f[1]&&t.f[0]<e)?c.f[1]=e:a.push(c={beat:`keys`,src:`keys`,f:[e,e]});let l=e=>Math.max(0,Math.min(r,Math.round(i(e))));for(let e of a)e.f=[l(e.f[0]),l(e.f[1])];return a.sort((e,t)=>e.f[0]-t.f[0]).slice(0,aM)}function pM(e){let t=e.frameCount,n=e.f0??0,r={l:new Uint8Array(t),r:new Uint8Array(t)};for(let[t,i]of[[`l`,`Left`],[`r`,`Right`]]){let a=e.frames.map((t,n)=>t?mu(e,n,i):null);a.forEach((e,i)=>{let o=a[i>0?i-1:i+1];if(!e||!o)return;let s=[`heel`,`ball`].some(t=>e[t][1]<rd.plantH&&Math.abs(e[t][1]-o[t][1])<cM&&Math.hypot(e[t][0]-o[t][0],e[t][2]-o[t][2])<=rd.slide);r[t][n+i]=+!!s})}return r}function mM(e,[t,n]){let r=[],i=null;for(let a=t;a<=n+1;a++){let t=a<=n&&e[a]===1;t&&i===null&&(i=a),!t&&i!==null&&(a-i>=sM&&r.push([i,a-1]),i=null)}if(r.length<=oM)return r;let a=r.slice(1,-1).sort((e,t)=>t[1]-t[0]-(e[1]-e[0])||e[0]-t[0]).slice(0,2);return[r[0],...a,r[r.length-1]].sort((e,t)=>e[0]-t[0])}function hM(e,t){let n=e.frameCount,r=[],i=Object.entries(t.objects??{});for(let[e,t]of i)for(let i=1;i<n;i++){let n=cg(t,i-1),a=cg(t,i);a&&!n&&r.push({f:i,object:e,event:`grab`}),n&&!a&&r.push({f:i-1,object:e,event:`release`})}let a={};for(let[e,t]of i)typeof t?.visible==`string`&&(a[t.visible]??=[]).push(e);for(let t of new Set([...Object.keys(a),...Object.keys(e.baked??{}).filter(e=>e.endsWith(`_vis`))])){let i=e.baked?.[t];if(i)for(let e=1;e<n;e++){let n=i[e-1]>.5,o=i[e]>.5;if(n!==o)for(let n of a[t]??[t])r.push({f:e,object:n,event:o?`show`:`hide`})}}return r.sort((e,t)=>e.f-t.f)}function gM(e,t,n,r){for(let[t,i]of Object.entries(e.objects??{}))if(e.props?.[i?.prop]?.hand===n&&cg(i,r))return`object:${t}`;let i=null,a=.5;for(let[e,r]of Object.entries(t)){let t=/^w_(.+)_([lr])$/.exec(e);t&&t[2]===n&&r>a&&(i=t[1],a=r)}return i&&`anchor:${i}`}function _M(e,t,n){let r=e.frames[n-(e.f0??0)];if(!r)return null;let{s:i,c:a}=r,o=e.ctx.sk.index;return{root:dM(i.P[o.Hips]),yaw:uM(a.yaw??0),hand_l:dM(i.P[o.LeftHand]),hand_r:dM(i.P[o.RightHand]),on_l:gM(t,a,`l`,n),on_r:gM(t,a,`r`,n)}}function vM(e,{used:t,spec:n}){let r=fM(e,t??[],n);if(!r.length)return[];let i=pM(e),a=hM(e,n);return r.map(t=>({...t,end:_M(e,n,t.f[1]),planted:{l:mM(i.l,t.f),r:mM(i.r,t.f)},events:a.filter(e=>e.f>=t.f[0]&&e.f<=t.f[1])}))}var yM=e=>`[${e[0]},${e[1]}]`,bM=(e,t)=>{e&&!e.includes(t)&&e.push(t)};function xM(e,t){if(!(Array.isArray(e)&&e.length===2&&e.every(Number.isInteger)&&e[0]<=e[1]))return null;let n=Math.max(0,e[0]),r=Math.min(t,e[1]);return n<=r?[n,r]:null}function SM(e,t){if(!Array.isArray(e.goals)||!Number.isInteger(e.frames))return;let n=e.frames-1;e.goals.forEach((e,r)=>{if(!e||typeof e!=`object`||!Array.isArray(e.at))return;let i=xM(e.at,n);!i||i[0]===e.at[0]&&i[1]===e.at[1]||(bM(t,`goals[${r}]${e.name?` "${e.name}"`:``} at ${yM(e.at)} -> ${yM(i)}: the clip is 0..${n}`),e.at=i)})}var CM=e=>e.rot===void 0?{aim:e.aim,...e.roll===void 0?{}:{roll:e.roll},...e.lean===void 0?{}:{lean:e.lean}}:{rot:e.rot},wM=e=>e&&(e.rot!==void 0||e.aim!==void 0),TM=e=>e&&typeof e==`object`&&!Array.isArray(e)&&!wM(e)&&e.roll===void 0&&e.lean===void 0;function EM(e,t,n,r){let i=t.keys.map((e,t)=>({k:e,i:t})).filter(({k:e})=>e&&Number.isInteger(e.f)).sort((e,t)=>e.k.f-t.k.f),a=i.filter(({k:e})=>TM(e));if(!a.length)return;let o=n?.objects?.[e]??Jl(n??{})[e],s=o?b_(t)?{aim:[o.R[0][1],o.R[1][1],o.R[2][1]].map(e=>Math.round(e*1e4)/1e4)}:{rot:Do(o.R)}:null,c=i.filter(e=>wM(e.k)),l=[],u=[];for(let{k:e,i:t}of a){let n=c.filter(t=>t.k.f<e.f).at(-1)??c.find(t=>t.k.f>e.f);n?(Object.assign(e,CM(n.k)),l.push(t)):s&&(Object.assign(e,s),u.push(t))}l.length&&bM(r,`objects.${e}.keys[${l.join(`,`)}] had no rot or aim: each holds the turn of the nearest key before it (else after)`),u.length&&bM(r,`objects.${e}.keys[${u.join(`,`)}] had no rot or aim: ${s.aim?`+Y as in the scene, aim [${s.aim}]`:`turned as in the scene`}`)}function DM(e,t,n){t.keys.forEach((t,r)=>{if(!Array.isArray(t?.rot)||t.rot.length!==4||!t.rot.every(Number.isFinite))return;let i=Math.hypot(...t.rot);Math.abs(i-1)<=.01||i<=.5||i>=2||(t.rot=t.rot.map(e=>e/i),bM(n,`objects.${e}.keys[${r}].rot had length ${i.toFixed(3)}: normalized`))})}var OM=e=>e.map(e=>Math.round(e*1e3)/1e3);function kM(e,t){Array.isArray(e.keys)&&e.keys.forEach((n,r)=>{for(let i of[`knee_l`,`knee_r`]){let a=n?.set?.[i];if(!(Array.isArray(a)&&a.length===3&&a.every(Number.isFinite)))continue;let o=Math.hypot(...a);if(!(o>1e-6&&a[2]<-.7*o))continue;let s=Fy(e.keys,n.f).yaw;if(!(Number.isFinite(s)&&Math.abs((s%360+540)%360-180)>=90))continue;let c=OM(J(X(-s),a));c[2]<.7*o||(n.set[i]=c,bM(t,`corrected: ${n.src?.startsWith(`keys[`)?n.src:`keys[${r}]`} (f${n.f}) ${i} [${OM(a)}] is a world direction at root yaw ${Math.round(s)}: body frame [${c}] (a pole is +z forward)`))}})}function AM(e,t,n){Array.isArray(e.goals)&&e.goals.forEach((r,i)=>{for(let a of[`near`,`above`])(Array.isArray(r?.[a])?r[a]:[]).forEach((o,s)=>{if(typeof o!=`string`||/^[a-z]+:/.test(o))return;let c=$d(e,t,o);c.length===1&&(r[a][s]=c[0],bM(n,`corrected: goals[${i}].${a}[${s}] "${o}" -> "${c[0]}"`))})})}function jM(e,t,n,r){if(!e||typeof e!=`object`)return e;SM(e,n),AM(e,{sk:r,scene:t},n),kM(e,n);for(let[r,i]of Object.entries(e.objects??{}))!i||typeof i!=`object`||!Array.isArray(i.keys)||!(b_(i)||Ph(i))||(EM(r,i,t,n),DM(r,i,n));return e}function MM(e,t,n,r){let i=Number.isInteger(e)?[e,e]:e,a=xM(i,t);return a&&(a[0]!==i[0]||a[1]!==i[1])&&bM(r,`${n}.frames ${yM(i)} -> ${yM(a)}: the take is 0..${t}`),a}function NM(e,t,n,r,i){if(Math.ceil(t/e)<=n)return e;let a=Math.ceil(t/n);return bM(i,`${r}.every ${e} -> ${a}: a position probe answers at most ${n} rows`),a}function PM(e,[t,n]){let r=e.filter(e=>e<t||e>n),i=[...new Set(e.map(e=>Math.min(n,Math.max(t,e))))].sort((e,t)=>e-t);return r.length?{frames:i,adjusted:`frames ${r.join(`, `)} lie outside ${t}..${n}: drawn at ${i.filter(e=>e===t||e===n).join(`, `)}`}:{frames:i}}var FM={always:!0,yes:!0,true:!0,on:!0,never:`never`,no:`never`,false:`never`,off:`never`,none:`never`,ifclean:`ifClean`,whenclean:`ifClean`,onlyifclean:`ifClean`,clean:`ifClean`};function IM(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;if(typeof e.install==`string`&&e.install!==`ifClean`&&e.install!==`never`){let n=FM[e.install.toLowerCase().replace(/[^a-z]/g,``)];n!==void 0&&(t={...t,install:n})}return e.repair===!0?t={...t,repair:{}}:(e.repair===!1||e.repair&&typeof e.repair==`object`&&e.repair.rounds===0&&Object.keys(e.repair).length===1)&&(t=Object.fromEntries(Object.entries(t).filter(([e])=>e!==`repair`))),t}var LM=16,RM=16,zM=12,BM=`{ name, distance: [refA, refB] | position: ref, frames: [f0, f1], every }`,VM=e=>Math.round(e*1e6)/1e6,HM=e=>Math.round(e*1e4)/1e4;function UM(e,t){let n=/^(joint|bone):(.+)$/s.exec(t);return n?`${n[1]}:${Bl(e,n[2]).bone??n[2]}`:t}function WM(e,t,n,r,i){let a=e.frames===void 0?[0,n]:MM(e.frames,n,t,i);return a||r(`${t}.frames must be [f0, f1], integer frames within 0..${n} with f0 <= f1, got ${Z(e.frames)}`),a}function GM(e,t,{spec:n,sk:r,scene:i,notes:a}){let o=[],s=e=>{o.length<zM&&o.push(e)},c=e.frameCount-1,l=[],u=new Map;if(Array.isArray(t)?t.length>LM?s(`probes has ${t.length} entries; at most ${LM} per compile`):t.forEach((e,t)=>{let o=`probes[${t}]`;if(!e||typeof e!=`object`||Array.isArray(e))return s(`${o} must be ${BM}`);for(let t of Object.keys(e))jl.includes(t)||s(`${o} has unknown field "${t}"${il(t,jl)}; a probe is ${BM}`);let d=e.name??o;if(typeof d!=`string`||!d?s(`${o}.name must be a non-empty string, got ${Z(e.name)}`):u.has(d)?s(`${o}.name "${d}" is already used by ${u.get(d)}; probe names must differ`):u.set(d,o),e.distance===void 0==(e.position===void 0))return s(`${o} needs exactly one of distance: [refA, refB] or position: ref`);let f=e.distance===void 0?`position`:`distance`,p=f===`distance`?e.distance:[e.position];if(f===`distance`&&!(Array.isArray(p)&&p.length===2&&p.every(e=>typeof e==`string`)))return s(`${o}.distance must be [refA, refB], two point refs, got ${Z(e.distance)}`);if(f===`position`&&typeof e.position!=`string`)return s(`${o}.position must be a point ref, got ${Z(e.position)}`);let m=p.map((e,t)=>tf(n,s,{sk:r,scene:i},f===`distance`?`${o}.distance[${t}]`:`${o}.position`,e)).every(Boolean),h=WM(e,o,c,s,a);if(e.every!==void 0&&!(Number.isInteger(e.every)&&e.every>=1))return s(`${o}.every must be a positive integer, got ${Z(e.every)}`);if(!m||!h)return;let g=h[1]-h[0]+1,_=e.every??(f===`position`?Math.ceil(g/RM):1),v=f===`position`?NM(_,g,RM,o,a):_;l.push({name:d,kind:f,refs:p.map(e=>UM(r,e)),range:h,every:v})}):s(`probes must be an array of ${BM}`),o.length)throw Error(`MOTION_SPEC_INVALID: ${o.join(`
|
|
9
|
+
`)}${o.length>=zM?`
|
|
10
|
+
(more problems not listed)`:``}`);return l}function KM([e,t],n){let r=[];for(let i=e;i<=t;i+=n)r.push(i);return r}function qM(e,t){let n=KM(t.range,t.every).map(n=>[n,Qd(e,n,t.refs[0],t.refs[1])]).filter(([,e])=>Number.isFinite(e));if(!n.length)return{min:null,minAt:null,max:null,maxAt:null,mean:null,first:null,last:null};let r=n[0],i=n[0],a=0;for(let e of n)e[1]<r[1]&&(r=e),e[1]>i[1]&&(i=e),a+=e[1];return{min:VM(r[1]),minAt:r[0],max:VM(i[1]),maxAt:i[0],mean:VM(a/n.length),first:VM(n[0][1]),last:VM(n[n.length-1][1])}}function JM(e,t){return{at:KM(t.range,t.every).map(n=>{let r=Zd(e,n,t.refs[0]);return{f:n,p:r?r.map(HM):null}})}}function YM(e,t,n){return Object.fromEntries(GM(e,t,n).map(t=>[t.name,t.kind===`distance`?qM(e,t):JM(e,t)]))}var XM=.3,ZM=2,QM=[`Thumb4`,`Index4`,`Middle4`,`Ring4`,`Pinky4`],$M=e=>Math.round(e*1e3)/1e3,eN=`near: hand (palm, fingertips), foot (sole) to the nearest object within 0.3 m (top group; part: the body at the closest frame), 2 closest runs; gap [min, f, max, f] m, < 0 inside`;function tN(e,t){let n=e.index,r={};for(let[i,a]of[[`Left`,`l`],[`Right`,`r`]]){let o=U(V(t.P[n[`${i}Hand`]],t.P[n[`${i}HandMiddle1`]]),.5);r[`hand_${a}`]=[o,...QM.map(e=>t.P[n[`${i}Hand${e}`]]).filter(Boolean)],r[`foot_${a}`]=Object.values(kc(e,t,i))}return r}var nN=(e,t,n)=>[t,...e.ctx.scene.objects[t].ancestors??[]].some(t=>{let r=e.ctx.spec.objects?.[t];return r?.visible&&!((e.baked?.[r.visible]?.[n]??0)>.5)});function rN(e,t){let{scene:n,spec:r}=e.ctx,i=[];for(let[a,o]of Object.entries(n?.objects??{})){let n=o.ancestors??[];if([a,...n].some(e=>x_(r.objects?.[e]))||nN(e,a,t))continue;let s=kg(e,a,t);if(!s)continue;let c={pos:s.pos,R:s.R,half:o.half};i.push({id:a,root:n[n.length-1]??a,hand:Og(e,a,t),box:c,c:V(c.pos,J(c.R,[0,o.half[1],0])),r:G(o.half)})}return i}function iN(e,t,n){let r=U(e.reduce((e,t)=>V(e,t),[0,0,0]),1/e.length),i=Math.max(...e.map(e=>go(e,r))),a=null;for(let o of t){if(n&&o.hand===n||go(r,o.c)-o.r-i>(a?a[2]:XM))continue;let t=Math.min(...e.map(e=>wc(e,o.box)));t<=XM&&(!a||t<a[2])&&(a=[o.root,o.id,t])}return a}function aN(e,t){let n=[];return e.forEach((e,r)=>{let i=n[n.length-1];if(!e)return;let[a,o,s]=e,c=r+t;i&&i.object===a&&i.frames[1]===c-1?(i.frames[1]=c,s<i.gap[0]&&(i.gap[0]=s,i.gap[1]=c,i.part=o),s>i.gap[2]&&(i.gap[2]=s,i.gap[3]=c)):n.push({object:a,part:o,frames:[c,c],gap:[s,c,s,c]})}),n.sort((e,t)=>e.gap[0]-t.gap[0]).slice(0,ZM).sort((e,t)=>e.frames[0]-t.frames[0]).map(({object:e,part:t,frames:n,gap:r})=>({object:e,...t===e?{}:{part:t},frames:n,gap:[$M(r[0]),r[1],$M(r[2]),r[3]]}))}function oN(e,t){if(!Object.keys(t.ctx.scene?.objects??{}).length)return null;let n=t.f0??0,r={hand_l:[],hand_r:[],foot_l:[],foot_r:[]};t.frames.forEach(({s:i},a)=>{let o=rN(t,a+n),s=tN(e,i);for(let e of Object.keys(r))r[e].push(iN(s[e],o,e.startsWith(`hand_`)?e.slice(-1):null))});let i=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,aN(t,n)]).filter(([,e])=>e.length));return Object.keys(i).length?i:null}var sN=[`Hips`,`Spine`,`Spine2`,`Head`,`LeftArm`,`RightArm`,`LeftForeArm`,`RightForeArm`,`LeftHand`,`RightHand`,`LeftUpLeg`,`RightUpLeg`,`LeftLeg`,`RightLeg`,`LeftFoot`,`RightFoot`],cN=.25,lN=3,uN=.2,dN=4,fN=.6,pN=3,mN=.15,hN=4,gN=.7,_N=4,vN=20,yN=.25,bN=.005,xN=48,SN=.9,CN=15,wN=1e-4,TN=10,EN=15,DN=e=>Math.round(e*100)/100,ON=`life (warnings, not QA): [share or s, worst f0, f1]; keys [gap cv, even channels, half-second share]; jerk [p95 m/s^3, joint, spikes]; lead [frames the head turns before the pelvis, correlation]`,kN=e=>{let t=[...e].sort((e,t)=>e-t);return t.length?t[Math.min(t.length-1,Math.floor(.95*t.length))]:0},AN=e=>{let t=e.reduce((e,t)=>e+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return t>0?Math.sqrt(n)/t:0};function jN(e,t){let n=e.length,r=e.reduce((e,t)=>e+t,0)/n,i=t.reduce((e,t)=>e+t,0)/n,a=0,o=0,s=0;for(let c=0;c<n;c++)a+=(e[c]-r)*(t[c]-i),o+=(e[c]-r)**2,s+=(t[c]-i)**2;return o>0&&s>0?a/Math.sqrt(o*s):0}function MN(e,t){let n=e.index,r=t.length,i=180/Math.PI;return sN.map(a=>{let o=n[a],s=a===`Hips`?-1:e.parent[o],c=new Float64Array(r),l=new Float64Array(9),u=new Float64Array(9);for(let e=0;e<r;e++){let{R:n,P:r}=t[e].s,a=n[o],d=s<0?null:n[s];for(let e=0;e<3;e++)for(let t=0;t<3;t++)l[e*3+t]=d?d[0][e]*a[0][t]+d[1][e]*a[1][t]+d[2][e]*a[2][t]:a[e][t];if(e){let n=0;for(let e=0;e<9;e++)n+=l[e]*u[e];let a=Math.acos(Math.max(-1,Math.min(1,(n-1)/2)))*i,d=t[e-1].s.P[o];c[e]=s<0?Math.max(a,Math.hypot(r[o][0]-d[0],r[o][1]-d[1],r[o][2]-d[2])*100):a}[l,u]=[u,l]}return c})}function NN(e,t){let n=[],r=-1,i=0;for(let a=1;a<t;a++)e.some(e=>e[a]>cN)?(r<0&&(r=a),i=0):r>=0&&++i>=lN&&(n.push([r,a-i]),r=-1,i=0);return r>=0&&n.push([r,t-1-i]),n.filter(([e,t])=>t-e>=3)}function PN(e,t,n){let r=[[],[]];e.forEach((e,i)=>{let a=[...e].filter(e=>e>cN).sort((e,t)=>e-t),o=Math.max(cN,uN*(a[Math.floor(.9*a.length)]??0)),s=t=>e[t]>o;for(let e=1;e<n;e++)if(!t[e]){if(s(e)&&!s(e-1)){let t=1;for(;t<=lN&&e-t>=0&&!s(e-t);)t++;(t>lN||e-t<0)&&r[0].push([e,i])}if(!s(e)&&s(e-1)){let t=0;for(;t<lN&&e+t<n&&!s(e+t);)t++;t>=lN&&e+t<n&&r[1].push([e-1,i])}}});let i=0,a=0,o=null;for(let e of r){e.sort((e,t)=>e[0]-t[0]);for(let t=0;t<e.length;){let n=t+1;for(;n<e.length&&e[n][0]-e[n-1][0]<=pN;)n++;let r=e.slice(t,n),s=new Set(r.map(e=>e[1])).size;if(t=n,s<dN)continue;let c=0,l=r[0][0];for(let e=0,t=0;t<r.length;t++){for(;r[t][0]-r[e][0]>2;)e++;let n=new Set(r.slice(e,t+1).map(e=>e[1])).size;n>c&&(c=n,l=r[e][0])}i++,c>=Math.max(dN,Math.ceil(fN*s))&&a++,(!o||c/s>o.share||c/s===o.share&&c>o.k)&&(o={share:c/s,k:c,of:s,at:[l,l+2]})}}return{score:i?DN(a/i):0,total:i,worst:o}}function FN(e,t){let n=new Map,r=new Set;for(let t of e??[])if(Number.isFinite(t?.f)){r.add(t.f);for(let e of Object.keys(t.set??{}))(n.get(e)??n.set(e,new Set).get(e)).add(t.f)}let i=e=>{let t=[...e].sort((e,t)=>e-t);return t.slice(1).map((e,n)=>e-t[n])},a=[...n].filter(([,e])=>e.size>=hN),o=a.filter(([,e])=>AN(i(e))<mN).map(([e])=>e),s=[...r].filter(e=>e>0),c=Math.round(t/2);return{cv:r.size>=hN?DN(AN(i(r))):null,grid:o,eligible:a.length,halfSec:s.length>=hN?DN(s.filter(e=>e%c===0).length/s.length):null}}function IN(e,t,n,r){let i=r**3,a=[0,null],o=null,s=new Set;for(let r of sN){let c=t.map(t=>t.s.P[e.index[r]]),l=new Float64Array(t.length),u=[];for(let e=3;e<t.length;e++){let t=t=>c[e][t]-3*c[e-1][t]+3*c[e-2][t]-c[e-3][t];l[e]=Math.hypot(t(0),t(1),t(2))*i,n[e]&&u.push(l[e])}let d=kN(u);d>a[0]&&(a=[DN(d),r]);for(let e=3;e<t.length;e++){if(l[e]<=Math.max(vN,_N*d))continue;s.add(e);let t=l[e]/Math.max(d,1e-9);(!o||t>o.ratio)&&(o={ratio:t,f:e,j:r})}}return{p95:a,spikes:s.size,worst:o}}function LN(e,t,n,r){let i=e.index,a=t.P,o=H(a[i.Spine2],a[i.Hips]),s=(e,t)=>Math.acos(Math.max(-1,Math.min(1,(e[0]*t[0]+e[1]*t[1]+e[2]*t[2])/Math.max(1e-9,G(e)*G(t)))))*180/Math.PI,[c,l,u]=r?[`${n}Arm`,`${n}ForeArm`,`${n}Hand`]:[`${n}UpLeg`,`${n}Leg`,`${n}Foot`],d=H(a[i[l]],a[i[c]]);return[s(d,H(a[i[u]],a[i[l]])),s(d,r?o:[-o[0],-o[1],-o[2]])]}function RN(e,t,n){let r={};for(let[i,a]of[[`arms`,!0],[`legs`,!1]]){let o=t.map(({s:t})=>LN(e,t,`Left`,a)),s=t.map(({s:t})=>LN(e,t,`Right`,a)),c=0,l=0,u=null;for(let e=1;e+xN<=t.length;e+=xN/4){if(n.slice(e,e+xN).some(Boolean))continue;let t=[],r=[];for(let n=e;n<e+xN;n++)for(let e=0;e<2;e++)t.push(o[n][e]-o[n-1][e]),r.push(s[n][e]-s[n-1][e]);let i=e=>e.reduce((e,t)=>e+Math.abs(t),0);if(i(t)<CN||i(r)<CN)continue;let a=jN(t,r);c++,a>SN&&l++,(!u||a>u.c)&&(u={c:a,at:[e,e+xN-1]})}r[i]={score:c?DN(l/c):0,windows:c,worst:u}}return r}function zN(e,t,n,r){let i=new Uint8Array(t.length);for(let e of n.goals??[]){let n=Array.isArray(e?.at)?e.at:null;if(e?.still!==void 0&&n?.length)for(let e=Math.max(0,Math.round(n[0]));e<=Math.min(t.length-1,Math.round(n[n.length-1]));e++)i[e]=1}let a=null,o=0;for(let n=1,s=-1;n<=t.length;n++){if(n<t.length&&!i[n]&&e.names.every((e,r)=>G(H(t[n].s.P[r],t[n-1].s.P[r]))<wN)){s<0&&(s=n);continue}s>=0&&n-s>=r&&(o+=n-s,(!a||n-s>a[1]-a[0]+1)&&(a=[s,n-1])),s=-1}return{frames:o,best:a}}function BN(e,t){let n=e.index,r=t.length,i=180/Math.PI,a=e=>e-360*Math.round(e/360),o=t.map(({s:e})=>{let t=e.P[n.LeftUpLeg],r=e.P[n.RightUpLeg];return Math.atan2(r[0]-t[0],r[2]-t[2])*i}),s=t.map(({s:e})=>{let t=e.R[n.Head];return Math.atan2(t[0][2],t[2][2])*i}),c=o.map((e,t)=>t?a(e-o[t-1]):0),l=s.map((e,t)=>t?a(e-s[t-1]):0),u=0,d=0,f=0;for(let e of c)u+=e,d=Math.min(d,u),f=Math.max(f,u);if(r<=40||f-d<EN)return null;let p=null;for(let e=-10;e<=TN;e++){let t=0,n=0,i=0;for(let a=12;a<r-TN-2;a++)t+=c[a]*l[a-e],n+=c[a]**2,i+=l[a-e]**2;let a=n>0&&i>0?t/Math.sqrt(n*i):0;(!p||a>p[1])&&(p=[e,a])}return[p[0],DN(p[1])]}function VN(e,t,n){let r=t.frames,i=r.length,a=t.fps??24,o=t.f0??0,s=t.ctx.spec,c=e.index,l=[],u=MN(e,r),d=NN(u,i),f=new Uint8Array(i);for(let[e,t]of d)f.fill(1,e,t+1);let p=new Uint8Array(i),m=xN/2;for(let e=1;e<i;e++){let t=r[e].s.P[c.Hips],n=r[e-1].s.P[c.Hips];Math.hypot(t[0]-n[0],t[2]-n[2])*a>yN&&p.fill(1,Math.max(0,e-m),Math.min(i,e+m))}let h=p.slice();for(let e=1;e<i;e++)[`LeftFoot`,`RightFoot`].every(t=>G(H(r[e].s.P[c[t]],r[e-1].s.P[c[t]]))>bN)&&h.fill(1,Math.max(0,e-m),Math.min(i,e+m));let g=PN(u,p,i),_=FN(n,a),v=IN(e,r,f,a),y=RN(e,r,h),b=zN(e,r,s,a),x=([e,t])=>`f${e+o}-${t+o}`;g.total>=2&&g.score>=.5&&l.push([g.score,`sync`,`${g.worst.k} of ${g.worst.of} parts start or stop together ${x(g.worst.at)}: lead with pelvis or a hand, spine/head/arms 2-4 frames later`]),(_.cv!==null&&_.cv<mN||_.eligible&&_.grid.length/_.eligible>=.5||(_.halfSec??0)>=gN)&&l.push([.9,`keys`,`keys on a grid: key the extremes (contact, peak, turn), vary the gaps`]),v.worst&&v.worst.ratio>8&&l.push([.6,`jerk`,`${v.worst.j} jerks ${Math.round(v.worst.ratio)}x at f${v.worst.f+o}: a key snaps; ease or move it`]);for(let[e,t]of Object.entries(y))t.windows>=2&&t.score>=.4&&l.push([t.score,e,`${e} mirror ${x(t.worst.at)}: ${e===`legs`?`weight onto one foot, not straight down`:`offset one side 2-4 frames or pose it apart`}`]);b.best&&l.push([.7,`dead`,`dead still ${x(b.best)}${s.idle===!1?` (idle false)`:``}: let idle run or key a settle`]),l.sort((e,t)=>t[0]-e[0]);let S=(e,t)=>t?[e,t[0]+o,t[1]+o]:[e];return{sync:S(g.score,g.worst?.at),keys:[_.cv,_.grid.length,_.halfSec],jerk:[...v.p95,v.spikes],arms:S(y.arms.score,y.arms.worst?.at),legs:S(y.legs.score,y.legs.worst?.at),dead:S(DN(b.frames/a),b.best),lead:BN(e,r),...l.length?{flags:l.map(e=>e[1]),warn:l[0][2]}:{}}}var HN=180/Math.PI,UN=12,WN=4,GN={cadence:[80,140],stance:[.55,.65],rotation:[3.7,15.3],obliquity:[2.4,12.4],vertical:[2.7,5]},KN=(e,t)=>Math.round(e*10**t)/10**t,qN=`gait (walks, warnings not QA): cadence [steps/min, normal]; stepLength m; speed m/s; stance [L, R] stride share down; pelvis p-p a stride: rotation, obliquity deg, vertical (range provisional), lateral cm`;function JN(e,t,n){let r=1/0,i=-1/0;for(let a=t;a<=n;a++){let o=e[a]-(e[t]+(e[n]-e[t])*(a-t)/(n-t));r=Math.min(r,o),i=Math.max(i,o)}return i-r}var YN=e=>e.reduce((t,n,r)=>(t.push(r?t[r-1]+(n-e[r-1])-360*Math.round((n-e[r-1])/360):n),t),[]),XN=e=>e.reduce((e,t)=>e+t,0)/e.length;function ZN(e,t,n,r){let[i,,a]=t[n],o=t[r][0]-i,s=t[r][2]-a,c=Math.hypot(o,s)||1,l=t.map(e=>((e[0]-i)*s-(e[2]-a)*o)/c);return[JN(e.yaw,n,r),JN(e.tilt,n,r),100*JN(t.map(e=>e[1]),n,r),100*JN(l,n,r)]}function QN(e,t,n){let r=t.frames,i=r.length,a=t.f0??0,o=t.fps??24,s=e.index,c=Uy(n??[]).map(([e,t])=>[Math.max(0,Math.round(e-a)),Math.min(i-1,Math.round(t-a)+UN)]).filter(([e,t])=>t>e);if(!c.length)return null;let l={Left:[],Right:[]};for(let[e,n]of c)for(let r=e;r<=n;r++)for(let e of[`Left`,`Right`])l[e][r]??=mu(t,r,e);let u=r.map(({s:e})=>e.P[s.Hips]),d=r.map(({s:e})=>{let t=e.P[s.LeftUpLeg],n=e.P[s.RightUpLeg];return[n[0]-t[0],n[1]-t[1],n[2]-t[2]]}),f={yaw:YN(d.map(e=>Math.atan2(e[0],e[2])*HN)),tilt:d.map(e=>Math.atan2(e[1],Math.hypot(e[0],e[2]))*HN)},p=0,m=0,h=0,g={Left:[],Right:[]},_=[];for(let[e,t]of c){let n=[];for(let r of[`Left`,`Right`]){let i=[];for(let n=e+1;n<=t;n++)l[r][n].heel[1]<rd.plantH&&l[r][n-1].heel[1]>=rd.plantH&&i.push(n);n.push(...i);for(let e=1;e<i.length;e++){let[t,n]=[i[e-1],i[e]],a=0;for(let e=t;e<n;e++)a+=+(Math.min(l[r][e].heel[1],l[r][e].ball[1])<rd.plantH);g[r].push(a/(n-t)),_.push(ZN(f,u,t,n))}}if(n.sort((e,t)=>e-t),!(n.length<2)){p+=n.length-1,m+=(n.at(-1)-n[0])/o;for(let e=1;e<n.length;e++)h+=Math.hypot(u[n[e]][0]-u[n[e-1]][0],u[n[e]][2]-u[n[e-1]][2])}}if(p<WN||!_.length)return{steps:p};let v=p/m*60,y=[`Left`,`Right`].map(e=>g[e].length?KN(XN(g[e]),2):null),[b,x,S,C]=[0,1,2,3].map(e=>XN(_.map(t=>t[e]))),w=[],T=(e,t,[n,r])=>{t<n?w.push(`${e} ${t} < ${n}`):t>r&&w.push(`${e} ${t} > ${r}`)};return T(`cadence`,KN(v,1),GN.cadence),y.forEach((e,t)=>e!==null&&T(`stance ${`LR`[t]}`,e,GN.stance)),T(`rotation`,KN(b,1),GN.rotation),T(`obliquity`,KN(x,1),GN.obliquity),T(`vertical`,KN(S,2),GN.vertical),{steps:p,cadence:[KN(v,1),`100-115`],stepLength:KN(h/p,3),speed:KN(h/m,2),stance:y,pelvis:{rotation:KN(b,1),obliquity:KN(x,1),vertical:KN(S,2),lateral:KN(C,2)},warnings:w}}var $N=.15;function eP(e){let{sk:t,spec:n}=e.ctx,r=[];for(let[i,a]of Object.entries(n.objects??{})){if(!a?.spring||!b_(a)||!n.props?.[a.prop])continue;let[o,s]=dg(e,a),c=Math.round((o+s)/2),l=Eg(e,i,c);if(!l)continue;let u=go(l.pos,w_(t,n,yg(e,c).s,a));u>=$N&&r.push(`SPRING_PIVOT ${i}: base is ${u.toFixed(2)} m from the hand; the swing pivots there, so put the base at the hand with at/along`)}return r.length?r:null}var tP=9.7,nP=.25,rP=.75,iP=.88,aP=.5,oP=22,sP=24,cP=Array.from({length:16},(e,t)=>9+t),lP=[`steps`,`period`,`step`,`swing`],uP=new Set([`POP`,`REACH`,`SLIDE`,`FLOAT`,`FLIP`,`KNEE`]),dP=new Map,fP=e=>Math.round(e*100)/100,pP=e=>(Array.isArray(e?.use)?e.use:[]).map((e,t)=>({i:t,u:e})).filter(({u:e})=>e?.skill===`walkTo`&&Number.isInteger(e.args?.arrive)&&Array.isArray(e.args?.to)&&!lP.some(t=>e.args[t]!==void 0)&&Object.values(e.args).every(e=>!(e&&typeof e==`object`&&!Array.isArray(e))));function mP(e,t){if(t===2)return e>=nP&&e<=rP?{first:e,step:e}:null;let n=Math.min(.62,Math.max(.3,.8*e/(t-2+.8))),r=(e-n)/(t-2);return r>=nP&&r<=rP?{first:n,step:r}:null}function hP(e,t,n){let r=[];for(let i of cP)for(let a=2;a<=40;a++){let o=mP(e,a);if(!o)continue;let s=t+16+a*i+18,c=o.step*sP/i,l=Math.abs(Math.log(o.step*i/tP)),u=Math.max(0,n-s)/Math.max(1,n-t);r.push({args:{steps:a,period:i,swing:Math.round(iP*i),step:fP(o.step),firstStep:fP(o.first)},end:s,v:c,late:s>n,score:l+1.5*u+Math.max(0,aP-c)*4})}return{onTime:r.filter(e=>!e.late).sort((e,t)=>e.score-t.score),late:r.filter(e=>e.late).sort((e,t)=>e.end-t.end||e.score-t.score)}}function gP(e,t){let{steps:n,period:r}=e.args,i=Math.round(.8*r),a=n>2&&e.args.firstStep<.62?{firstStep:.62,step:fP((t-.62)/(n-2))}:null;return[{},a,{lift:.06},a&&{...a,lift:.06}].filter(Boolean).map(t=>({...e,args:{...e.args,swing:i,...t}})).filter(e=>e.args.step>=nP&&e.args.step<=rP)}var _P=(e,t,n)=>e.groups.filter(e=>uP.has(e.kind)&&e.last>=t&&e.first<=n).reduce((e,t)=>e+t.count,0);function vP(e,{sk:t,scene:n,trial:r}){let i=[];for(let{i:a,u:o}of pP(e)){let s=JSON.stringify([e.keys,e.use.slice(0,a+1),e.anchors,e.props,e.fits,e.fix,n?.objects??null]);if(dP.has(s)){i.push(dP.get(s));continue}let c=e.use.slice(0,a).filter(e=>e.f0<o.f0),l,u=[];try{let{spec:r,used:i}=zj({...e,frames:2e4,use:c},{sk:t,scene:n,lenient:!0});l=Fy(r.keys??[],o.f0),u=i.map(e=>e.end??0)}catch{l=null}if(!l?.foot_l||!l?.foot_r)continue;let d=[(l.foot_l[0]+l.foot_r[0])/2,(l.foot_l[2]+l.foot_r[2])/2],f=o.args.to,p=Math.hypot(f[0]-d[0],f[f.length-1]-d[1]),{onTime:m,late:h}=hP(p,o.f0,o.args.arrive),g=t=>{let n=Math.max(t.end,...u)+1;return{schema:e.schema,fps:e.fps??sP,frames:n,keys:(e.keys??[]).filter(e=>e.f<n),use:[...c,{...o,args:{...o.args,...t.args}}],...e.anchors?{anchors:e.anchors}:{},...e.props?{props:e.props}:{},...e.fits?{fits:e.fits}:{},...e.fix===void 0?{}:{fix:e.fix}}},_=null,v=0,y=null,b=0,x=[...m.slice(0,6),...m.slice(0,3).flatMap(e=>gP(e,p))].slice(0,18);for(let e of[...x,...h.slice(0,oP-x.length)]){let t;try{t=_P(r(g(e)),o.f0,e.end)}catch{t=1/0}if(v++,b+=+!e.late,(!y||t<y.issues)&&(y={c:e,issues:t}),t===0){_=e;break}}if(_??=y?.issues<1/0?y.c:m[0]??h[0],!_)continue;let S=_.args,C=o.args.arrive,w=`use[${a}] walkTo arrive f${C}: steps ${S.steps}, period ${S.period}, swing ${S.swing}, step ${S.step} m, firstStep ${S.firstStep} m${S.lift?`, lift ${S.lift} m`:``} (${fP(_.v)} m/s), ends f${_.end}`,T=m.length?`the ${b} walks tried that end by f${C} pop or miss a foot`:`even the quickest walk over ${fP(p)} m (a step every ${cP[0]} frames, strides up to ${rP} m, 34 frames to start and stop) ends f${h[0]?.end}`,E=_.late?`; f${C} is too soon: ${T}; give arrive >= f${_.end} or a shorter distance`:``,D=y&&y.c===_&&y.issues>0?`; no candidate walked clean (${y.issues} issues in its frames)`:``,O={i:a,args:S,end:_.end,note:`${w}${E}${D} (${v} checked)`};dP.size>=64&&dP.delete(dP.keys().next().value),dP.set(s,O),i.push(O)}return i}function yP(e,t){if(!t.length)return e;let n=e.use.map((e,n)=>{let r=t.find(e=>e.i===n);return r&&e?.skill===`walkTo`?{...e,args:{...e.args,...r.args}}:e});return{...e,use:n}}var bP=8,xP=6,SP=8,CP=.05,wP=5,TP=e=>`[${e.map(Q).join(`, `)}]`,EP=e=>`${Math.round(e*1e3)/10}`,DP=e=>(e%360+540)%360-180,OP={top:` (box top)`,base:` (box base)`,center:` (box centre)`,rim:` (opening)`};function kP(e,t){let n=/^object:.+?(?:\.(center|top|base|rim))?$/s.exec(e);return n?`${e}${n[1]?OP[n[1]]:t?` (surface)`:OP.center}`:e}function AP(e,t){let n=e.frames[t-(e.f0??0)];if(!n)return null;let{P:r}=n.s,i=e.ctx.sk.index,a=r[i.LeftFoot],o=r[i.RightFoot];return{at:[(a[0]+o[0])/2,(a[2]+o[2])/2],yaw:n.c?.yaw??0}}function jP(e,t,n,r,i){let a=e.frameCount-1,o=e=>Math.max(0,Math.min(a,Math.round(i(e)))),s=o(t.f0),c=o(t.end??t.f0),l=AP(e,c),u=r?.args??{};if(!l)return null;let d=u.side?` ${u.side}`:``,f=u.anchor?` ${u.anchor}`:``,p=`use[${n}] ${t.skill}${d}${f} f${s}-${c}: at ${TP(l.at)} yaw ${Math.round(DP(l.yaw))}`,m=Array.isArray(u.heading)?u.heading[u.heading.length-1]:u.heading;typeof m==`number`&&Math.abs(DP(l.yaw-m))>wP&&(p+=` (asked ${m})`);let h=Array.isArray(u.to)?[u.to[0],u.to[u.to.length-1]]:Array.isArray(u.at)&&!t.placed?u.at:null;if(h){let t=[l.at[0]-h[0],l.at[1]-h[1]],n=Math.hypot(...t);if(n>CP){let r=u.to&&AP(e,s),i=r&&Math.hypot(h[0]-r.at[0],h[1]-r.at[1])>1e-6?[h[0]-r.at[0],h[1]-r.at[1]].map((e,t,n)=>e/Math.hypot(...n)):null,a=i?t[0]*i[0]+t[1]*i[1]:null,o=i?Math.abs(t[0]*i[1]-t[1]*i[0]):null,c=i?`${Q(Math.abs(a))} m ${a<0?`short`:`past`}${o>CP?`, ${Q(o)} m aside`:``}`:`${Q(n)} m off`;p+=`; ${u.to?`to`:`at`} ${TP(h)}: ${c}${u.to&&u.steps!==void 0?`, args.steps set the distance (to only aims)`:``}`}}return p}function MP(e,t){let n=e.f0??0,r=null,i=null,a=null,o=null;for(let s=0;s<e.frames.length;s++){if(!IC(e,s,t.when))continue;a??=s+n,o=s+n;let c=RC(e,s,t);c!==null&&((!r||c<r[0])&&(r=[c,s+n]),(!i||c>i[0])&&(i=[c,s+n]))}return a===null?`${t.name}: never on${typeof t.when==`string`?` (${t.when} never > 0.99)`:``}`:`${t.name} f${a}-${o}: gap ${r?`${EP(r[0])} cm f${r[1]} .. ${EP(i[0])} cm f${i[1]}`:`unknown`} (tol ${EP(t.tol??.01)})`}function NP(e,t,n,r){let i=PS(t)[0];if(!r||r.at===null||!(i===`near`||i===`above`||!r.ok&&(i===`moved`||i===`still`)))return null;let a=(i===`near`||i===`above`?t[i]:[RS(t[i].includes(`:`)?t[i]:`object:${t[i]}`)]).map(t=>[t,Zd(e,r.at,t)]);if(a.some(([,e])=>!e))return null;let o=`goal ${FS(t,n)} f${r.at}: ${a.map(([e,t])=>`${kP(e,i===`near`)} ${TP(t)}`).join(`, `)}`;if(i===`near`&&Array.isArray(t.at)&&t.at[0]!==t.at[1]&&(t.mode??`all`)===`all`){let n=e.f0??0,i=null;for(let r=Math.max(t.at[0],n);r<=Math.min(t.at[1],n+e.frames.length-1);r++){let n=Qd(e,r,t.near[0],t.near[1]);n!==null&&(!i||n<i[0])&&(i=[n,r])}i&&i[1]!==r.at&&(o+=`; best ${Q(i[0])} f${i[1]}`)}return o}function PP(e,{used:t=[],use:n=[],checks:r={},goals:i=[],results:a=[]}){let o=e.timeMap??(e=>e),s=new Map(a.map(e=>[e.name,e])),c=[...t.slice(0,bP).map((t,r)=>jP(e,t,r,n[r],o)),...(r.contacts??[]).slice(0,xP).map(t=>MP(e,t)),...i.map((t,n)=>NP(e,t,n,s.get(FS(t,n)))).filter(Boolean).slice(0,SP)].filter(Boolean);return c.length?c:null}var FP=e=>!!e&&typeof e==`object`&&!Array.isArray(e),IP=e=>String(e).toLowerCase().replace(/[\s_-]/g,``),LP=e=>String(e).replace(/[_-]?(left|Left|LEFT)$/,`_l`).replace(/[_-]?(right|Right|RIGHT)$/,`_r`).replace(/[_-]?L$/,`_l`).replace(/[_-]?R$/,`_r`),RP={arm_swing:`aswing`,armswing:`aswing`,elbow_bend:`abend`,arm_bend:`abend`,wrist_twist:`wtwist`,wrist_flex:`wflex`,foot_yaw:`fyaw`,foot_pitch:`fpitch`,arm_weight:`armw`,ik_weight:`armw`,hips:`root`,pelvis:`root`,finger:`fingers`,hand_pole:`elbow`,knee_pole:`knee`},zP={objectKey:{position:`pos`,rotation:`rot`,quat:`rot`,quaternion:`rot`,frame:`f`},anchor:{pos:`p`,position:`p`,point:`p`,id:`object`,joint:`bone`},use:{frame:`f0`,f:`f0`}};function BP(e,t,n={}){if(t.includes(e))return e;let r=n[e]??n[IP(e)];if(r&&t.includes(r))return r;let i=new Set(t.filter(t=>IP(t)===IP(e)||t===`${e}s`||`${t}s`===e));return i.size===1?[...i][0]:null}function VP(e,t,n,r,i){if(!FP(e))return e;let a=e;for(let o of Object.keys(e)){let e=t.includes(o)?null:BP(o,t,i);!e||e in a||(a=Object.fromEntries(Object.entries(a).map(([t,n])=>t===o?[e,n]:[t,n])),r.push(`corrected: ${n}.${o} -> ${n}.${e}`))}return a}var HP=(e,t)=>Array.isArray(e)?e.map(t):e,UP=e=>FP(e)&&(e.to!==void 0||e.arrive!==void 0||typeof e.heading==`number`||BP(String(e.type),[`walkTo`])===`walkTo`);function WP(e,t){if(!Array.isArray(e.generators)||!e.generators.some(UP))return e;let n=Array.isArray(e.use)?[...e.use]:[],r=[];e.generators.forEach((e,i)=>{if(!UP(e))return r.push(e);let{type:a,f0:o,...s}=e,c=n.findIndex(e=>FP(e)&&Number.isFinite(e.f0)&&e.f0>o),l=c<0?n.length:c;n.splice(l,0,{skill:`walkTo`,f0:o,args:s});let u=e.to===void 0?e.arrive===void 0?typeof e.heading==`number`?`a single heading`:`type "${a}"`:`arrive`:`to`;t.push(`corrected: generators[${i}] (a walk with ${u}) -> use[${l}] walkTo { ${Object.keys(s).join(`, `)} }: a generator walks by steps and [h0, h1]; walkTo is the walk that heads for a point`)});let{generators:i,...a}=e;return{...a,...r.length?{generators:r}:{},use:n}}function GP(e,t,n){if(!FP(e))return e;let r=e,i=Aj.includes(e.skill)?e.skill:BP(String(e.skill),Aj);i&&i!==e.skill&&(r={...r,skill:i},n.push(`corrected: use[${t}].skill "${e.skill}" -> "${i}"`));let a=QD[r.skill];if(!a)return r;let o=Object.keys(a.args);if(FP(r.args)||r.args===void 0){let e=r.args??{},i=VP(e,o,`use[${t}].args`,n);for(let[e,r]of Object.entries(i)){let o=a.args[e]?.enum,s=o&&typeof r==`string`&&!o.includes(r)?BP(r,o,{left:`l`,right:`r`}):null;s&&(i={...i,[e]:s},n.push(`corrected: use[${t}].args.${e} "${r}" -> "${s}"`))}if(i.f0!==void 0&&!o.includes(`f0`)&&r.f0===void 0){let{f0:e,...a}=i;i=a,r={...r,f0:e},n.push(`corrected: use[${t}].args.f0 -> use[${t}].f0`)}for(let e of Object.keys(r)){let a=yl.includes(e)?null:BP(e,o);!a||a in i||(i={...i,[a]:r[e]},r=Object.fromEntries(Object.entries(r).filter(([t])=>t!==e)),n.push(`corrected: use[${t}].${e} -> use[${t}].args.${a}`))}if(FP(i.define)&&bl[i.define.kind]){let e=VP(i.define,[`kind`,...bl[i.define.kind]],`use[${t}].args.define`,n,zP.anchor);e!==i.define&&(i={...i,define:e})}i!==e&&(r={...r,args:i})}return VP(r,yl,`use[${t}]`,n,zP.use)}var KP=e=>[...Bc,...Hc,...Uc,...TC(e)];function qP(e,t){let n=LP(e),r=/_[lr]$/.exec(n)?.[0]??``,i=r?n.slice(0,-2):n,a=RP[i]??RP[IP(i)];return a&&t.includes(a+r)?a+r:BP(n,t)}function JP(e,t,n,r){if(!FP(e)||!FP(e.set))return e;let i=e.set,a=e.step;for(let o of Object.keys(e.set)){if(n.includes(o)||o.endsWith(`_vis`)||o.startsWith(`w_`))continue;let s=qP(o,n);!s||s in i||(i=Object.fromEntries(Object.entries(i).map(([e,t])=>e===o?[s,t]:[e,t])),Array.isArray(a)&&(a=a.map(e=>e===o?s:e)),r.push(`corrected: keys[${t}] (f${e.f}) channel "${o}" -> "${s}"`))}for(let n of[`l`,`r`]){let a=i[`fingers_${n}`];if(!FP(a))continue;let o=VP(a,Gc,`keys[${t}] (f${e.f}) fingers_${n}`,r);o!==a&&(i={...i,[`fingers_${n}`]:o})}return i===e.set?e:{...e,set:i,...a?{step:a}:{}}}function YP(e,t,n){if(!FP(t))return t;let r=Object.keys(t).filter(e=>[`free`,`carry`,`hinge`,`follow`,`switch`].includes(e)&&FP(t[e]));if(r.length!==1)return t;let{[r[0]]:i,...a}=t;return Object.keys(i).some(e=>e in a)?t:(n.push(`corrected: objects.${e}.${r[0]} { ${Object.keys(i).join(`, `)} } -> objects.${e} { ${Object.keys(i).join(`, `)} }: an entry's kind is read from its fields, not named`),{...a,...i})}function XP(e,t,n){let r=`objects.${e}`,i=YP(e,t,n);if(!FP(i))return i;let a=VP(i,[...new Set(Object.values(Cl).flat())],r,n);return Array.isArray(a.keys)&&(a={...a,keys:a.keys.map((e,t)=>VP(e,El,`${r}.keys[${t}]`,n,zP.objectKey))}),FP(a.fall)?a={...a,fall:VP(a.fall,Tl,`${r}.fall`,n)}:Array.isArray(a.fall)&&(a={...a,fall:a.fall.map((e,t)=>VP(e,Tl,`${r}.fall[${t}]`,n))}),a}var ZP=(e,t,n)=>VP(e,Al,`goals[${t}]`,n);function QP(e,t){return FP(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,FP(n)&&bl[n.kind]?VP(n,[`kind`,...bl[n.kind]],`anchors.${e}`,t,zP.anchor):n])):e}function $P(e,t){return FP(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,kl[e]?HP(n,(n,r)=>VP(n,kl[e],`checks.${e}[${r}]`,t)):n])):e}function eF(e,t=[]){if(!FP(e))return e;let n=t.length,r=VP(e,[..._l,`probes`],`spec`,t);if(r=WP(r,t),Array.isArray(r.use)&&(r={...r,use:r.use.map((e,n)=>GP(e,n,t))}),r.anchors&&(r={...r,anchors:QP(r.anchors,t)}),Array.isArray(r.keys)){let e=KP(r);r={...r,keys:r.keys.map((n,r)=>JP(n,r,e,t))}}return FP(r.objects)&&(r={...r,objects:Object.fromEntries(Object.entries(r.objects).map(([e,n])=>[e,XP(e,n,t)]))}),Array.isArray(r.goals)&&(r={...r,goals:r.goals.map((e,n)=>ZP(e,n,t))}),Array.isArray(r.fits)&&(r={...r,fits:r.fits.map((e,n)=>VP(e,Sl,`fits[${n}]`,t))}),r.checks&&(r={...r,checks:$P(r.checks,t)}),t.length>n?r:e}function tF(e,{sk:t,scene:n}={},r=[],i=[]){if(!FP(e)||!Array.isArray(e.use)||!e.use.some(e=>e?.skill===`walkTo`&&FP(e.args)&&e.args.to!==void 0))return e;let a=Object.values(FP(e.objects)?e.objects:{}).flatMap(e=>FP(e)?[e.grab,e.release,...Array.isArray(e.keys)?e.keys.map(e=>e?.f):[]]:[]).filter(Number.isFinite),o=r=>{let i={refusals:[],stretch:e.frames===`auto`,busy:a,last:Number.isFinite(e.frames)?e.frames-1:1/0,noStop:r,stopped:new Set};try{return{used:zj({...e,frames:2e4},{sk:t,scene:n,fit:i,auto:!0}).used,fit:i}}catch{return null}},s=o(new Set);if(!s)return e;if(s.fit.stopped.size){let e=new Set(s.fit.stopped),t=o(e);if(t&&t.fit.refusals.length<s.fit.refusals.length){for(let n of[...s.fit.stopped].sort((e,t)=>e-t)){e.delete(n);let r=o(e);(!r||r.fit.refusals.length>t.fit.refusals.length)&&e.add(n)}s=o(e)??t}}let{used:c,fit:l}=s;if(i.push(...l.refusals),!c.some(e=>e.adjust))return e;for(let e of c)e.adjust&&r.push(`corrected: ${e.adjust.note}`);return{...e,use:e.use.map((e,t)=>c[t]?.adjust?{...e,args:{...e.args,...c[t].adjust.args}}:e)}}var nF=(e,t,n,r)=>tF(eF(e,n),t,n,r),rF=e=>e?.groups??[],iF=e=>rF(e).reduce((e,t)=>e+(t.severity??0),0),aF=e=>(e?.goals??[]).filter(e=>e.ok).map(e=>e.name),oF=e=>(e?.goals??[]).filter(e=>!e.ok).length,sF=.5,cF=e=>Math.round(e*100)/100;function lF(e){let t=new Map;for(let n of rF(e))t.set(dD(n),(t.get(dD(n))??0)+(n.severity??0));return t}function uF(e,t){let n=lF(t),r=lF(e),i=0,a=0,o=[];for(let[e,t]of r){let r=n.get(e)??0;t>r+1e-9?(i+=t-r,o.push({key:e,severity:[cF(r),cF(t)]})):a+=r-t}for(let[e,t]of n)r.has(e)||(a+=t);o.sort((e,t)=>t.severity[1]-t.severity[0]-(e.severity[1]-e.severity[0]));let s=[cF(iF(t)),cF(iF(e))],c=[rF(t).length,rF(e).length],l=aF(t).filter(t=>!aF(e).includes(t)),u=iF(e)<iF(t)-1e-9?oF(e)>oF(t)||l.length?`goal ${l.length?`"${l[0]}" no longer holds`:`failures rose`}`:c[1]>c[0]?`problems ${c[0]} -> ${c[1]}`:i>sF*a+1e-9?`${o[0]?.key} got worse (${o[0]?.severity.join(` -> `)})`:``:`summed severity ${s[0]} -> ${s[1]}`;return{better:!u,why:u,sev:s,problems:c,worse:o.slice(0,3)}}var dF=(e,t)=>(rF(e).length<rF(t).length||rF(e).length===rF(t).length&&iF(e)<=iF(t)+1e-9)&&oF(e)<=oF(t)&&aF(t).every(t=>aF(e).includes(t)),fF=(e,t)=>rF(e).filter(e=>dD(e)===t).reduce((e,t)=>e+(t.severity??0),0),pF=e=>Math.round(performance.now()-e);function mF(e,t){let n=structuredClone(e.checks??{}),r=e=>Array.isArray(e)?[Math.round(t(e[0])),Math.round(t(e[1]))]:e;for(let e of[`contacts`,`orient`,`below`])for(let t of n[e]??[])t.when=r(t.when);for(let e of n.clearance??[])e.frames=r(e.frames);return{...e,checks:n}}function hF(e,t,n,r){let i=r(e),a=e.timeMap?mF(t,e.timeMap):t;if(!e.fixed?.retime)return{out:e,measured:a,qa:i};let o=n({...t,fix:{...t.fix,retime:!1}}),s=r(o);if(dF(i,s))return{out:e,measured:a,qa:i};let c=uF(i,s);return o.fixed={...o.fixed,retime:{...e.fixed.retime,kept:!1,how:`${e.fixed.retime.how}; not kept: QA was worse with it (summed severity ${c.sev[0]} -> ${c.sev[1]}, problems ${c.problems[0]} -> ${c.problems[1]}), so the take is compiled without it`}},{out:o,measured:t,qa:s}}function gF(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return{spec:e,probes:t};let n=cC(e.goals);if(e.probes===void 0&&n===e.goals)return{spec:e,probes:t};let{probes:r,...i}=e,a=r===void 0?t:t?[...t,...Array.isArray(r)?r:[r]]:r;return{spec:n===e.goals?i:{...i,goals:n},probes:a}}function _F(e,{sk:t,scene:n},r={}){let i=[],a=[];try{return vF(r.lenient?e:nF(e,{sk:t,scene:n},i,a),{sk:t,scene:n},r,i,a)}catch(e){throw a.length&&/^MOTION_SPEC_INVALID/.test(e.message)&&!e.message.includes(a[0])&&(e.message=e.message.replace(/^MOTION_SPEC_INVALID: /,`MOTION_SPEC_INVALID: ${a.join(`
|
|
11
|
+
`)}\n`)),i.length&&/^MOTION_SPEC_INVALID/.test(e.message)&&(e.message+=`\n(adjusted before these checks: ${i.join(`; `)})`),e}}function vF(e,{sk:t,scene:n},r,i,a){let{spec:o,probes:s}=gF(e,r.probes),c=performance.now(),l={sk:t,scene:n,lenient:r.lenient===!0,problems:a},u=r.checks&&gD({checks:r.checks}).checks,d=[],f=e=>{let{spec:r,used:a}=zj(gD(yP(e,d)),l),o=jM(JSON.parse(JSON.stringify(u?{...r,checks:u}:r)),n,i,t);return MC(o,l),{full:o,used:a}};d=vP(o,{sk:t,scene:n,trial:e=>{let n=f(e).full;return mD(t,fS({fps:24,...n},l),n,{explain:!1})}});let p=o?.frames===`auto`&&d.length?{...o,frames:$j(yP(o,d),l).frames}:$j(o,l),m=Uj(p),h=p,g=null;m.length&&({spec:h,search:g}=Xj(p,m,l,e=>f(e).full)),o?.frames===`auto`&&tM(h);let _=performance.now(),{full:v,used:y}=f(h),{out:b,measured:x,qa:S}=hF(fS({fps:24,...v},l),v,e=>fS({fps:24,...e},l),e=>mD(t,e,e.timeMap?mF(v,e.timeMap):v,{userSpec:h})),C=pF(_),w=performance.now(),T=qu(t,b,x.checks),E=JC(b);E&&Object.assign(T,{units:`${T.units}; ${qC}`,held:E});let D=oN(t,b),O=Gw(t,b);D&&Object.assign(T,{units:`${T.units}; ${eN}`,near:D}),O&&Object.assign(T,{units:`${T.units}; ${Uw}`,wrist:O});let k=tS(t,b);k&&Object.assign(T,{units:`${T.units}; ${Jx}`,load:k}),Object.assign(T,{units:`${T.units}; ${ON}`,life:VN(t,b,h?.keys)});let ee=QN(t,b,b.keys);ee&&Object.assign(T,ee.cadence?{units:`${T.units}; ${qN}`,gait:ee}:{gait:ee});let A=y.filter(e=>e.paced).map(e=>`${e.skill} paced ${e.paced.toFixed(2)} to fit f${e.f0}..f${e.end}`);A.length&&(T.paced=A);let te=y.filter(e=>e.cut).map(e=>`${e.skill}: ${e.cut}`);te.length&&(T.cut=te);let ne=y.filter(e=>e.placed).map(e=>`${e.skill} f${e.f0}: ${e.placed.why}: at [${e.placed.at.join(`, `)}], heading ${e.placed.heading}`);ne.length&&(T.placed=ne),d.length&&(T.planned=d.map(e=>e.note));let re=eP(b);re&&(T.spring=re);let ie=PP(b,{used:y,use:h?.use,checks:x.checks,goals:x.goals,results:S.goals});ie&&(T.asked=ie);let ae=vM(b,{used:y,spec:v}),oe=s&&YM(b,s,{spec:v,sk:t,scene:n,notes:i});return{out:b,qa:S,observations:T,spec:h,expanded:v,used:y,fixed:b.fixed,search:g,timeline:ae,...oe?{probes:oe}:{},...i.length?{notes:i}:{},ms:{compile:C,qa:pF(w),total:pF(c)}}}var yF=`cozyclay.take.v3`;function bF(e,t,n={position:[0,0,0],yaw:0},r={}){let i=t.frames.length,a=e.names.length,o=new Float32Array(i*a*4),s=new Float32Array(i*3),c=X(-(n.yaw??0));for(let r=0;r<i;r++){let i=t.frames[r].s,{quats:l,hips:u}=Po(e,{P:i.P.map(e=>J(c,H(e,n.position))),R:i.R.map(e=>q(c,e))});l.forEach((e,t)=>o.set(e,(r*a+t)*4)),s.set(u,r*3)}let l={},u=t.f0??0;for(let[e,n]of Object.entries(t.ctx.spec.objects??{})){let r=b_(n),a=x_(n),o=r||a,s=!S_(n),c=s?new Float32Array(i*3):null,d=s?new Float32Array(i*4):null,f=o||!s||Ph(n),p=f&&n.visible?new Uint8Array(i):null,m=o?new Uint8Array(i):null,h=f&&n.level?new Float32Array(i):null,[g,_]=r?dg(t,n):[0,0],v=r&&vg(t,e)?new Uint8Array(i):null;for(let r=0;r<i;r++){if(p&&(p[r]=+((t.baked?.[n.visible]?.[r+u]??0)>.5)),h&&(h[r]=Math.max(0,Math.min(4,t.baked?.[n.level]?.[r+u]??1))),!s)continue;let i=Sg(t,e,r+u);i&&(c.set(i.pos,r*3),d.set(Do(i.R),r*4),m&&(m[r]=a||r+u>=g&&r+u<=_?1:0),v&&(v[r]=+(r+u>_)))}l[e]={...s?{pos:c,quat:d}:{},...p?{vis:p}:{},...m?{hold:m}:{},...v?{world:v}:{},...h?{lvl:h}:{}}}return{schema:yF,fps:t.fps,frameCount:i,rig:e.model,bones:e.names.slice(),rot:o,hips:s,objects:l,placement:n,...r}}function xF(e,t){let n=Math.max(0,Math.min(e.frameCount-1,Math.round(t)))*3;return[e.hips[n],e.hips[n+1],e.hips[n+2]]}var SF=`modulepreload`,CF=function(e){return`/`+e},wF={},TF=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=CF(t,n),t=s(t),t in wF)return;wF[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:SF,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},EF=Object.freeze([`keys`,`follow`,`rail`]),DF=Object.freeze({distance:3,height:1.6,response:.7,lead:.25,railStartMode:`head`,maxDollySpeed:4,pitchOffsetDeg:0,orbitOffsetDeg:0});function OF(e){return Array.isArray(e)?e.map(e=>({x:e.x,z:e.z})):null}function kF(e){if(!e||typeof e!=`object`)return null;let t=Array.isArray(e.points)?e.points:Number.isFinite(e.start)&&Number.isFinite(e.end)?[{t:0,height:e.start},{t:1,height:e.end}]:null;if(!t)return null;let n=t.filter(e=>e&&Number.isFinite(e.t)&&Number.isFinite(e.height)).map(e=>({t:Math.max(0,Math.min(1,e.t)),height:Math.max(.1,e.height)})).sort((e,t)=>e.t-t.t).filter((e,t,n)=>t===n.length-1||n[t+1].t-e.t>1e-6).slice(0,8);return n.length<2?null:(n[0]={...n[0],t:0},n[n.length-1]={...n[n.length-1],t:1},{points:n})}function AF(e){return!e||typeof e!=`object`?null:e.mode===`off`?{mode:`off`}:e.mode===`range`?{mode:`range`,startFrame:e.startFrame,endFrame:e.endFrame}:null}function jF(e){let t=Array.isArray(e?.ids)?e.ids.filter(e=>typeof e==`string`&&e).slice(0,4):[];if(t.length)return Number.isFinite(e.height)?{ids:t,height:e.height}:{ids:t};let n=e?.point;return n&&[n.x,n.y,n.z].every(Number.isFinite)?{point:{x:n.x,y:n.y,z:n.z}}:null}function MF(e,t){let n=t?jF(e.aim):null,r=t&&Number.isFinite(e.focalMm)&&e.focalMm>0?e.focalMm:null;return{...n?{aim:n}:{},...r?{focalMm:r}:{}}}function NF(e={}){let t=e&&typeof e==`object`?e:{},n=EF.includes(t.mode)?t.mode:`keys`,r={...DF,...t.followCam??{}},i=OF(t.cameraRail),a=kF(t.craneHeight)??(n===`rail`&&i?{points:[{t:0,height:r.height},{t:1,height:r.height}]}:null),o=Or(t.dollyTiming);return{mode:n,followCam:r,cameraRail:i,railFollow:AF(t.railFollow),craneHeight:a,dollyTiming:Dr(o)?null:o,...MF(t,i)}}function PF(e){return NF(e)}function FF(e,t={}){let n=NF(e),r=t&&typeof t==`object`?t:{};return NF({...n,...r,followCam:r.followCam?{...n.followCam,...r.followCam}:n.followCam,cameraRail:Object.hasOwn(r,`cameraRail`)?r.cameraRail:n.cameraRail,railFollow:Object.hasOwn(r,`railFollow`)?r.railFollow:n.railFollow,craneHeight:Object.hasOwn(r,`craneHeight`)?r.craneHeight:n.craneHeight,dollyTiming:Object.hasOwn(r,`dollyTiming`)?r.dollyTiming:n.dollyTiming})}function IF(e){let t=NF(e);return FF(t,{mode:t.mode===`rail`?`follow`:t.mode,cameraRail:null,railFollow:null,craneHeight:null})}var LF=[`begin`,`mark`,`rollback`,`finish`,`cancel`],RF=(e,t)=>Object.fromEntries(LF.map(n=>[`agent.turn.${n}`,e({turnId:t})]));function zF(e,t){if(e===`agent.turn.mark`)return t.mark={point:t.session?.savepoint()??null,affectedIds:new Set(t.affectedIds),since:new Set},{txId:t.txId,affectedIds:[],toasts:[]};let{mark:n}=t;if(!n)throw new $e(`STALE_TARGET`,`The agent turn has no mark to roll back to.`);return t.mark=null,t.edits=(t.edits??[]).filter(e=>e.mark!==n),t.session?.rollback(n.point??void 0),t.affectedIds=n.affectedIds,{txId:t.txId,affectedIds:[...n.since],toasts:[]}}var BF=e=>e&&{point:e.session?.savepoint()??null,affectedIds:new Set(e.affectedIds),since:e.mark&&new Set(e.mark.since),mark:e.mark};function VF(e,t,n){return e&&t&&n?.ok&&n.authored&&(e.edits??=[]).push({...t,receiptId:n.receiptId,ids:n.affectedIds}),n}function HF(e,t,n,r,i){let a=e.edits??[],o=a.findIndex(e=>e.receiptId===t.receiptId);if(o<0)throw new $e(`TARGET_BUSY`,`Finish the agent turn before traversing history or opening another transaction. Inside the turn, undo_edit with the receiptId of this message's newest edit reverts it${a.length?` (now ${a.at(-1).receiptId})`:``}; an earlier message's edit is undone after this one ends.`);let s=a[o];if(o<a.length-1)throw new $e(`UNDO_CONFLICT`,`Later edits of this message come after it; undo them first, newest first: ${a.slice(o+1).reverse().map(e=>e.receiptId).join(`, `)}.`);return e.session.rollback(s.point??void 0),a.pop(),e.affectedIds=s.affectedIds,e.mark&&s.mark!==e.mark?e.mark={point:e.session.savepoint(),affectedIds:new Set(e.affectedIds),since:new Set}:e.mark&&(e.mark.since=s.since),{ok:!0,status:`completed`,kind:`transaction`,action:`edit.undo`,txId:e.txId,commandId:n.commandId,receiptId:crypto.randomUUID(),host:r.host,summary:`Undid ${s.receiptId} inside this message.`,authored:!1,revision:{before:r.revision,after:i().revision},affectedIds:s.ids,delta:[],checks:{coverage:`agent-turn-savepoint`},undo:null,warnings:[],output:{undoneReceiptId:s.receiptId}}}var UF=new Set([`timeline`,`scene`]),WF=Object.freeze([`placement`,`take`,`ik`,`props`]),GF=RegExp(`^(?:(?:object|character|shot):[A-Za-z0-9][A-Za-z0-9._:-]*|stage|timeline|scene)$`),KF=e=>typeof e==`string`&&e.length<=140&&GF.test(e),qF=/^character:(.+?)(?::(placement|take|ik|props))?$/s;function JF(e){let t=qF.exec(e);return t?{id:t[1],layer:t[2]??null}:null}var YF=(e,t=WF)=>t.map(t=>`character:${e}:${t}`),XF=e=>[...new Set(e.flatMap(e=>{let t=JF(e);return t&&!t.layer?YF(t.id):[e]}))];function ZF(e,t){if(e===t)return!0;let n=JF(e),r=JF(t);return!!(n&&r&&n.id===r.id&&(!n.layer||!r.layer))}var QF=[`cast.replace`,`cast.setCustomPoses`,`cast.showExtras`,`cast.removePose`,`objects.replace`,`shot.replace`,`ai.prepareShot`],$F=[`shot.create`,`shot.createStill`,`shot.split`,`shot.duplicate`,`shot.remove`,`shot.reorder`,`shot.setRange`,`shot.setTimeline`],eI=[`object.add`,`object.createKit`,`asset.import`,`character.add`],tI=/^(character\.|characters?\b|cast\.(savePose|setLayer)$|ik\.|motion\.)/,nI={"character.move":[`placement`],"characters.arrange":[`placement`],"cast.setLayer":[`take`],"motion.set":[`take`],"motion.compile":[`take`,`ik`],"motion.clear":[`take`,`ik`],"motion.keyObject":[`take`,`ik`,`props`],"object.attach":[`props`],...Object.fromEntries([`addWaypoint`,`moveWaypoint`,`removeWaypoint`,`clearWaypoints`].map(e=>[`character.${e}`,[`take`]])),...Object.fromEntries([`cut`,`setSegmentSpeed`,`removeSegment`,`trim`,`resetTiming`].map(e=>[`motion.${e}`,[`take`,`ik`]])),...Object.fromEntries([`character.setIkKey`,`character.removeIkKey`,`character.clearIkKeys`,`ik.setKey`,`ik.removeKey`,`ik.clearKeys`,`ik.applyPose`,`motion.rangePin.apply`,`motion.rangePin.remove`].map(e=>[e,[`ik`]]))},rI={layer:`take`,motionTake:`take`,waypoints:`take`,ikEdits:`ik`,ikKeys:`ik`,model:null},iI=e=>e.some(e=>rI[e]===null)?WF:[...new Set(e.map(e=>rI[e]??`placement`))],aI=e=>e.clearMotion?[`placement`,`take`,`ik`]:[`placement`];function oI(e,t){return nI[e]?nI[e]:e===`character.update`?iI(Object.keys(t.patch??{})):e===`character.set`?iI(Object.keys(t.set??{})):e===`character.setPose`||e===`cast.savePose`?aI(t):WF}function sI(e,t){let n=t?.objects??[],r=new Set,i=e=>{if(!(!e||r.has(`object:${e}`))){r.add(`object:${e}`);for(let t of n)t.parent===e&&i(t.id)}};for(let t of e)i(t);return[...r]}var cI=(e,t)=>e.flatMap(e=>e.op===`create`?[]:e.op===`group`?sI([e.parentId,...e.childIds],t):e.op===`ungroup`?sI(e.childIds,t):sI([e.id],t));function lI(e,t={},n={},r={}){if(r.kind===`document`||/^(scene|project)\./.test(e)||e===`load_scenes`||QF.includes(e))return[`scene`];if(r.readOnly||r.kind===`transient`||/^(view|timeline)\./.test(e)||[`motion.qa`,`motion.sample`,`motion.describe`,`motion.report`,`sculpt.compare`,`export.shotVideo`].includes(e)||eI.includes(e))return[];if(e===`objects.batch`)return[...new Set(t.ops.flatMap(e=>lI(e.name,e.args,n)))];if(e===`objects.arrange`)return[...new Set(cI(t.ops,n))];if(e===`characters.arrange`)return t.ops.flatMap(t=>t.op===`create`?[]:YF(t.characterId,oI(e,t)));if((e===`character.set`||e===`motion.set`)&&t.ops)return[...new Set(t.ops.flatMap(t=>YF(t.id,oI(e,t))))];if(e.startsWith(`stage.`)||e===`shot.setLens`)return[`stage`];if($F.includes(e))return[`timeline`];if(e.startsWith(`shot.`)){let e=t.shotId??t.id??n.selectedShotId;return e?[`shot:${e}`]:[`timeline`]}return e===`object.group`?sI([t.parent,...t.children],n):e===`object.ungroup`?sI(t.children,n):e===`object.remove`?sI(t.ids,n):e===`object.attach`||e===`motion.keyObject`?[...YF(t.characterId,oI(e,t)),...sI([t.objectId],n)]:e.startsWith(`object.`)?sI([t.id??t.objectId],n):tI.test(e)&&(t.characterId??t.id)?YF(t.characterId??t.id,oI(e,t)):[`scene`]}function uI(e,t={}){return(t.objects??[]).some(t=>t.id===e)?`object:${e}`:(t.characters??[]).some(t=>t.id===e)?`character:${e}`:(t.shots??[]).some(t=>t.id===e)?`shot:${e}`:null}function dI(e,t,n){for(let r of n.values()){if(r.taskId===e)continue;let n=t.find(e=>UF.has(e)||[...r.keys].some(t=>UF.has(t)||ZF(e,t)));if(n)return`${n} is held by task ${r.taskId}${r.title?` (${r.title})`:``}`}return null}var fI=(e,t)=>{throw new $e(e,t)},pI=[`begin`,`requestScope`,`mark`,`rollback`,`finish`,`cancel`,`undo`],mI=32,hI=e=>[...e].slice(0,6).join(`, `)+(e.length>6?` and ${e.length-6} more`:``);function gI({ports:e,emit:t}){let n=new Map,r=new Map,i=new Map,a=t=>{let n=JF(t);if(n?.layer)return e.readLayer?.(t)??e.readTarget?.(n.id)??`absent`;let[r,i]=t.split(/:(.*)/s);if(i!==void 0)return e.readTarget?.(i)??`absent`;let a=e.read();return r===`scene`?`r${a.revision}`:`${r}:${a.domainRevisions?.[r===`timeline`?`shot`:r]??0}`},o=t=>({key:t,value:e.snapshotTarget?e.snapshotTarget(t):fI(`CAPABILITY_MISSING`,`This editor cannot snapshot task targets.`)});function s(n,r,o){if(n.skipped=r.filter(e=>e.value===null).map(e=>e.key),r=r.filter(e=>e.value!==null),!r.length)return null;e.restoreTargets||fI(`CAPABILITY_MISSING`,`This editor cannot restore task targets.`);let{historyEntryId:s=null}=e.restoreTargets(r)??{};s&&i.set(s,n.taskId),n.restored=[...new Set(r.map(({key:t})=>JF(t)?.id??(t.includes(`:`)?t.slice(t.indexOf(`:`)+1):e.read().host.sceneId)))];for(let{key:e}of r)n.tokens.set(e,a(e));return t?.({type:`task.${o}`,taskId:n.taskId,keys:r.map(e=>e.key)}),s}function c(e,t){let r=t.find(e=>!KF(e));r!==void 0&&fI(`INVALID_ARGUMENT`,`"${r}" is not a scope key: object:<id>, character:<id> (or one layer: character:<id>:placement, :take, :ik, :props), shot:<id>, stage, timeline or scene.`);let i=XF(t),o=dI(e.taskId,i,n);o&&fI(`SCOPE_BUSY`,`${o}; wait for it, or ask for what is free.`);for(let t of i)e.keys.has(t)||(e.keys.add(t),e.tokens.set(t,a(t)))}function l(t,n,r,i,{historyEntryId:a=null,affectedIds:o=[],output:s,warnings:c=[]}={}){let l=e.read();return n.skipped?.length&&(c=[...c,{code:`SCOPE_NOT_RESTORED`,message:`Left as they are (a document change has no undo): ${hI(n.skipped)}.`}]),n.skipped=null,Pn({ok:!0,status:`completed`,kind:`transaction`,commandId:r.commandId,receiptId:crypto.randomUUID(),host:i.host,action:t,txId:n.taskId,authored:!!a,revision:{before:i.revision,after:l.revision},affectedIds:a&&!o.length?n.restored:o,delta:[],checks:{coverage:`task-scope`},warnings:c,undo:a?{historyEntryId:a,entries:1,canUndoDirect:!1}:null,output:{scope:[...n.keys],...s}})}let u=(e,t)=>{(e.origin!==`agent`||e.taskId!==t)&&fI(`CAPABILITY_MISSING`,`Only the owning task can control it.`)};return{get size(){return n.size},controls:(e,t)=>Object.fromEntries(pI.map(n=>[`task.${n}`,n===`begin`||n===`requestScope`?{...e({taskId:t,scope:{type:`array`,items:{type:`string`},maxItems:64}}),properties:{taskId:t,scope:{type:`array`,items:{type:`string`},maxItems:64},reads:{type:`array`,items:{type:`string`},maxItems:64},title:{type:`string`,maxLength:120}}}:e({taskId:t})])),of(e,t){if(!e.taskId)return null;let r=n.get(e.taskId);return!r&&!t.startsWith(`task.`)&&fI(`STALE_TARGET`,`Task ${e.taskId} is not open.`),r??null},control(e,i,d,f,p){if(e===`task.undo`){let t=r.get(i.taskId)??fI(`UNDO_EXPIRED`,`Task ${i.taskId} is not a finished task this editor still holds.`),n=[...t.final].filter(([e,{token:t,value:n}])=>a(e)!==t&&JSON.stringify(o(e).value)!==n).map(([e])=>e);n.length&&fI(`UNDO_CONFLICT`,`Changed since the task finished: ${hI(n)}; undo those first or edit by hand.`);let c=s(t,[...t.pre.values()],`undone`);return r.delete(i.taskId),l(e,t,d,f,{historyEntryId:c,affectedIds:t.affectedIds})}if(u(d,i.taskId),e===`task.begin`){p&&fI(`TARGET_BUSY`,p),(n.has(i.taskId)||r.has(i.taskId))&&fI(`INVALID_ARGUMENT`,`Task ${i.taskId} already exists.`);let a={taskId:i.taskId,title:i.title??``,keys:new Set,reads:new Set(i.reads??[]),tokens:new Map,pre:new Map,edits:[],notices:[],affectedIds:[]};return c(a,i.scope),n.set(a.taskId,a),t?.({type:`task.begun`,taskId:a.taskId,scope:[...a.keys]}),l(e,a,d,f)}let m=n.get(i.taskId)??fI(`STALE_TARGET`,`Task ${i.taskId} is not open.`);if(e===`task.requestScope`)return c(m,i.scope),t?.({type:`task.scope`,taskId:m.taskId,scope:[...m.keys]}),l(e,m,d,f);if(e===`task.mark`)return m.mark={values:[...m.keys].map(o),keys:new Set(m.keys)},l(e,m,d,f);if(e===`task.rollback`){let t=m.mark??fI(`STALE_TARGET`,`The task has no mark to roll back to.`);m.mark=null;let n=[...m.keys].filter(e=>!t.keys.has(e)).map(e=>m.pre.get(e)??o(e)),r=s(m,[...t.values,...n],`rolledBack`);return m.edits=m.edits.filter(e=>e.mark!==t),l(e,m,d,f,{historyEntryId:r})}if(n.delete(m.taskId),e===`task.cancel`)return l(e,m,d,f,{historyEntryId:s(m,[...m.pre.values()],`cancelled`),affectedIds:m.affectedIds});for(m.final=new Map([...m.pre.keys()].map(e=>[e,{token:a(e),value:JSON.stringify(o(e).value)}])),r.set(m.taskId,m);r.size>mI;)r.delete(r.keys().next().value);return t?.({type:`task.finished`,taskId:m.taskId}),l(e,m,d,f,{affectedIds:m.affectedIds,output:{edits:m.edits.length}})},admit(e,r,i,s,c){if(!e&&!n.size)return null;let l=r?.id?lI(r.id,i,c,r):[];if(!e&&s.origin===`ui`){for(let e of n.values()){let n=l.filter(t=>[...e.keys].some(e=>ZF(t,e)));n.length&&t?.({type:`task.userEdit`,taskId:e.taskId,keys:n})}return null}if(!e){let e=l.find(e=>dI(null,[e],n));return e&&fI(`SCOPE_BUSY`,`${dI(null,[e],n)}; this command waits for that task.`),null}let u=l.filter(t=>!e.keys.has(t));u.length&&fI(`SCOPE_DENIED`,`Outside this task's scope: ${hI(u)}. Ask for it with task.requestScope, or leave it to the task that holds it.`);let d=l.filter(t=>e.tokens.has(t)&&a(t)!==e.tokens.get(t));if(d.length){for(let t of d)e.tokens.set(t,a(t));fI(`STALE_TARGET`,`${hI(d)} changed outside this task (the user, or an undo) since it last looked; read it again, then retry.`)}for(let t of l)e.pre.has(t)||e.pre.set(t,o(t));return{task:e,keys:l,values:l.map(o),mark:e.mark,fence:new Map(l.map(e=>[e,a(e)]))}},moved:e=>[...e.fence].filter(([e,t])=>a(e)!==t).map(([e])=>e),rebase(e){for(let t of e.fence.keys())e.fence.set(t,a(t))},record(r,o){if(!r||!o?.ok)return o;let{task:s}=r,c=e.read(),l=[],u=!1;for(let e of o.affectedIds??[]){let t=uI(e,c);if(!(!t||[...s.keys].some(e=>ZF(t,e)))){if(dI(s.taskId,[t],n)){l.push({code:`SCOPE_DENIED`,message:`${t} changed outside the task's scope.`});continue}for(let e of XF([t]))s.keys.add(e),u=!0,r.keys.includes(e)||(s.pre.set(e,{key:e,value:void 0}),r.values.push({key:e,value:void 0}))}}u&&t?.({type:`task.scope`,taskId:s.taskId,scope:[...s.keys]});for(let e of s.keys)s.tokens.set(e,a(e));if(o.authored){s.edits.push({receiptId:o.receiptId,values:r.values,keys:r.keys,mark:r.mark}),s.affectedIds=[...new Set([...s.affectedIds,...o.affectedIds])],o.undo?.historyEntryId&&i.set(o.undo.historyEntryId,s.taskId);for(let e of n.values())for(let n of r.keys)e!==s&&e.reads.has(n)&&(e.notices.push({code:`DEPENDENCY_CHANGED`,message:`${n}, which this task reads, was changed by task ${s.taskId}.`}),t?.({type:`task.dependencyChanged`,taskId:e.taskId,key:n,by:s.taskId}))}let d=s.notices.splice(0);return d.length||l.length?{...o,warnings:[...o.warnings,...l,...d].slice(0,12)}:o},traversal(e,t,r,a,o){let c=r.taskId?n.get(r.taskId):null;if(c&&e===`edit.undo`){let n=c.edits.findIndex(e=>e.receiptId===t.receiptId);n<0&&fI(`TARGET_BUSY`,`Inside a task, undo_edit takes the receiptId of the task's own newest edit${c.edits.length?` (now ${c.edits.at(-1).receiptId})`:``}.`),n<c.edits.length-1&&fI(`UNDO_CONFLICT`,`Later edits of this task come after it; undo them first, newest first: ${c.edits.slice(n+1).reverse().map(e=>e.receiptId).join(`, `)}.`);let i=c.edits.pop();return l(e,c,r,a,{historyEntryId:s(c,i.values,`editUndone`),output:{undoneReceiptId:i.receiptId}})}let u=n.get(i.get(o));return!c&&u&&fI(`TARGET_BUSY`,`The last edit belongs to running task ${u.taskId}${u.title?` (${u.title})`:``}; cancel or undo it from that task.`),null},dispose(){n.clear(),r.clear(),i.clear()}}}var _I=new Set([`unsupported_codec`,`encode_failed`,`render_failed`,`aborted`,`unknown`]),vI=new Set([`0`,`1-3`,`4-10`,`gte11`]),yI=Object.freeze({export_kind:new Set([`video`,`depth_video`,`frame`,`keyframe_pack`,`workflow_send`,`animation_project`,`contact_sheet`,`panel_pack`,`animatic`,`storyboard`,`render_pass`,`otio`]),format:new Set([`mp4`,`png`,`zip`,`cclayproject`,`otio`]),surface:new Set([`studio`,`workflow`,`embed`]),duration_bucket:new Set([`lt1s`,`1-3s`,`3-10s`,`10-30s`,`gte30s`]),failure_code:_I,objects:vI,stage:new Set([`preparing`,`encoding`,`finalizing`,`handoff`]),progress:new Set([`0`,`1-25`,`26-50`,`51-75`,`76-99`]),method:new Set([`workspace`,`download`]),reason:new Set([`none`,`unsupported`,`no_workspace`,`permission`,`write_failed`])}),bI=/^[a-f0-9]{32}$/;function xI(e,t){return e===`attempt_id`||e===`retry_of`?typeof t==`string`&&bI.test(t):e===`is_retry`?typeof t==`boolean`:yI[e]?.has(t)??!1}var SI=new Set([`Error`,`TypeError`,`RangeError`,`ReferenceError`,`SyntaxError`,`EvalError`,`URIError`,`AggregateError`,`AbortError`,`TimeoutError`,`NotAllowedError`,`NotSupportedError`,`NotFoundError`,`NotReadableError`,`InvalidStateError`,`QuotaExceededError`,`SecurityError`,`NetworkError`,`DataCloneError`,`OperationError`,`EncodingError`,`UnknownError`,`DOMException`,`non_error`,`other`]),CI=new Set([`lt1m`,`1-5m`,`5-15m`,`15-30m`,`gte30m`]),wI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,TI=20;function EI(e,t){return e===`duration_bucket`?CI.has(t):e===`scenes_touched`?Number.isInteger(t)&&t>=0&&t<=TI:e===`session_id`?typeof t==`string`&&wI.test(t):e.endsWith(`_bucket`)&&vI.has(t)}var DI=Object.freeze([`refusals_ui`,`refusals_agent`,`undos`,`errors`,`rage_clicks`,`dead_clicks`,`shortcut_ignored`,`search_empty`,`nav_thrash`,`camera_thrash`,`long_tasks`,`compiles`]),OI=Object.freeze([`active_time`,...DI,`long_task_max`,`late_tick_ratio`]),kI=new Set([`0`,`1`,`2`,`3`,`4-5`,`6-10`,`gte11`]),AI=new Set([`lt50`,`50-150`,`150-500`,`500-2000`,`gte2000`]),jI=new Set([`0`,`lt5`,`5-20`,`20-50`,`gte50`]),MI=new Map(DI.map(e=>[e,0])),NI=new Map,PI=0,FI=0,II=0,LI=!1;function RI(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return t<=3?String(t):t<=5?`4-5`:t<=10?`6-10`:`gte11`}function zI(e){return e>=50?e<150?`50-150`:e<500?`150-500`:e<2e3?`500-2000`:`gte2000`:`lt50`}function BI(e,t){if(!(t>0)||!(e>0))return`0`;let n=e/t*100;return n<5?`lt5`:n<20?`5-20`:n<50?`20-50`:`gte50`}function VI(e,t=1){return!MI.has(e)||!Number.isFinite(t)||t<1?!1:(MI.set(e,MI.get(e)+Math.floor(t)),!0)}function HI(e,t){let n=NI.get(e)??0;return n<t&&(NI.set(e,n+1),!0)}function UI(e){!Number.isFinite(e)||e<0||(VI(`long_tasks`),PI=Math.max(PI,e))}function WI(e,t){!Number.isInteger(e)||!Number.isInteger(t)||e<0||t<e||(FI+=e,II+=t)}function GI(e=globalThis.PerformanceObserver){if(LI)return!0;try{return typeof e!=`function`||!e.supportedEntryTypes?.includes(`longtask`)?!1:(new e(e=>{for(let t of e.getEntries())UI(t.duration)}).observe({type:`longtask`}),LI=!0,!0)}catch{return!1}}function KI(){return{...Object.fromEntries([...MI].map(([e,t])=>[e,RI(t)])),long_task_max:zI(PI),late_tick_ratio:BI(FI,II)}}function qI(e,t){return e===`active_time`?CI.has(t):e===`long_task_max`?AI.has(t):e===`late_tick_ratio`?jI.has(t):MI.has(e)&&kI.has(t)}var JI=Object.freeze(`dock_tab_board.dock_tab_animation.dock_tab_assets.mode_scene.mode_pose.mode_camera.mode_motion.mode_sculpt.tool_move.tool_rotate.tool_scale.tool_ik.tool_pin.tool_front.tool_side.tool_back.tl_play.shot_add.shot_delete.camera_key_add.export_animation_project.export_keyframe_pack.export_video.export_video_shot.export_render_passes.export_depth_video.export_storyboard.export_otio.menu_undo.menu_redo.agent_send.agent_stop.agent_steer.agent_retry.agent_connect.agent_panel.board_export.board_stylize`.split(`.`)),YI=e=>JI.includes(e)?e:`other`,XI=/^[a-f0-9]{32}$/,ZI=new Set([`0`,`1`,`2`,`3`,`4-5`,`6-10`,`gte11`]),QI=new Set([`lt10s`,`10-30s`,`30-60s`,`1-2m`,`2-5m`,`gte5m`]),$I=new Set([`lt2s`,`2-10s`,`10-60s`,`gte60s`]),eL=new Set([`lt50`,`50-150`,`150-500`,`500-2000`,`gte2000`]),tL=new Set([...s,`other`]),nL=Object.freeze([`openai-codex`,`anthropic`,`anthropic-subscription`,`openai`,`google`,`minimax`,`minimax-cn`,`openrouter`,`cliproxy`,`openai-compatible`]),rL=e=>s.includes(e)?e:`other`;function iL(e){return!Number.isFinite(e)||e<1e4?`lt10s`:e<3e4?`10-30s`:e<6e4?`30-60s`:e<12e4?`1-2m`:e<3e5?`2-5m`:`gte5m`}function aL(e){return!Number.isFinite(e)||e<2e3?`lt2s`:e<1e4?`2-10s`:e<6e4?`10-60s`:`gte60s`}var $=(...e)=>t=>e.includes(t),oL=e=>t=>e.has(t),sL=e=>typeof e==`string`&&XI.test(e),cL=e=>typeof e==`boolean`,lL=oL(ZI),uL=oL(QI),dL=Object.freeze({"studio:refused":{code:oL(tL),origin:$(`ui`,`agent`),phase:$(`admission`,`commit`),group:$(`object`,`shot`,`cast`,`scene`,`motion`,`edit`,`task`,`agent`,`other`)},"app:render_crash":{error_type:oL(SI)},"app:gl_lost":{kind:$(`unavailable`,`context_lost`)},"studio:ready":{boot:$(`lt2s`,`2-5s`,`5-15s`,`gte15s`)},"playback:summary":{duration:uL,late_ticks:$(`0`,`lt5`,`5-20`,`20-50`,`gte50`),max_catchup:$(`1`,`2`,`3-5`,`gte6`),fps:$(`12`,`24`,`30`,`60`,`other`),speed:$(`0.5`,`1`,`2`,`other`),measured_fps:$(`lt20`,`20-40`,`40-55`,`gte55`,`unknown`)},"guide:opened":{mode:$(`animation`,`storyboard`)},"guide:step":{mode:$(`animation`,`storyboard`),step:$(`1`,`2`,`3`,`4`),step_ms:uL},"guide:dismissed":{mode:$(`animation`,`storyboard`),reached:$(`1`,`2`,`3`,`4`)},"guide:completed":{mode:$(`animation`,`storyboard`)},"agent:panel_toggled":{open:cL,via:$(`key`,`button`)},"object:deleted_soon":{age:oL($I)},"object:delete_undone":{age:oL($I)},"edit:undone":{age:oL($I),kind:$(`pose`,`camera`,`object`,`shot`,`prompt`,`agent_turn`,`ik_preview`,`other`),via:$(`key`,`menu`,`button`),result:$(`done`,`noop`,`refused`)},"agent:turn_summary":{turn_id:sL,outcome:$(`succeeded`,`failed`,`cancelled`),wall:uL,first_tool:uL,tool_calls:lL,tool_failed:lL,refused:lL,refusal_top:e=>e===`none`||tL.has(e),stale_retry:lL,authored:cL,drafts:lL,qa_first:$(`clean`,`problems`),qa_last:$(`clean`,`problems`),qa_trend:$(`improved`,`flat`,`worse`,`na`),stuck:cL,cancel_phase:$(`before_tool`,`during_tool`,`after_tool`,`na`)},"motion:draft_compiled":{draft_index:lL,qa_clean:cL,qa_problems:lL,qa_frames:$(`0`,`1-10`,`11-50`,`51-200`,`gte201`),compile:oL(eL),installed:cL,stuck:cL,repaired:cL,searched:cL,adjusted:cL,frames:$(`lt30`,`30-120`,`121-480`,`gte481`)},"shortcut:ignored":{key_class:$(`undo`,`redo`,`mode`,`transform`,`frame`,`duplicate`,`delete`),reason:$(`no_selection`,`wrong_mode`,`workflow_mode`,`busy`,`empty_history`)},"shortcut:unbound":{combo:$(`copy`,`paste`,`cut`,`select_all`,`group`,`find`,`rename`,`help`)},"help:shortcuts_opened":{},"search:no_results":{surface:$(`assets`,`outliner`),query_len:$(`1`,`2-3`,`4-8`,`gte9`)},"nav:thrash":{surface:$(`dock_tab`,`mode`,`agent_panel`),switches:$(`4-5`,`6-10`,`gte11`),window_s:$(10)},"camera:thrash":{gestures:$(`6-10`,`gte11`),kind_mix:$(`orbit`,`fly`,`pan`,`mixed`),window_s:$(20)},"agent:connect_opened":{entry:$(`first_run`,`failure_card`,`signed_out`,`menu`,`other`)},"agent:connect_started":{provider:$(...nL,`other`),method:$(`oauth`,`api_key`,`chatgpt`)},"agent:connect_finished":{provider:$(...nL,`other`),method:$(`oauth`,`api_key`,`chatgpt`),outcome:$(`ok`,`failed`,`cancelled`,`abandoned`),step:$(`list`,`prompt`,`waiting`,`done`),duration:uL},"agent:model_changed":{provider:$(...nL,`other`),after_failure:cL},"agent:prompt_sent":{turn_id:sL,provider:$(...nL,`other`),via:$(`typed`,`retry_button`,`regenerate`,`chip`,`supervisor`),prompt_len:$(`1-20`,`21-80`,`81-240`,`gte241`),compose_ms:uL,similarity:$(`first`,`same`,`near`,`different`),gap:e=>e===`first`||uL(e),prev_outcome:$(`succeeded`,`failed`,`cancelled`,`none`),turn_index:lL,attached:cL,task_mode:cL},"ui:rage_click":{control:$(...JI,`other`),clicks:$(`3`,`4-5`,`gte6`),changed:cL},"ui:dead_click":{control:$(...JI,`other`),reason:$(`aria_disabled`,`refused`,`no_effect`)},"update:notice_shown":{kind:$(`global`,`npx`),behind:$(`patch`,`minor`,`major`)},"update:clicked":{action:$(`update_now`,`copy_command`,`later`,`dismiss`,`release_notes`),kind:$(`global`,`npx`)},"update:finished":{outcome:$(`ok`,`failed`),error_class:$(`none`,`permission`,`network`,`node_version`,`npm_missing`,`other`),duration:uL},"agent:post_turn_edit":{turn_id:sL,edited:cL,pose:lL,camera:lL,object:lL,shot:lL,prompt_block:lL,first_delay:uL}}),fL=Object.freeze({"app:friction_summary":OI,...Object.fromEntries(Object.entries(dL).map(([e,t])=>[e,Object.keys(t)]))});function pL(e){if(e===`app:session_ended`)return EI;if(e===`app:friction_summary`)return qI;let t=dL[e];return t?(e,n)=>Object.hasOwn(t,e)&&t[e](n):null}var mL=12e4,hL=Object.freeze([`pose`,`camera`,`object`,`shot`,`prompt`]),gL=null,_L=!1,vL={set:(e,t)=>setTimeout(e,t),clear:e=>clearTimeout(e),now:()=>Date.now()};function yL(){let e=gL;if(!e)return null;gL=null;try{e.timers.clear(e.timer)}catch{}let t=e.firstAt!==null,n={turn_id:e.turnId,edited:t,...Object.fromEntries(hL.map(t=>[t===`prompt`?`prompt_block`:t,RI(e.counts[t])])),...t?{first_delay:iL(e.firstAt-e.openedAt)}:{}};try{Promise.resolve(e.emit(`agent:post_turn_edit`,n)).catch(()=>{})}catch{}return n}function bL(e,t,n=vL){if(yL(),typeof e==`string`&&typeof t==`function`)try{gL={turnId:e,emit:t,timers:n,openedAt:n.now(),firstAt:null,counts:Object.fromEntries(hL.map(e=>[e,0]))},gL.timer=n.set(yL,mL),!_L&&typeof globalThis.addEventListener==`function`&&(_L=!0,globalThis.addEventListener(`pagehide`,yL))}catch{gL=null}}function xL(e){if(!gL||!hL.includes(e))return!1;try{let t=gL.timers.now();return t-gL.openedAt>=12e4?(yL(),!1):(gL.counts[e]+=1,gL.firstAt===null&&(gL.firstAt=t),!0)}catch{return!1}}var SL=1e3,CL=24,wL=3,TL=1e4,EL=500,DL=2,OL=2,kL=`[data-fid], button, [role='button'], [role='tab'], [role='menuitem'], a[href]`,AL=gB,jL=()=>performance.now(),ML=null,NL=null,PL=new Map,FL=-1/0,IL=-1/0,LL=-1/0;function RL(e){let t=jL();FL=t,e||(IL=t)}var zL=(e,t)=>t?.isComposing||!!e?.closest?.(`input, textarea, select, [contenteditable=''], [contenteditable='true']`),BL=e=>!!e?.closest?.(`[aria-disabled='true'], :disabled`),VL=e=>e>=6?`gte6`:e>=4?`4-5`:`3`,HL=(e,t)=>{try{AL(e,t)}catch{}};function UL(){clearTimeout(NL);let e=ML;if(ML=null,!e||e.count<wL)return;VI(`rage_clicks`);let t=jL();t-(PL.get(e.control)??-1/0)<TL||(PL.set(e.control,t),HI(`ui:rage_click:${e.control}`,DL)&&HL(`ui:rage_click`,{control:e.control,clicks:VL(e.count),changed:e.changed()}))}function WL(e,t){VI(`dead_clicks`),HI(`ui:dead_click:${e}`,OL)&&HL(`ui:dead_click`,{control:e,reason:t})}function GL({target:e,x:t,y:n,event:r,observe:i=()=>()=>{}}){if((r?.button??0)!==0||zL(e,r))return;let a=e?.closest?.(kL);if(!a)return;let o=a.closest(`[data-fid]`)?.getAttribute(`data-fid`),s=YI(o),c=jL();if(ML&&ML.control===s&&ML.element===a&&c-ML.at<=SL&&Math.hypot(t-ML.x,n-ML.y)<=CL)ML.count+=1;else{UL();let e=c;ML={control:s,element:a,at:c,x:t,y:n,count:1,changed:()=>FL>=e||LL>=e},NL=setTimeout(UL,SL)}if(BL(a)){WL(s,`aria_disabled`);return}if(s===`other`)return;let l=i(()=>{LL=jL()});setTimeout(()=>{try{l()}catch{}IL>=c?WL(s,`refused`):FL<c&&LL<c&&WL(s,`no_effect`)},EL)}function KL(e=globalThis.document){if(!e?.addEventListener)return()=>{};let t=t=>{if(typeof MutationObserver!=`function`)return()=>{};let n=new MutationObserver(t);return n.observe(e.body??e,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),()=>n.disconnect()},n=e=>{try{GL({target:e.target,x:e.clientX,y:e.clientY,event:e,observe:t})}catch{}};return e.addEventListener(`pointerdown`,n,!0),()=>e.removeEventListener(`pointerdown`,n,!0)}var qL=gB,JL=()=>Date.now(),YL=3,XL=20,ZL=500,QL=[[/^objects?\./,`object`],[/^shot\./,`shot`],[/^(characters?|cast)\./,`cast`],[/^scene\./,`scene`],[/^(?:motion|ik)\./,`motion`],[/^edit\./,`edit`],[/^task\./,`task`],[/^agent\./,`agent`]],$L=e=>QL.find(([t])=>t.test(String(e)))?.[1]??`other`,eR=[[/^shot\.captureCamera$/,null],[/^shot\.(create|createStill|duplicate|split)$/,`shot_add`],[/^shot\.(setCameraRail|clearCameraRail)$/,`rail_edit`],[/^shot\.addKey$/,`camera_key_record`],[/^shot\./,`shot_edit`],[/^(character\.(setPose|setIkKey|removeIkKey|clearIkKeys)|ik\.|motion\.rangePin\.)/,`pose_edit`],[/^(object\.(add|duplicate|sculpt|createKit)|character\.add)$/,`object_insert`],[/^(objects?\.|character\.(set|remove|update|move)$|characters\.arrange$|cast\.replace$)/,`object_transform`],[/^motion\.set$/,`prompt_block_edit`]],tR=null,nR=e=>(tR??=new Map(Object.entries(BR).flatMap(([e,t])=>t.map(t=>[t,e])))).get(e);function rR(e,{placeAs:t,rail:n=!1}={}){return e===`asset.import`?t===`cutout`?`cutout_insert`:`object_insert`:e===`shot.setCamera`&&n?`rail_edit`:eR.find(([t])=>t.test(String(e)))?.[1]??null}var iR=[`cameraRail`,`craneHeight`,`railFollow`,`dollyTiming`],aR=e=>Object.keys(e?.patch??{}).some(e=>iR.includes(e)),oR=new Set;function sR(e,t,n){if(e===`run.begin`||e===`run.update`){for(n.txId&&aR(t?.args)&&oR.add(n.txId);oR.size>50;)oR.delete(oR.values().next().value);return{}}return{placeAs:t?.placeAs,rail:e===`run.commit`?oR.delete(n.txId):aR(t)}}var cR=new Set([`agent.turn.finish`,`task.finish`]);function lR(e,t=`ui`,n){return cR.has(e)||t!==`ui`?`agent_turn`:nR(rR(e,n))??`other`}var uR=`craft`,dR=kR((e,t)=>qL(e,t));function fR(e){uR=e,dR=kR((e,t)=>qL(e,t))}var pR=(e,t)=>{try{qL(e,t)}catch{}};function mR(e,t,n){if(e.code===`CANCELLED`)return;t===`ui`&&RL(!1);let r=t===`ui`?`ui`:`agent`,i=rL(e.code),a=$L(n);VI(r===`ui`?`refusals_ui`:`refusals_agent`),HI(`studio:refused:${i}:${a}:${r}`,YL)&&pR(`studio:refused`,{code:i,origin:r,phase:e.phase,group:a})}var hR=new Map;function gR(e){let t=new Map;return{get:e=>t.get(e),remember(n,{id:r,origin:i,action:a,args:o}){let s=sR(r,o,n);if(i===`ui`&&n.ok!==!1&&RL(!0),r===`edit.undo`&&i===`ui`&&n.status===`undone`&&VI(`undos`),i===`ui`&&n.authored===!0&&!r.startsWith(`edit.`)&&yR(rR(a??r,s)),n.undo?.canUndoDirect&&!r.startsWith(`edit.`))for(t.set(n.undo.historyEntryId,n),hR.set(n.receiptId,{at:JL(),kind:lR(a??r,i,s)});hR.size>ZL;)hR.delete(hR.keys().next().value);for(let[n,r]of t)e.isRetained?.(r)===!1&&(t.delete(n),hR.delete(r.receiptId))}}}var _R=-1/0,vR=()=>_R;function yR(e){if(e){_R=JL();try{Zz(e),dR(uR,e)}catch{}xL(nR(e))}}var bR={undone:`done`,noop:`noop`};function xR(e,t){let n=t?t.ok===!1?`refused`:bR[t.status]:`done`;if(!n||!HI(`edit:undone`,XL))return;let r=n===`done`&&t?hR.get(t.undoneReceiptId):null;pR(`edit:undone`,{kind:t?r?.kind??`other`:`ik_preview`,via:e,result:n,...r?{age:aL(JL()-r.at)}:{}})}var SR=(e,t)=>JSON.stringify(e)===JSON.stringify(t),CR=(e,t)=>{throw new $e(e,t)},wR=(e,t,n)=>e?.then?e.then(t,n):t(e),TR=e=>e.slice(-12).map(e=>({code:`STUDIO_TOAST`,message:[...e.message].slice(0,120).join(``)})),ER=0;function DR({registry:e,ports:t}){let n=new Map,r=new Map,i=new Map,a=new Set,o=new Map,s=gR(t),l=null,u=gI({ports:t,emit:e=>f(e)});function d(n,r,i){if(i.origin===`ui`)return;if(n.exposure===`ui-only`&&CR(`CAPABILITY_MISSING`,n.uiOnlyHint??`This command is available only from the Studio UI.`),n.id===`load_scenes`){let t=e=>[...new Set(e.map(e=>e.id))].sort();if(SR(t(r.document.scenes),t(e.state().scenes)))return}else if(n.exposure!==`confirm`||n.requiresConfirmation?.(e.state(),r)===!1)return;let a=o.get(i.confirmationToken);(!a||a.id!==n.id||!SR(a.args,r)||!SR(a.host,t.read().host)||a.expires<(t.now??Date.now)())&&CR(`CONFIRMATION_REQUIRED`,n.confirmationReason??`This command needs user confirmation.`),o.delete(i.confirmationToken)}let f=e=>{for(let t of a)t(e);t.emit?.(e)},p=Dn.TargetGuard.properties.targetId,m=e=>({type:`object`,properties:e,required:Object.keys(e),additionalProperties:!1}),h={type:`object`,properties:{},required:[],additionalProperties:!0},g={...RF(m,p),...u.controls(m,p),"run.begin":m({id:p,args:h}),"run.update":m({txId:p,args:h}),"run.commit":m({txId:p}),"run.cancel":m({txId:p}),"job.await":{...m({jobId:p}),properties:{jobId:p,timeoutMs:{type:`integer`,minimum:1,maximum:3e5,default:3e4}}},"job.cancel":m({jobId:p}),"edit.undo":{...m({receiptId:p}),required:[]},"edit.redo":{...m({receiptId:p}),required:[]}},_=e=>(t.clearTimeout??clearTimeout)(e);function v(e,n=!1,i=new $e(`CANCELLED`,`Transaction was cancelled.`)){r.delete(e.txId),_(e.timer),e.workTimer!==void 0&&_(e.workTimer),e.controller.abort(i),e.session.cancel({restore:SR(e.before.host,t.read().host)}),f({type:`transaction.cancelled`,txId:e.txId,expired:n})}function y(e){e.timer!==void 0&&_(e.timer),e.timer=(t.setTimeout??setTimeout)(()=>v(e,!0),t.transactionIdleMs??3e4)}function b(n,a,o,c){if(n.startsWith(`task.`))return u.control(n,a,o,c,l?`Finish the agent turn first.`:r.size?`Finish the open command transaction first.`:null);if(n.startsWith(`agent.turn.`)){if((o.origin!==`agent`||o.turnId!==a.turnId)&&CR(`CAPABILITY_MISSING`,`Only the owning agent turn can control this transaction.`),n===`agent.turn.begin`)return(l||r.size||u.size)&&CR(`TARGET_BUSY`,`Finish the open transaction first.`),l={txId:a.turnId,before:c,affectedIds:new Set,toasts:[],session:null},x(n,l,o,c);l?.txId!==a.turnId&&CR(`STALE_TARGET`,`The agent turn is no longer open.`);let e=l;if(n===`agent.turn.mark`||n===`agent.turn.rollback`)return x(n,zF(n,e),o,c);if(n===`agent.turn.cancel`)return l=null,e.session?.cancel(),x(n,e,o,c);try{e.historyEntryId=e.session?.commit().historyEntryId}catch(t){throw e.session?.cancel(),t}finally{l=null}return x(n,e,o,e.before)}let f=n===`edit.undo`||n===`edit.redo`,p=f&&u.traversal(n,a,o,c,n===`edit.undo`?t.history?.(!1):null);if(p)return p;if(l&&!n.startsWith(`job.`)&&!(f&&!l.session)){if(n===`edit.undo`&&o.turnId===l.txId)return Pn(HF(l,a,o,c,()=>t.read()));CR(`TARGET_BUSY`,`Finish the agent turn before traversing history or opening another transaction.`)}if(f){let e=n===`edit.redo`,r=t.history?.(e),i=a.receiptId?t.receipt(a.receiptId):s.get(r)??(r?{receiptId:r,host:c.host,affectedIds:[c.host.sceneId],undo:{historyEntryId:r,entries:1,canUndoDirect:!0}}:null);if(!a.receiptId&&!i)return Pn({ok:!0,status:`noop`,action:n,commandId:o.commandId,receiptId:crypto.randomUUID(),host:c.host,authored:!1,mutated:!1,revision:{before:c.revision,after:c.revision},affectedIds:[],delta:[],checks:{coverage:`native-history-restoration`},undo:null,warnings:[]});(!i?.undo||!t.isRetained(i))&&CR(`UNDO_EXPIRED`,`The receipt no longer has a retained history entry.`),SR(i.host,c.host)||CR(`STALE_SCENE`,`The receipt belongs to another document.`),(e?r!==i.undo.historyEntryId:!t.canUndo(i))&&CR(`UNDO_CONFLICT`,`Another edit owns the history boundary.`),(e?t.redo:t.undo)();let l=t.read(),u=i.affectedIds,d=u.map(e=>({...c.host,targetId:e,token:t.readTarget?.(e)??`removed-${crypto.randomUUID()}`}));return Pn({ok:!0,status:e?`applied`:`undone`,commandId:o.commandId,receiptId:crypto.randomUUID(),host:c.host,authored:!0,revision:{before:c.revision,after:l.revision},affectedIds:u,delta:u.slice(0,8).map(e=>({id:e,after:{token:d.find(t=>t.targetId===e).token}})),checks:{coverage:`native-history-restoration`},undo:{...i.undo,canUndoDirect:e},warnings:[],...e?{action:n,mutated:!0}:{undoneReceiptId:i.receiptId,restoredTargets:d},...u.length>8?{detailCursor:o.commandId}:{}})}if(n.startsWith(`job.`)){let e=i.get(a.jobId);(!e||!SR(e.host,c.host))&&CR(`STALE_TARGET`,`Job is not in this document.`),n===`job.cancel`&&!e.outcome&&e.controller.abort(new $e(`CANCELLED`,`Job was cancelled.`));let r;return(n===`job.await`&&!e.outcome?Promise.race([e.completion,new Promise((e,n)=>{r=(t.setTimeout??setTimeout)(()=>n(new $e(`TIMEOUT`,`Job is still running.`)),a.timeoutMs)})]):e.completion).then(t=>Pn({...t,commandId:o.commandId,...t.ok?{receiptId:crypto.randomUUID()}:{},jobId:e.id})).finally(()=>{r!==void 0&&_(r)})}let m;if(n===`run.begin`){r.size&&CR(`TARGET_BUSY`,`Finish or cancel the open command transaction first.`);let n=e.prepare(a.id,a.args);d(n.entry,n.args,o),n.entry.kind!==`mutation`&&CR(`INVALID_ARGUMENT`,`Only mutations can open a transaction.`),m={txId:crypto.randomUUID(),entry:n.entry,before:c,origin:o.origin,targetId:n.args.characterId??null,controller:new AbortController,session:t.beginAction(n.entry.undoDomain,n.args.characterId??null),affectedIds:new Set,toasts:[]},r.set(m.txId,m),y(m)}else{if(m=r.get(a.txId),(!m||!SR(m.before.host,c.host))&&CR(`STALE_TARGET`,`Transaction is no longer open in this document.`),o.origin!==m.origin&&CR(`TARGET_BUSY`,`This transaction belongs to another origin.`),m.updating&&n!==`run.cancel`&&CR(`TARGET_BUSY`,`A transaction update is still running.`),n===`run.update`){let i=e.prepare(m.entry.id,a.args);m.entry.undoDomain===`motion`&&i.args.characterId!==m.targetId&&CR(`INVALID_ARGUMENT`,`A motion transaction keeps its original target.`);let s=[],l=t.captureToasts?.(e=>s.push(typeof e==`string`?{message:e}:e)),u={origin:o.origin,signal:m.controller.signal,check(){m.controller.signal.throwIfAborted(),(!r.has(m.txId)||!SR(m.before.host,t.read().host))&&CR(`STALE_TARGET`,`Transaction is no longer current.`)}},d=e=>{l?.(),_(m.workTimer),m.updating=!1,u.check(),s.length&&t.read().revision===c.revision&&CR(`TARGET_NOT_READY`,s.at(-1).message);for(let t of e.affectedIds)m.affectedIds.add(t);return m.toasts.push(...s),y(m),x(n,m,o,c)},f=e=>{throw l?.(),_(m.workTimer),m.updating=!1,!(e instanceof $e)&&s.length&&t.read().revision===c.revision&&(e=new $e(`TARGET_NOT_READY`,s.at(-1).message)),r.has(m.txId)&&v(m),e};try{m.updating=!0,_(m.timer),m.workTimer=(t.setTimeout??setTimeout)(()=>v(m,!0,new $e(`TIMEOUT`,`${m.entry.id} exceeded its deadline.`)),m.entry.timeoutMs??3e4);let n=m.session.run(()=>e.invoke(m.entry,i.args,u));if(!n?.then)return d(n);let r=new Promise((e,t)=>m.controller.signal.addEventListener(`abort`,()=>t(m.controller.signal.reason),{once:!0}));return Promise.race([n,r]).then(d,f)}catch(e){return f(e)}}if(n===`run.cancel`&&v(m),n===`run.commit`){r.delete(m.txId),_(m.timer);try{m.historyEntryId=m.session.commit().historyEntryId}catch(e){throw m.session.cancel({restore:!1}),e}}}return x(n,m,o,n===`run.commit`?m.before:c)}function x(e,n,r,i){let a=t.read();return Pn({ok:!0,status:`completed`,kind:`transaction`,commandId:r.commandId,receiptId:crypto.randomUUID(),host:i.host,action:e,txId:n.txId,authored:!!n.historyEntryId,revision:{before:i.revision,after:a.revision},affectedIds:[...n.affectedIds],delta:[],checks:{coverage:`wire-transaction`},warnings:TR(n.toasts),undo:n.historyEntryId?{historyEntryId:n.historyEntryId,entries:1,canUndoDirect:!0}:null})}function S(e,n,r,i){let a=i??t.read().revision!==n.revision;return Pn({ok:!1,commandId:e.commandId,host:n.host,code:c(r),phase:a?`commit`:`admission`,affectedIds:[],expectedTargets:[],currentTargets:[],mutated:a,preserved:{authoredState:a?`changed`:`unchanged`},recovery:{action:`inspect`,retryAllowed:!1},message:[...String(r.message||r)].slice(0,2e3).join(``)})}let C=(e=[],t=[],n=0,r=12)=>{let i=[...n?[{code:`READBACK_TRUNCATED`,count:n,message:`Readback lists 8 of ${8+n} affected ids; inspect_studio scope entities with ids for the rest.`}]:[],...e,...TR(t)];return i.length<=r?i:[...i.slice(0,r-1),{code:`WARNINGS_TRUNCATED`,count:i.length-r+1,message:`${i.length-r+1} more warnings omitted.`}]};function w(e,n,r,i,a,o=[],s=null){let c=t.read(),l=c.revision!==r.revision,u=a??(l?s?.txId:null)??null;e.kind===`mutation`&&l&&!a&&!s&&CR(`UNCERTAIN_APPLY`,`${e.id} changed the scene without one undoable entry.`);let d=e.kind===`job`||e.kind===`document`||e.kind===`mutation`&&l&&(s||c.revision>r.revision+1),f=d||l?i.affectedIds:e.kind===`transient`?[r.host.sceneId]:[];if(s&&l)for(let e of f)s.affectedIds.add(e),s.mark?.since.add(e);let p=a=>Pn({ok:!0,commandId:n.commandId,receiptId:crypto.randomUUID(),host:r.host,action:e.id,summary:i.summary,status:d?`completed`:e.kind===`transient`?`transient`:l?`applied`:`noop`,authored:l,...d?{kind:e.kind,...i.output===void 0?{}:{output:i.output},...SR(r.host,c.host)?{}:{nextHost:c.host}}:e.kind===`transient`?{view:{before:r.viewRevision??0,after:c.viewRevision??0}}:{mutated:l},revision:{before:r.revision,after:c.revision},affectedIds:f,delta:f.slice(0,8).map(e=>({id:e,after:t.readback?.(e,c,a>0)??{removed:!0}})),checks:{coverage:`studio-action:${e.id}`,...i.checks},warnings:C(i.warnings,o,Math.max(0,f.length-8),a>1?4:12),undo:u?{historyEntryId:u,entries:1,canUndoDirect:!s}:null,...f.length>8?{detailCursor:n.commandId}:{}});for(let e=0;;e++)try{return p(e)}catch(t){if(e>=2||t?.code!==`INVALID_RECEIPT`||!/8 KiB/.test(t.message))throw t}}function T(a,o={},c={}){let p={origin:`ui`,commandId:crypto.randomUUID(),...c};p.origin===`ui`&&(a===`edit.undo`||a===`edit.redo`)&&t.finishHistoryGesture?.();let m=t.read(),h=t.journal();l&&!SR(l.before.host,m.host)&&(l.session?.cancel({restore:!1}),l=null);let v=p.origin===`agent`&&p.turnId===l?.txId?l:null,y=u.of(p,a),x=a===`run.begin`?o?.id:a.startsWith(`run.`)?r.get(o?.txId)?.entry.id:void 0,C=(e,n,r,i=!1)=>v?(v.session??=t.beginAction(e,r),{result:v.session.run(()=>t.beginAction(e,r).run(n)),historyEntryId:null}):t.recordAction(e,n,r,i),T=!1,E,D,O,k,ee=!1,A,te=new AbortController,ne=()=>{D!==void 0&&_(D),O!==void 0&&_(O)},re=[],ie=()=>re.length&&t.read().revision===m.revision?new $e(`TARGET_NOT_READY`,re.at(-1).message):null,ae=e=>{if(k?.background){let t=k.completionCommandId??=crypto.randomUUID();h.begin(t),e=Pn({...e,commandId:t,jobId:k.id})}let n=h.record(e);return s.remember(n,{id:a,origin:p.origin,action:x,args:o}),t.remember?.(n),n},oe=e=>{ne(),E?.(),E=null,e instanceof $e||(e=ie()??e),p.origin===`ui`&&e.uiMessage&&t.showRefusal?.(e.uiMessage);let n=S(p,m,e,k?ee:void 0);mR(n,p.origin,x??a);let r=T?ae(n):n;return k&&!k.completion&&(k.outcome=r,k.completion=Promise.resolve(r),f({type:`job.completed`,jobId:k.id,receipt:r})),r};try{p.origin!==`ui`&&!SR(kn(p.host),m.host)&&CR(`STALE_SCENE`,`The live document changed.`),p.turnId&&!v&&a!==`agent.turn.begin`&&CR(`STALE_TARGET`,`The agent turn is no longer open.`);let s=JSON.stringify({id:a,args:o,...p});if(!h.begin(p.commandId,s))return h.get(p.commandId)??n.get(p.commandId)??S(p,m,new $e(`UNCERTAIN_APPLY`,`Command is still executing.`));T=!0;let{entry:c,args:l}=g[a]?{args:On(g[a],o)}:e.prepare(a,o);if(p.origin!==`ui`&&(!y&&!a.startsWith(`task.`)&&!c?.readOnly&&![`job.await`,`job.cancel`,`agent.turn.mark`,`agent.turn.rollback`,`agent.turn.finish`,`agent.turn.cancel`].includes(a)&&p.expectedRevision!==m.revision&&CR(`STALE_SCENE`,`Authored state changed; obtain fresh intent.`),!c?.readOnly&&m.busy&&!v&&!r.has(l.txId)&&!a.startsWith(`job.`)&&CR(`TARGET_BUSY`,`Finish the current editor gesture first.`)),g[a])return wR(b(a,l,p,m),ae,oe);r.size&&CR(`TARGET_BUSY`,`Finish or cancel the open command transaction first.`),v&&c.kind===`document`&&CR(`TARGET_BUSY`,`Finish the agent turn before changing documents.`),d(c,l,p);let _=u.admit(y,c,l,p,m);E=t.captureToasts?.(e=>re.push(typeof e==`string`?{message:e}:e));let x=c.domain??c.undoDomain,se=c.target?.(l,m)??l.characterId??l.shotId??l.objectId,ce=se?t.readTarget?.(se):null,le=x?m.domainRevisions?.[x]:null,ue=()=>{let e=t.read();ce=se?t.readTarget?.(se):null,le=x?e.domainRevisions?.[x]:null,_?.keys.length&&u.rebase(_)},de=new Set,fe={origin:p.origin,signal:te.signal,taskId:p.taskId??null,turnId:p.turnId??null,callId:typeof p.callId==`string`?p.callId:null,check(){te.signal.throwIfAborted();let e=t.read();SR(e.host,m.host)||CR(`STALE_TARGET`,`The open document or scene changed while the job was running.`),x&&!y&&e.domainRevisions?.[x]!==le&&CR(`STALE_TARGET`,`The ${x} data changed while the job was running (revision ${le} to ${e.domainRevisions?.[x]}); an edit landed between the request and its result.`);let n=_?.keys.length?u.moved(_):se&&t.readTarget?.(se)!==ce?[se]:[];n.length&&CR(`STALE_TARGET`,`${n.join(`, `)} changed while the job was running.`)},commit(e){fe.check(),x||CR(`INVALID_ARGUMENT`,`A committing job must declare its domain.`);let t=C(x,e,se??null);return t?.then&&CR(`INVALID_ARGUMENT`,`Job publication must be synchronous; prepare before commit.`),A=t.historyEntryId,ee||=!!A,k&&ue(),t.result},run(t,n={}){k?fe.check():te.signal.throwIfAborted();let r=e.prepare(t,n);d(r.entry,r.args,p);let i=()=>e.invoke(r.entry,r.args,fe),a=r.entry.kind===`mutation`?C(r.entry.undoDomain,i,r.args.characterId??null,!0):{result:i()};return k&&ue(),wR(a,e=>wR(e.result,t=>{k&&(fe.check(),ue(),ee||=!!e.historyEntryId);for(let e of t.affectedIds)de.add(e);return t}))}};c.kind===`job`&&(k={id:crypto.randomUUID(),host:m.host,controller:te,background:!1},i.set(k.id,k)),D=(t.setTimeout??setTimeout)(()=>{let e=new $e(`TIMEOUT`,`${c.id} exceeded its deadline.`);te.abort(e)},k&&c.background===!0?3e5:c.timeoutMs??3e4);let pe=()=>{let t=e.invoke(c,l,fe);if(!t?.then)return t;let n=new Promise((e,t)=>te.signal.addEventListener(`abort`,()=>t(te.signal.reason),{once:!0}));return Promise.race([t,n])},me=BF(v),he=c.kind===`mutation`?C(c.undoDomain,pe,l.characterId??null):{result:pe(),historyEntryId:null},ge=({result:e,historyEntryId:t})=>wR(e,e=>{ne(),E?.(),E=null;let n=e?.output===void 0?ie():null;if(n)throw n;return u.record(_,VF(v,me,ae(w(c,p,m,{...e,affectedIds:[...new Set([...e.affectedIds,...de])]},t??A,re,v))))}),_e=he?.then?he.then(ge):ge(he),ve=_e?.then?_e.catch(oe):_e;if(k){k.completion=Promise.resolve(ve).then(e=>(k.outcome=e,f({type:`job.completed`,jobId:k.id,receipt:e}),e));let e=()=>{k.background=!0;let e=t.read();return h.record(Pn({ok:!0,commandId:p.commandId,receiptId:crypto.randomUUID(),host:m.host,action:c.id,status:`started`,kind:`job`,jobId:k.id,authored:!1,revision:{before:e.revision,after:e.revision},affectedIds:[],delta:[],checks:{coverage:`studio-action:${c.id}`},warnings:[],undo:null}))};if(ve?.then&&p.wait===!1)return e();if(ve?.then&&c.background===!0){let r=Promise.race([k.completion,new Promise(n=>{O=(t.setTimeout??setTimeout)(()=>n(e()),c.timeoutMs??3e4)})]).finally(()=>n.delete(p.commandId));return n.set(p.commandId,r),r}}if(ve?.then){let e=(k?.completion??ve).finally(()=>n.delete(p.commandId));return n.set(p.commandId,e),e}return ve}catch(e){return oe(e)}}function E(...e){ER++;try{let t=T(...e);return t?.then?t.finally(()=>{ER--}):(ER--,t)}catch(e){throw ER--,e}}return{run:E,noteUndone:xR,confirm(n,r={}){let i=e.prepare(n,r),a=crypto.randomUUID();return o.set(a,{id:n,args:i.args,host:t.read().host,expires:(t.now??Date.now)()+3e5}),a},subscribe(e){return a.add(e),()=>a.delete(e)},dispose(){l?.session?.cancel(),l=null,u.dispose();for(let e of r.values())v(e);for(let e of i.values())e.outcome||e.controller.abort(new $e(`CANCELLED`,`Studio closed.`));a.clear()}}}var OR=Object.freeze([`pose_edit`,`object_insert`,`cutout_insert`,`object_transform`,`shot_add`,`shot_edit`,`camera_key_record`,`rail_edit`,`prompt_block_add`,`prompt_block_edit`]);function kR(e){let t=new Set,n=(n,r)=>![`craft`,`playground`].includes(n)||t.has(n)||!OR.includes(r)?!1:(t.add(n),e(`${n}:first_edit`,{edit_kind:r,definition_version:2}),!0);return n.seen=e=>t.has(e),n}var AR=Object.freeze([`read`,`camera`,`scene_write`,`prompt_authoring`,`frame_capture`,`motion_generate`,`motion_apply`,`project_io`,`other`]),jR=Object.freeze([`workflow_read`,`workflow_write`,`workflow_run`,`frame_capture`,`image_generate`,`scene_write`,`other`]),MR=Object.freeze([`workflow:run_requested`,`workflow:run_succeeded`,`workflow:run_failed`,`workflow:run_cancelled`,`workflow:result_applied`,`agent:turn_requested`,`agent:tool_executed`,`agent:turn_succeeded`,`agent:turn_failed`,`agent:turn_cancelled`,`agent:result_applied`,`mcp:tool_requested`,`mcp:tool_executed`,`mcp:result_applied`]),NR=Object.freeze({"workflow:run_requested":[`surface`,`run_id`,`node_count_bucket`],"workflow:run_succeeded":[`run_id`,`duration_bucket`],"workflow:run_failed":[`run_id`,`duration_bucket`,`failure_code`],"workflow:run_cancelled":[`run_id`,`duration_bucket`,`failure_code`],"workflow:result_applied":[`run_id`],"agent:turn_requested":[`surface`,`turn_id`],"agent:tool_executed":[`turn_id`,`tool_category`,`outcome`,`duration_bucket`],"agent:turn_succeeded":[`turn_id`,`duration_bucket`],"agent:turn_failed":[`turn_id`,`duration_bucket`,`failure_code`],"agent:turn_cancelled":[`turn_id`,`duration_bucket`,`failure_code`],"agent:result_applied":[`turn_id`],"mcp:tool_requested":[`tool_category`,`request_id`],"mcp:tool_executed":[`tool_category`,`outcome`,`duration_bucket`,`request_id`],"mcp:result_applied":[`request_id`]}),PR=Object.freeze({surface:new Set([`studio`,`workflow`]),node_count_bucket:new Set([`0`,`1-3`,`4-10`,`gte11`]),duration_bucket:new Set([`lt1s`,`1-3s`,`3-10s`,`10-30s`,`gte30s`]),tool_category:new Set([...AR,...jR]),outcome:new Set([`succeeded`,`failed`,`uncertain`,`cancelled`])}),FR=Object.freeze({source:new Set([`agent`,`manual`]),outcome:new Set([`ok`,`error`]),surface:new Set([`assets`,`agent`,`mcp`])}),IR=`cozyclay.analyticsOptOut`,LR=`cozyclay.internalQa`,RR=`cozyclay.analyticsActivation`,zR=`cozyclay.useCaseAsked`,BR=Object.freeze({pose:Object.freeze([`pose_edit`]),camera:Object.freeze([`camera_key_record`,`rail_edit`]),object:Object.freeze([`object_insert`,`cutout_insert`,`object_transform`]),shot:Object.freeze([`shot_add`,`shot_edit`]),prompt:Object.freeze([`prompt_block_add`,`prompt_block_edit`])}),VR=Object.freeze(Object.keys(BR).map(e=>`${e}_edit_bucket`)),HR=Object.freeze([`animation`,`film`,`game`,`ad_mv`,`personal`,`other`,`skip`]),UR=Object.freeze([`team`,`solo`,`skip`]),WR=new Set([`storyboard`,`animation`]),GR=Object.freeze([`latest`,`outdated`,`unknown`]),KR=Object.freeze([`https://cozyclay.org`,`https://www.cozyclay.org`]),qR=[`attempt_id`,`export_kind`,`format`,`surface`,`is_retry`,`retry_of`,`objects`],JR=Object.freeze({"install:first_launch":[`heard_from`],"app:session_started":[],"app:session_ended":[`duration_bucket`,`action_count_bucket`,`scenes_touched`,...VR,`session_id`],...fL,"app:error":[`error_kind`,`error_type`,`error_source`,`error_file`,`error_line`,`error_col`],"device:profile":[`gpu_vendor`,`gpu_class`,`webgl`,`cpu_bucket`,`memory_bucket`,`frame_rate_bucket`],"survey:use_case":[`use_case`,`team`],"feature:used":[`name`],"hosted:composer_viewed":[],"hosted:login_started":[],"hosted:ticket_created":[],"hosted:result_opened":[],"hosted:opened_in_studio":[],"scene:created":[`scene_source`,`previs_mode`],"storyboard:panel_created":[`source`],"storyboard:panel_stylized":[`outcome`],"cast:proxy_added":[`surface`],"scene:loaded":[`scene_source`],"project:saved":[`object_count_bucket`,`shot_count_bucket`],"project:opened":[`age_bucket`],"craft:first_action":[`action_kind`],"craft:first_edit":[`edit_kind`,`definition_version`],"export:blocking_frame_succeeded":[`format`],"export:video_succeeded":[`format`],"export:keyframe_pack":[`entries`,`source`],"export:attempt_started":qR,"export:attempt_succeeded":[...qR,`duration_bucket`],"export:attempt_failed":[...qR,`duration_bucket`,`failure_code`,`stage`,`progress`],"export:attempt_cancelled":[...qR,`duration_bucket`,`failure_code`,`stage`,`progress`],"export:saved":[`method`,`reason`],"playground:opened":[],"playground:first_action":[`action_kind`],"playground:first_edit":[`edit_kind`,`definition_version`],"activation:completed":[`activation_path`],sculpt_run:[`outcome`,`rounds`,`final_iou`,`duration_ms`,`had_target`],...NR}),YR=new Set([`pose_edit`,`pose_save`,`camera_fly`,`orbit`,`dolly_rail`,`crane_graph`,`timeline_scrub`,`export_frame`,`export_video`,`export_depth_video`,`export_keyframe_pack`,`export_render_pass`,`export_storyboard`,`auto_color`]),XR=Object.freeze([`x`,`hn`,`reddit`,`github`,`friend`,`other`,`site`,`playground`]),ZR=new Set(XR),QR=new Set([`prompt`,`text`,`url`,`path`,`file`]),$R=Object.freeze([`done`,`cancelled`,`failed`]),ez=10,tz=864e5,nz=Object.freeze({workflow:new Set([`aborted`,`capture_failed`,`generation_failed`,`unknown`]),agent:new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`,`key_refused`,`stale_scene`,`capability_missing`,`busy`,`invalid_request`])}),rz=Object.freeze({error_kind:new Set([`error`,`unhandled_rejection`]),error_type:SI,error_source:new Set([`app`,`extension`,`external`,`unknown`])}),iz=/^[A-Za-z0-9_.-]{1,80}\.(?:m?js|jsx|ts|tsx)$/,az=Object.freeze({gpu_vendor:new Set([`nvidia`,`amd`,`intel`,`apple`,`qualcomm`,`arm`,`software`,`other`,`unknown`]),gpu_class:new Set([`discrete`,`integrated`,`software`,`unknown`]),webgl:new Set([`webgl2`,`webgl1`,`none`]),cpu_bucket:new Set([`1-4`,`5-8`,`9-16`,`gte17`,`unknown`]),memory_bucket:new Set([`lt4`,`4-7`,`gte8`,`unknown`]),frame_rate_bucket:new Set([`lt20`,`20-40`,`40-55`,`gte55`,`unknown`])}),oz=null,sz=!1,cz=!1,lz=!1,uz=null,dz=!1,fz=!1,pz=0,mz=0,hz=0,gz=!1,_z=!1,vz=new Set,yz=new Map(Object.entries(BR).flatMap(([e,t])=>t.map(t=>[t,e]))),bz=1e3,xz=Object.fromEntries(Object.keys(BR).map(e=>[e,0])),Sz=null,Cz=-1/0,wz=10,Tz=new Set,Ez=!1,Dz=!1,Oz=new Set([`app:session_started`,`app:session_ended`,`install:first_launch`,...Object.keys(fL),`app:error`,`device:profile`,`app:render_crash`,`app:gl_lost`]);function kz(){try{return globalThis.localStorage??null}catch{return null}}function Az(e){try{return kz()?.getItem(e)??null}catch{return null}}function jz(e,t){try{kz()?.setItem(e,t)}catch{}}function Mz(e){return typeof e==`string`?e.trim().toLowerCase().replace(/[/.]+$/g,``):``}function Nz(e){return e===void 0?[...KR]:e.split(`,`).map(Mz).filter(Boolean)}function Pz(e,t){let n=Mz(e);return Array.isArray(t)&&t.some(e=>n===Mz(e))}var Fz=e=>typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):typeof e==`string`&&e.length<=32&&!/\s/.test(e);function Iz(e,t){let n=JR[e]??[];if(!t||typeof t!=`object`||Array.isArray(t))return{};let r={},i=pL(e);for(let a of n)if(!(QR.has(a)||!Object.hasOwn(t,a))&&!(e===`feature:used`&&(a!==`name`||!YR.has(t[a])))&&!(e===`install:first_launch`&&(a!==`heard_from`||!ZR.has(t[a])))&&!((e.startsWith(`export:attempt_`)||e===`export:saved`)&&!xI(a,t[a]))){if(i){i(a,t[a])&&(r[a]=t[a]);continue}if(!(e===`export:keyframe_pack`&&(a===`source`&&t[a]!==`workflow`||a===`entries`&&(!Number.isFinite(t[a])||t[a]<0)))&&!((e===`craft:first_edit`||e===`playground:first_edit`)&&(a===`edit_kind`&&!OR.includes(t[a])||a===`definition_version`&&t[a]!==2))){if(e.startsWith(`workflow:`)||e.startsWith(`agent:`)||e.startsWith(`mcp:`)){if(a===`run_id`||a===`turn_id`||a===`request_id`){if(typeof t[a]!=`string`||!/^[a-f0-9]{32}$/.test(t[a]))continue}else if(a===`surface`){if(!PR.surface.has(t[a])||e.startsWith(`workflow:`)&&t[a]!==`workflow`)continue}else if(a===`node_count_bucket`&&!PR.node_count_bucket.has(t[a]))continue;else if(a===`duration_bucket`&&!PR.duration_bucket.has(t[a]))continue;else if(a===`tool_category`){if(!(e.startsWith(`agent:`)?jR:AR).includes(t[a]))continue}else if(a===`outcome`){if(!(e===`mcp:tool_executed`?[`succeeded`,`failed`,`uncertain`,`cancelled`]:[`succeeded`,`failed`,`cancelled`]).includes(t[a]))continue}else if(a===`failure_code`&&!nz[e.startsWith(`agent:`)?`agent`:`workflow`].has(t[a]))continue}if(e===`app:error`){if(a===`error_file`){typeof t[a]==`string`&&iz.test(t[a])&&(r[a]=t[a]);continue}if(a===`error_line`||a===`error_col`){Number.isInteger(t[a])&&t[a]>=0&&t[a]<=1e7&&(r[a]=t[a]);continue}if(!rz[a]?.has(t[a]))continue}if(!(e===`device:profile`&&!az[a]?.has(t[a]))){if(e===`sculpt_run`){let e=t[a];a===`outcome`&&$R.includes(e)||a===`rounds`&&Number.isInteger(e)&&e>=0&&e<=ez?r[a]=e:a===`final_iou`&&typeof e==`number`&&e>=0&&e<=1?r[a]=Math.round(e*100)/100:a===`duration_ms`&&typeof e==`number`&&e>=0&&e<=tz?r[a]=Math.round(e):a===`had_target`&&typeof e==`boolean`&&(r[a]=e);continue}a===`previs_mode`&&!WR.has(t[a])||(e.startsWith(`storyboard:`)||e.startsWith(`cast:`))&&!FR[a]?.has(t[a])||e===`survey:use_case`&&(a===`use_case`&&!HR.includes(t[a])||a===`team`&&!UR.includes(t[a]))||Fz(t[a])&&(r[a]=t[a])}}}return r}Object.freeze([...YR]);function Lz(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return t===0?`0`:t<=3?`1-3`:t<=10?`4-10`:`gte11`}function Rz(e){return!Number.isFinite(e)||e<6e4?`lt1m`:e<3e5?`1-5m`:e<9e5?`5-15m`:e<18e5?`15-30m`:`gte30m`}function zz(e){return!Number.isFinite(e)||e<0||e<36e5?`lt1h`:e<864e5?`1-24h`:e<6048e5?`1-7d`:e<2592e6?`7-30d`:`gte30d`}function Bz(){let e=String(globalThis.navigator?.userAgentData?.platform||globalThis.navigator?.platform||``).toLowerCase();return e.includes(`mac`)?`macos`:e.includes(`win`)?`windows`:e.includes(`linux`)?`linux`:e.includes(`android`)?`android`:e.includes(`iphone`)||e.includes(`ipad`)||e.includes(`ios`)?`ios`:`unknown`}function Vz(e){return!Number.isFinite(e)||e<1e3?`lt1s`:e<3e3?`1-3s`:e<1e4?`3-10s`:e<3e4?`10-30s`:`gte30s`}function Hz(e){return!Number.isFinite(e)||e<=0?`unknown`:e<=4?`1-4`:e<=8?`5-8`:e<=16?`9-16`:`gte17`}function Uz(e){return!Number.isFinite(e)||e<=0?`unknown`:e<4?`lt4`:e<8?`4-7`:`gte8`}function Wz(e){return!Number.isFinite(e)||e<=0?`unknown`:e<20?`lt20`:e<40?`20-40`:e<55?`40-55`:`gte55`}function Gz(e){let t=String(e??``).toLowerCase();return t.trim()?/swiftshader|llvmpipe|softpipe|software|basic render driver/.test(t)?{gpu_vendor:`software`,gpu_class:`software`}:/nvidia|geforce|quadro|\brtx\b|\bgtx\b|tesla/.test(t)?{gpu_vendor:`nvidia`,gpu_class:`discrete`}:/\bamd\b|radeon|\bati\b/.test(t)?{gpu_vendor:`amd`,gpu_class:/radeon\(tm\) graphics|radeon graphics|vega \d+ graphics|\b(?:610|660|680|740|760|780|880|890)m\b/.test(t)?`integrated`:`discrete`}:/intel|iris|uhd graphics|hd graphics/.test(t)?{gpu_vendor:`intel`,gpu_class:/arc(?:\(tm\))? [ab]\d{3}/.test(t)?`discrete`:`integrated`}:/apple|\bm[1-9](?: pro| max| ultra)?\b/.test(t)?{gpu_vendor:`apple`,gpu_class:`integrated`}:/adreno|qualcomm/.test(t)?{gpu_vendor:`qualcomm`,gpu_class:`integrated`}:/\bmali\b|\barm\b|powervr/.test(t)?{gpu_vendor:`arm`,gpu_class:`integrated`}:{gpu_vendor:`other`,gpu_class:`unknown`}:{gpu_vendor:`unknown`,gpu_class:`unknown`}}var Kz=/((?:https?|chrome-extension|moz-extension|safari-extension|safari-web-extension):\/\/[^\s()]+?):(\d+):(\d+)/g;function qz(e,t){if(typeof e!=`string`||!e)return`unknown`;if(/^(?:chrome|moz|safari|safari-web)-extension:/.test(e))return`extension`;try{return t&&new URL(e).origin===t?`app`:`external`}catch{return`unknown`}}function Jz(e){try{let t=new URL(e).pathname.split(`/`).pop()??``;return iz.test(t)?t:null}catch{return null}}function Yz(e){try{if(e===null||typeof e!=`object`&&typeof e!=`function`)return`non_error`;let t=typeof e.name==`string`?e.name:``;return t&&t!==`non_error`&&t!==`other`&&rz.error_type.has(t)?t:typeof DOMException<`u`&&e instanceof DOMException?`DOMException`:e instanceof Error?`other`:`non_error`}catch{return`other`}}function Xz({error:e,filename:t,lineno:n,colno:r,kind:i=`error`}={},a=globalThis.location?.origin??``){let o={error_kind:i===`unhandled_rejection`?`unhandled_rejection`:`error`,error_type:Yz(e),error_source:`unknown`},s=typeof t==`string`&&t?{url:t,line:n,col:r}:null;if(!s||qz(s.url,a)!==`app`){let t=``;try{t=typeof e?.stack==`string`?e.stack.slice(0,4e3):``}catch{t=``}let n=[...t.matchAll(Kz)].map(e=>({url:e[1],line:Number(e[2]),col:Number(e[3])}));s=n.find(e=>qz(e.url,a)===`app`)??s??n[0]??null}if(!s||(o.error_source=qz(s.url,a),o.error_source!==`app`))return o;let c=Jz(s.url);return c&&(o.error_file=c),Number.isInteger(s.line)&&s.line>=0&&(o.error_line=s.line),Number.isInteger(s.col)&&s.col>=0&&(o.error_col=s.col),o}function Zz(e,t=Date.now()){let n=yz.get(e);if(!n)return!1;let r=n===Sz&&t-Cz<bz;return Sz=n,Cz=t,r||(xz[n]+=1),e===`pose_edit`&&vB(`pose_edit`),!r}function Qz(){return Object.fromEntries(Object.entries(xz).map(([e,t])=>[`${e}_edit_bucket`,Lz(t)]))}function $z(e,t=`unknown`){try{if(e?.name===`AbortError`)return`aborted`;if(_I.has(e?.exportFailureCode))return e.exportFailureCode}catch{}return _I.has(t)?t:`unknown`}var eB=[`$current_url`,`$initial_current_url`,`$referrer`,`$initial_referrer`],tB=[`utm_source`,`utm_medium`,`utm_campaign`,`utm_content`,`utm_term`,`gad_source`,`mc_cid`,`gclid`,`gclsrc`,`dclid`,`gbraid`,`wbraid`,`fbclid`,`msclkid`,`twclid`,`li_fat_id`,`igshid`,`ttclid`,`rdt_cid`,`epik`,`qclid`,`sccid`,`irclid`,`_kx`,`ph_keyword`];function nB(e){return typeof e==`string`?e.split(`#`)[0].split(`?`)[0]:e}function rB(e){if(!e||typeof e!=`object`||!e.properties)return e;let t=[e.properties,e.properties.$set,e.properties.$set_once,e.$set,e.$set_once].filter(e=>e&&typeof e==`object`&&!Array.isArray(e));for(let e of t){for(let t of eB)typeof e[t]==`string`&&(e[t]=nB(e[t]));for(let t of tB)delete e[t],delete e[`$initial_${t}`];for(let t of Object.keys(e))t.startsWith(`$session_entry_`)&&delete e[t]}return e}function iB(e){return e?.activationTracked!==!0}function aB(){return lz?!0:uB()?.distribution===`npm`?uB()?.telemetryEnabled!==!0:Az(IR)===`1`}function oB(){try{let e=kz();if(!e)return;let t=[];for(let n=0;n<e.length;n+=1){let r=e.key(n);r&&r.startsWith(`ph_`)&&r.endsWith(`_posthog`)&&t.push(r)}for(let n of t)e.removeItem(n)}catch{}}async function sB(e){if(uB()?.distribution!==`npm`)return{ok:!0,enabled:e};try{let t=await fetch(`/__cozyclay/telemetry`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:e})});if(!t.ok)return{ok:!1,enabled:!e};let n=await t.json();return globalThis.__COZYCLAY_RUNTIME__=n,{ok:!0,enabled:n.telemetryEnabled===!0}}catch{return{ok:!1,enabled:!e}}}async function cB(e){let t=e===!0,n=uB()?.distribution===`npm`;lz=t;let r=await sB(!t);if(lz=!1,!r.ok)return aB();let i=!r.enabled;if(jz(IR,i?`1`:`0`),i&&oB(),n&&!i)return globalThis.location?.reload(),!1;if(!oz&&!i&&await hB(),!oz)return i;try{i?(cz=!1,oz.opt_out_capturing()):(oz.opt_in_capturing(),cz=sz)}catch{cz=!1}return i}function lB(){return{BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,VITE_COZYCLAY_LIVE_PORT:`5184`}}function uB(){let e=globalThis.__COZYCLAY_RUNTIME__;return!e||typeof e!=`object`||Array.isArray(e)?null:e}function dB(e){try{let t=new URL(e);return t.protocol===`http:`&&[`127.0.0.1`,`localhost`].includes(t.hostname)}catch{return!1}}function fB({env:e=lB(),origin:t=globalThis.location?.origin??``,runtime:n=uB()}={}){return e.PROD?n?.distribution===`npm`?n.telemetryEnabled===!0?dB(t)?typeof n.apiKey!=`string`||n.apiKey.length===0?{kind:`disabled`,reason:`no key`}:typeof n.installationId!=`string`||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n.installationId)?{kind:`disabled`,reason:`invalid anonymous identity`}:{kind:`enabled`,distribution:`npm`,apiKey:n.apiKey,apiHost:n.apiHost||`https://t.cozyclay.org`,appVersion:n.appVersion||null,installationId:n.installationId,firstLaunch:n.firstLaunch===!0,firstLaunchHeardFrom:ZR.has(n.firstLaunchHeardFrom)?n.firstLaunchHeardFrom:null,installKind:[`npx`,`global`,`clone`].includes(n.installKind)?n.installKind:`npx`,originKind:`local`,internalQa:n.internalQa===!0,updateStatus:GR.includes(n.updateStatus)?n.updateStatus:`unknown`}:{kind:`disabled`,reason:`unapproved origin`}:{kind:`disabled`,reason:`opted out`}:e.VITE_POSTHOG_KEY?Pz(t,Nz(e.VITE_POSTHOG_ALLOWED_ORIGINS))?{kind:`enabled`,distribution:`hosted`,apiKey:e.VITE_POSTHOG_KEY,apiHost:e.VITE_POSTHOG_HOST||`https://us.i.posthog.com`,appVersion:e.VITE_APP_VERSION||null,installationId:null,firstLaunch:!1,firstLaunchHeardFrom:null,installKind:null,originKind:`hosted`,internalQa:Az(LR)===`1`,updateStatus:null}:{kind:`disabled`,reason:`unapproved origin`}:{kind:`disabled`,reason:`no key`}:{kind:`disabled`,reason:`not production`}}function pB(e){return{distribution:e.distribution,...e.appVersion?{app_version:e.appVersion}:{},origin_kind:e.originKind,os:Bz(),...e.installKind?{install_kind:e.installKind}:{},...e.updateStatus?{update_status:e.updateStatus}:{},internal_qa:e.internalQa}}function mB(e){let t=fB({env:e});return t.kind===`disabled`?t.reason:aB()?`opted out`:null}async function hB(){if(sz||uz)return uz;if(uB()?.distribution!==`npm`){let e=new URLSearchParams(globalThis.location?.search??``).getAll(`internal_qa`);e.length===1&&(e[0]===`1`||e[0]===`0`)&&jz(LR,e[0])}let e=lB(),t=mB(e);if(t){fz||=(console.info(`[analytics] disabled: `+t),!0);return}uz=(async()=>{try{let t=await TF(()=>import(`./module-MzlRiBjI.js`),[]);if(aB())return;let n=fB({env:e});if(n.kind===`disabled`)return;oz=t.default??t,oz.init(n.apiKey,{api_host:n.apiHost,defaults:`2025-05-24`,autocapture:!1,capture_pageview:!1,capture_pageleave:!1,person_profiles:`never`,persistence:n.distribution===`npm`?`memory`:`localStorage`,respect_dnt:!0,disable_session_recording:!0,capture_dead_clicks:!1,capture_performance:!1,disable_capture_url_hashes:!0,save_campaign_params:!1,save_referrer:!1,mask_personal_data_properties:!0,request_batching:!1,advanced_disable_feature_flags:!0,disable_external_dependency_loading:!0,disable_surveys:!0,ui_host:`https://us.posthog.com`,bootstrap:n.installationId?{distinctID:n.installationId,isIdentifiedID:!1}:void 0,before_send:rB}),sz=!0,cz=!0;let r=pB(n);if(oz.register(r),globalThis.__cozyclayAnalytics={instance:oz},oz.capture(`$pageview`),pz=Date.now(),kB(n,r),SB(),GI(),OB(),n.distribution===`npm`&&(gB(`app:session_started`),n.firstLaunch)){let e=n.firstLaunchHeardFrom;gB(`install:first_launch`,e?{heard_from:e}:{})}}catch{console.info(`[analytics] initialization failed`)}})(),await uz}function gB(e,t={}){if(!(!sz||!cz||!oz||!Object.hasOwn(JR,e)))try{if(aB())return;let n=Iz(e,t);Oz.has(e)||(mz+=1,(e===`scene:created`||e===`scene:loaded`)&&(hz+=1)),oz.capture(e,n)}catch{}}function _B(e,{hadTarget:t=!1}={}){return $R.includes(e?.stage)?{outcome:e.stage,rounds:e.round,...Number.isFinite(e.iou)?{final_iou:Math.round(e.iou*100)/100}:{},duration_ms:Math.round(e.elapsedMs),had_target:!!t}:null}function vB(e){return!sz||!cz||!oz||!YR.has(e)||vz.has(e)?!1:(vz.add(e),gB(`feature:used`,{name:e}),!0)}function yB(){try{return sz&&cz&&!!oz&&!aB()}catch{return!1}}function bB(){return yB()&&Az(zR)!==`1`}function xB(e,t){jz(zR,`1`),gB(`survey:use_case`,{use_case:HR.includes(e)?e:`skip`,team:UR.includes(t)?t:`skip`})}function SB(){if(Ez||typeof window>`u`||typeof window.addEventListener!=`function`)return;Ez=!0;let e=e=>{try{let t=Xz(e);VI(`errors`);let n=[t.error_kind,t.error_type,t.error_source,t.error_file,t.error_line,t.error_col].join(`|`);if(Tz.has(n)||Tz.size>=wz)return;Tz.add(n),gB(`app:error`,t)}catch{}};window.addEventListener(`error`,t=>{try{if(typeof t?.message==`string`&&t.message.startsWith(`ResizeObserver loop`)||!t?.error&&!t?.filename)return;e({error:t?.error,filename:t?.filename,lineno:t?.lineno,colno:t?.colno,kind:`error`})}catch{}}),window.addEventListener(`unhandledrejection`,t=>{e({error:t?.reason,kind:`unhandled_rejection`})})}function CB(){try{let e=globalThis.document?.createElement?.(`canvas`);if(!e?.getContext)return{webgl:`none`,renderer:``};let t=e.getContext(`webgl2`),n=t?`webgl2`:`none`;if(t||(t=e.getContext(`webgl`),t&&(n=`webgl1`)),!t)return{webgl:n,renderer:``};let r=``;try{let e=t.getExtension(`WEBGL_debug_renderer_info`);r=String(t.getParameter(e?e.UNMASKED_RENDERER_WEBGL:t.RENDERER)??``)}catch{r=``}try{t.getExtension(`WEBGL_lose_context`)?.loseContext()}catch{}return{webgl:n,renderer:r}}catch{return{webgl:`none`,renderer:``}}}var wB=8e3,TB=3e3,EB=6e4;function DB(){return new Promise(e=>{let t=globalThis.requestAnimationFrame;if(typeof t!=`function`){e(null);return}let n=()=>globalThis.document?.visibilityState===`hidden`,r=Date.now(),i=()=>{if(Date.now()-r>EB){e(null);return}if(n()){setTimeout(i,2e3);return}let a=0,o=0,s=r=>{if(n()){setTimeout(i,2e3);return}if(o||=r,a+=1,r-o>=TB){e((a-1)*1e3/(r-o));return}t(s)};t(s)};setTimeout(i,wB)})}async function OB(){if(!(Dz||globalThis.document===void 0||typeof globalThis.requestAnimationFrame!=`function`)){Dz=!0;try{let{webgl:e,renderer:t}=CB(),n=Gz(t),r=await DB();gB(`device:profile`,{...n,webgl:e,cpu_bucket:Hz(globalThis.navigator?.hardwareConcurrency),memory_bucket:Uz(globalThis.navigator?.deviceMemory),frame_rate_bucket:Wz(r)})}catch{}}}function kB(e,t){if(_z||typeof window>`u`)return;_z=!0;let n=()=>{if(!(gz||!pz)){gz=!0;try{if(!cz||!oz||aB()||oz.has_opted_out_capturing())return;let n=`${e.apiHost.replace(/\/$/,``)}/e/`,r={...t,distinct_id:oz.get_distinct_id()},i=(t,i)=>{let a=JSON.stringify({api_key:e.apiKey,event:t,properties:{...r,...Iz(t,i)}});typeof globalThis.navigator?.sendBeacon==`function`?globalThis.navigator.sendBeacon(n,new Blob([a],{type:`application/json`})):fetch(n,{method:`POST`,body:a,keepalive:!0,headers:{"content-type":`application/json`}})},a=Rz(Date.now()-pz);i(`app:session_ended`,{session_id:oz.get_session_id?.(),duration_bucket:a,action_count_bucket:Lz(mz),scenes_touched:Math.min(20,hz),...Qz()}),i(`app:friction_summary`,{active_time:a,...KI()})}catch{}}};window.addEventListener(`pagehide`,n,{once:!0}),window.addEventListener(`beforeunload`,n,{once:!0})}function AB(e){if(!(!sz||!cz||dz)){if(!iB({activationTracked:Az(RR)===`1`})){dz=!0;return}dz=!0,jz(RR,`1`),gB(`activation:completed`,{activation_path:e})}}function jB(e){let t=Array.from(e?.files??[]).find(e=>e.type.startsWith(`image/`));if(t)return t;for(let t of Array.from(e?.items??[]))if(t.kind===`file`&&t.type.startsWith(`image/`)){let e=t.getAsFile?.();if(e)return e}return null}async function MB(e){let t=new Uint8Array(await e.arrayBuffer()),n=``;for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode.apply(null,t.subarray(e,e+32768));return`data:${e.type||`image/png`};base64,${btoa(n)}`}function NB(e,t){return{fileName:e.name&&e.name!==`image.png`?e.name:`pasted-${new Date().toISOString().slice(0,19).replace(/[:T]/g,`-`)}.png`,mimeType:e.type||`image/png`,fileUrl:t,image_url:t,localPreview:!0,outputs:[{value:t}]}}function PB(e,t){return jB(t)?!e||typeof e.matches!=`function`||!(e.isContentEditable||e.matches(`[contenteditable=true]`)):!1}var FB=new Set([`mp4`,`m4v`,`mov`,`webm`,`ogv`,`mkv`]),IB=9,LB=3,RB=480,zB=.85;function BB(e){let t=String(e?.type??``).toLowerCase();if(t)return t.startsWith(`video/`);let n=String(e?.name??``).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1];return FB.has(n)}function VB(e,t){return Array.from({length:t},(n,r)=>(r+.5)*e/t)}function HB(e){let t=Math.floor(e/60);return`${t}:${(e-t*60).toFixed(1).padStart(4,`0`)}`}function UB(e,t){return new Promise((n,r)=>{let i=()=>{e.removeEventListener(t,i),e.removeEventListener(`error`,a),n()},a=()=>{e.removeEventListener(t,i),e.removeEventListener(`error`,a),r(Error(`this browser cannot decode that video`))};e.addEventListener(t,i),e.addEventListener(`error`,a)})}async function WB(e,{doc:t=globalThis.document,frames:n=IB}={}){let r=URL.createObjectURL(e),i=t.createElement(`video`);i.muted=!0,i.playsInline=!0,i.preload=`auto`;try{let a=UB(i,`loadeddata`);i.src=r,await a;let{duration:o,videoWidth:s,videoHeight:c}=i;if(!Number.isFinite(o)||o<=0||!s||!c)throw Error(`that video has no usable length or size`);let l=Math.min(RB,s),u=Math.round(l*c/s),d=t.createElement(`canvas`);d.width=l*LB,d.height=u*Math.ceil(n/LB);let f=d.getContext(`2d`);if(!f)throw Error(`this browser cannot draw video frames — no 2D context`);f.fillStyle=`#000`,f.fillRect(0,0,d.width,d.height),f.font=`600 ${Math.max(12,Math.round(u/12))}px system-ui, sans-serif`,f.textBaseline=`top`;for(let[e,t]of VB(o,n).entries()){let n=UB(i,`seeked`);i.currentTime=t,await n;let r=e%LB*l,a=Math.floor(e/LB)*u;f.drawImage(i,r,a,l,u);let o=`${e+1} · ${HB(t)}`,s=f.measureText(o).width+12;f.fillStyle=`rgba(0, 0, 0, 0.6)`,f.fillRect(r+4,a+4,s,Math.round(u/12)+12),f.fillStyle=`#fff`,f.fillText(o,r+4+6,a+4+6)}return{blob:await new Promise((e,t)=>d.toBlob(n=>n?e(n):t(Error(`the contact sheet could not be encoded`)),`image/jpeg`,zB)),name:`${(String(e?.name??``).trim()||`video`).slice(0,70)} (${n} frames over ${o.toFixed(1)}s)`}}finally{i.removeAttribute(`src`),i.load(),URL.revokeObjectURL(r)}}var GB=1600,KB=4194304,qB=.85,JB=Object.freeze([`image/png`,`image/jpeg`,`image/webp`]),YB=`Up to 4 images per message`,XB=`Attach a PNG, JPEG or WebP image, or a video`,ZB=`That image or video could not be attached`,QB=[...JB,`video/*`].join(`,`),$B={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,webp:`image/webp`};function eV(e){let t=String(e?.type??``).toLowerCase();return JB.includes(t)?t:t?null:$B[String(e?.name??``).toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]]??null}function tV(e){return Array.from(e?.types??[]).includes(`Files`)}function nV(e){let t=Array.from(e?.files??[]);if(!t.length){let n=jB(e);n&&t.push(n)}let n=[],r=0;for(let e of t)eV(e)||BB(e)?n.push(e):String(e?.type??``).startsWith(`image/`)&&(r+=1);return{images:n,unsupported:r}}function rV(e){let t=String(e??``).slice(String(e??``).indexOf(`,`)+1);if(!t)return 0;let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return Math.max(0,Math.floor(t.length*3/4)-n)}function iV(e,t,n=GB){let r=Math.max(e,t);if(!Number.isFinite(r)||r<=0)return null;if(r<=n)return{width:Math.round(e),height:Math.round(t),scaled:!1};let i=n/r;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i)),scaled:!0}}function aV(e=[],t=[],n=4){let r=Math.max(0,n-e.length);return{attachments:[...e,...t.slice(0,r)],rejected:Math.max(0,t.length-r)}}var oV=32768,sV=e=>{let t=``;for(let n=0;n<e.length;n+=oV)t+=String.fromCharCode.apply(null,e.subarray(n,n+oV));return btoa(t)};async function cV(e,t){let n=new Uint8Array(await e.arrayBuffer());return`data:${t||e.type||`image/jpeg`};base64,${sV(n)}`}function lV(e,t){if(typeof OffscreenCanvas==`function`)return new OffscreenCanvas(e,t);throw Error(`this browser cannot resize images — OffscreenCanvas is unavailable`)}function uV(e){let t=e.indexOf(`,`),n=e.slice(5,e.indexOf(`;`)),r=atob(e.slice(t+1)),i=new Uint8Array(r.length);for(let e=0;e<r.length;e+=1)i[e]=r.charCodeAt(e);return new Blob([i],{type:n})}async function dV(e,{decode:t=globalThis.createImageBitmap,makeCanvas:n=lV,toBlob:r=uV,maxBytes:i=KB,maxDimension:a=GB,quality:o=qB}={}){if(rV(e)<=i)return e;if(typeof t!=`function`)throw Error(`this browser cannot decode images — createImageBitmap is unavailable`);let s=await t(r(e));try{let e=iV(s.width,s.height,a);if(!e)throw Error(`that image has no usable size`);let t=n(e.width,e.height),r=t.getContext(`2d`);if(!r)throw Error(`this browser cannot resize images — no 2D context`);return r.drawImage(s,0,0,e.width,e.height),await cV(await t.convertToBlob({type:`image/jpeg`,quality:o}),`image/jpeg`)}finally{s?.close?.()}}function fV(e){let t=String(e?.name??``).trim();return!t||t===`image.png`?`pasted-image.png`:t.slice(0,120)}async function pV(e,t={}){if(BB(e)){let t=await WB(e);return{dataUrl:await cV(t.blob,`image/jpeg`),name:t.name}}let{readDataUrl:n=MB,...r}=t,i=eV(e)??`image/png`,a=await n(e);return{dataUrl:await dV(a.startsWith(`data:${i};`)?a:`data:${i};${a.slice(a.indexOf(`;`)+1)}`,r),name:fV(e)}}var mV=new Set([`aborted`,`capture_failed`,`generation_failed`,`unknown`]),hV=new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`]);function gV(){try{if(!globalThis.crypto?.getRandomValues)return null;let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``)}catch{return null}}function _V(e,t,n){try{Promise.resolve(e(t,n)).catch(()=>{})}catch{}}function vV(e){try{return e()}catch{return NaN}}function yV(e,t,n=`unknown`){let r=t===`agent`?hV:mV;try{if(e?.name===`AbortError`)return`aborted`}catch{}return r.has(n)?n:`unknown`}function bV(e,{capture:t=gB,now:n=()=>performance.now(),durationBucket:r=Vz}={}){let i=gV(),a=!1,o=!1,s=vV(n),c=(e,n)=>{i&&_V(t,e,n)};c(`workflow:run_requested`,{surface:`workflow`,...PR.node_count_bucket.has(e.node_count_bucket)?{node_count_bucket:e.node_count_bucket}:{},run_id:i});let l=(e,t,o)=>{if(a||!i)return;a=!0;let l=yV(t,`workflow`,o),u=e===`failed`&&l===`aborted`?`cancelled`:e,d=`lt1s`;try{let e=r(vV(n)-s);PR.duration_bucket.has(e)&&(d=e)}catch{}c(`workflow:run_${u}`,{run_id:i,duration_bucket:d,...u===`succeeded`?{}:{failure_code:l}})};return{runId:i,succeed(){l(`succeeded`)},fail(e,t=`unknown`){l(`failed`,e,t)},apply(){o||!i||(o=!0,c(`workflow:result_applied`,{run_id:i}))}}}var xV=new Set([`aborted`,`auth`,`rate_limited`,`tool_failed`,`upstream`,`unknown`,`key_refused`,`stale_scene`,`capability_missing`,`busy`,`invalid_request`]),SV={unauthorized:`key_refused`,auth:`auth`,AUTH_REQUIRED:`auth`,rate_limit:`rate_limited`,RATE_LIMITED:`rate_limited`,STALE_SCENE:`stale_scene`,STALE_TARGET:`stale_scene`,STALE_ENVIRONMENT:`stale_scene`,CAPABILITY_MISSING:`capability_missing`,LIVE_HUB_UNAVAILABLE:`capability_missing`,busy:`busy`,TARGET_BUSY:`busy`,SCOPE_BUSY:`busy`,TARGET_NOT_READY:`busy`};function CV(e){try{let t=typeof e?.code==`string`?e.code:``,n=e?.status;return Object.hasOwn(SV,t)?SV[t]:t.startsWith(`INVALID_`)?`invalid_request`:n===401||n===403?`auth`:n===429?`rate_limited`:Number.isInteger(n)&&n>=400&&n<500?`invalid_request`:`upstream`}catch{return`upstream`}}async function wV(e){let t;try{let n=await e.clone().json();t=typeof n?.error?.code==`string`?n.error.code:void 0}catch{}try{return CV({code:t,status:e?.status})}catch{return`upstream`}}var TV=new Set([`oauth`,`api_key`,`chatgpt`]),EV=new Set([`first_run`,`failure_card`,`signed_out`,`menu`,`other`]),DV=`cozyclay.agentConnected`,OV=5,kV=10,AV=gB,jV=()=>Date.now(),MV=null,NV=!1,PV=e=>nL.includes(e)?e:`other`,FV=(e,t)=>{try{AV(e,t)}catch{}},IV=()=>{try{return globalThis.localStorage??null}catch{return null}};function LV(e){let t=EV.has(e)?e:`other`;try{t===`signed_out`&&IV()?.getItem(DV)!==`1`&&(t=`first_run`)}catch{}HI(`agent:connect_opened`,OV)&&FV(`agent:connect_opened`,{entry:t})}function RV(e,t){MV&&BV(`abandoned`),MV={provider:PV(e),method:TV.has(t)?t:`api_key`,startedAt:jV(),step:`list`},FV(`agent:connect_started`,{provider:MV.provider,method:MV.method})}function zV(e){MV&&[`list`,`prompt`,`waiting`,`done`].includes(e)&&(MV.step=e)}function BV(e){let t=MV;if(!t)return;MV=null;let n=e===`ok`?`done`:t.step;if(FV(`agent:connect_finished`,{provider:t.provider,method:t.method,outcome:e,step:n,duration:iL(jV()-t.startedAt)}),e===`ok`)try{IV()?.setItem(DV,`1`)}catch{}}function VV(){MV&&MV.method!==`chatgpt`&&BV(`abandoned`)}function HV(e,t){MV?.method===`chatgpt`&&(t?.signedIn===!0?BV(`ok`):e===`signing-in`||t?.pending===!0?zV(`waiting`):(e===`signed-out`||e===`ready`||e===`no-entitlement`)&&BV(`abandoned`))}function UV(e){let t=PV(String(e??``).split(`/`)[0]);HI(`agent:model_changed`,kV)&&FV(`agent:model_changed`,{provider:t,after_failure:NV})}function WV(e){NV=e===`failed`}var GV=new Set([`typed`,`retry_button`,`regenerate`,`chip`,`supervisor`]),KV=1e4,qV=()=>Date.now(),JV=null,YV=null,XV=0,ZV=null,QV=!1,$V=null;typeof globalThis.addEventListener==`function`&&globalThis.addEventListener(`pagehide`,()=>{JV=null,$V=null});function eH(e){return new Set(String(e??``).toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean))}function tH(e,t){if(!e)return`first`;let n=0;for(let r of t)e.has(r)&&(n+=1);let r=e.size+t.size-n,i=r===0?1:n/r;return i>=.9?`same`:i>=.5?`near`:`different`}function nH(e){return e<=20?`1-20`:e<=80?`21-80`:e<=240?`81-240`:`gte241`}function rH(){ZV===null&&(ZV=qV()),QV=!1}function iH(){ZV=null,QV=!1}function aH(){ZV===null&&(ZV=qV()),QV=!0}function oH(e,{via:t=`typed`,model:n=``,attached:r=!1,taskMode:i=!1}={}){try{let a=String(e??``).trim();if(!a)return;let o=t===`typed`&&QV?`chip`:GV.has(t)?t:`typed`,s=String(n??``).split(`/`)[0],c=(o===`typed`||o===`chip`)&&ZV!==null;$V={at:qV(),tokens:eH(a),props:{provider:nL.includes(s)?s:`other`,via:o,prompt_len:nH(a.length),...c?{compose_ms:iL(qV()-ZV)}:{},attached:!!r,task_mode:!!i}}}catch{$V=null}}function sH(e){let t=$V;if($V=null,!t||!e||qV()-t.at>KV)return null;XV+=1;let n={turn_id:e,...t.props,similarity:tH(JV,t.tokens),gap:YV?iL(qV()-YV.at):`first`,prev_outcome:YV?.outcome??`none`,turn_index:RI(XV)};return JV=t.tokens,ZV=null,QV=!1,n}function cH(e){YV={outcome:[`succeeded`,`failed`,`cancelled`].includes(e)?e:`none`,at:qV()}}var lH=e=>typeof e==`string`&&/^[a-f0-9]{32}$/.test(e),uH=(e,t)=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===t.length&&t.every(t=>Object.hasOwn(e,t)),dH=(e,t)=>{try{return e()}catch{return t}},fH=16,pH={set:(e,t)=>{let n=setTimeout(e,t);return n?.unref?.(),n},clear:e=>clearTimeout(e),now:()=>Date.now()},mH=new Map;function hH(e,{clean:t,problems:n,stuck:r}={}){if(typeof e!=`string`||!e)return;let i={clean:!!t,problems:Number.isFinite(n)?n:0},a=mH.get(e);if(a){a.n+=1,a.last=i,a.stuck||=!!r;return}for(mH.set(e,{n:1,first:i,last:i,stuck:!!r});mH.size>fH;)mH.delete(mH.keys().next().value)}function gH(e){let t=mH.get(e);if(mH.delete(e),!t)return{drafts:`0`,qa_trend:`na`,stuck:!1};let n=e=>e.clean?`clean`:`problems`,r=t.n<2?`na`:t.last.problems<t.first.problems?`improved`:t.last.problems>t.first.problems?`worse`:`flat`;return{drafts:RI(t.n),qa_first:n(t.first),qa_last:n(t.last),qa_trend:r,stuck:t.stuck}}var _H=e=>{if(e.ok===!1){let t=/^([A-Z][A-Z0-9_]*):/.exec(typeof e.error==`string`?e.error:``)?.[1];return t&&t!==`ABORTED`?t:null}return e.result?.ok===!1&&typeof e.result.code==`string`?e.result.code:null};function vH(e,t){let n=new Set,r=new Set,i=new Map,a=0,o=0,s=0,c=0,l=!1,u=null;return{note(t){let d=typeof t?.callId==`string`?t.callId:null;if(t?.type===`tool.start`){if(d&&n.has(d))return;d&&n.add(d),a+=1,u===null&&(u=e());return}if(t?.type!==`tool.done`||d&&r.has(d))return;d&&r.add(d),t.ok===!1&&(o+=1),t.ok===!0&&t.result?.authored===!0&&(l=!0),t.autoRebased===!0&&(c+=1);let f=_H(t);if(f){s+=1;let e=rL(f);i.set(e,(i.get(e)??0)+1)}},applied(){l=!0},props(e){let d=`none`,f=0;for(let[e,t]of i)t>f&&(d=e,f=t);let p=[...n].some(e=>!r.has(e));return{tool_calls:RI(a),tool_failed:RI(o),refused:RI(s),refusal_top:d,stale_retry:RI(c),authored:l,...u===null?{}:{first_tool:iL(u-t)},cancel_phase:e===`cancelled`?a===0?`before_tool`:p?`during_tool`:`after_tool`:`na`}}}}function yH({surface:e,capture:t,now:n,correlationId:r=null}){yL();let i=dH(()=>{let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``)},null),a=()=>dH(()=>{let e=n();return Number.isFinite(e)?e:NaN},NaN),o=r??i,s=a(),c=!1,l=!1,u=new Map,d=new Set,f=vH(a,s),p=(e,n)=>{if(i)try{Promise.resolve(t(e,n)).catch(()=>{})}catch{}},m=(t,n)=>{if(c)return;if(c=!0,WV(t),cH(t),t===`cancelled`)for(let[e,t]of u)d.has(e)||p(`agent:tool_executed`,{turn_id:i,tool_category:t.category,outcome:`cancelled`,duration_bucket:Vz(a()-t.startedAt)});u.clear(),p(`agent:turn_${t}`,{turn_id:i,duration_bucket:Vz(a()-s),...t===`succeeded`?{}:{failure_code:n}});let r=dH(()=>({turn_id:i,outcome:t,wall:iL(a()-s),...f.props(t),...gH(o)}),null);r&&p(`agent:turn_summary`,r),i&&e===`studio`&&bL(i,p,pH)};p(`agent:turn_requested`,{surface:e,turn_id:i});let h=sH(i);return h&&p(`agent:prompt_sent`,h),{turnId:i,cancel:()=>m(`cancelled`,`aborted`),fail:e=>m(`failed`,xV.has(e)?e:`upstream`),tool(e){c||dH(()=>f.note(e),null)},frame(e){try{if(!i||c)return;if(e.type===`execution_tool_started`){if(!uH(e,[`type`,`turn_id`,`telemetry_id`,`tool_category`])||e.turn_id!==o||!lH(e.telemetry_id)||!jR.includes(e.tool_category))return;!u.has(e.telemetry_id)&&!d.has(e.telemetry_id)&&u.set(e.telemetry_id,{category:e.tool_category,startedAt:a()});return}let{event:t,props:n}=e;if(n?.turn_id!==o)return;if(t===`agent:tool_executed`){if(!uH(e,[`type`,`event`,`props`,`telemetry_id`])||!lH(e.telemetry_id)||!uH(n,[`turn_id`,`tool_category`,`outcome`,`duration_bucket`])||!jR.includes(n.tool_category)||![`succeeded`,`failed`,`cancelled`].includes(n.outcome)||!PR.duration_bucket.has(n.duration_bucket)||d.has(e.telemetry_id))return;d.add(e.telemetry_id),u.delete(e.telemetry_id),p(t,{turn_id:i,tool_category:n.tool_category,outcome:n.outcome,duration_bucket:n.duration_bucket});return}if(!uH(e,[`type`,`event`,`props`]))return;if(t===`agent:result_applied`){!l&&uH(n,[`turn_id`])&&(l=!0,f.applied(),p(t,{turn_id:i}));return}if(![`agent:turn_succeeded`,`agent:turn_failed`,`agent:turn_cancelled`].includes(t))return;let r=t.slice(11),s=Object.hasOwn(n,`failure_code`);if(!uH(n,[`turn_id`,`duration_bucket`,...s?[`failure_code`]:[]])||!PR.duration_bucket.has(n.duration_bucket)||s&&(r===`succeeded`||!xV.has(n.failure_code)))return;m(r,r===`cancelled`?`aborted`:n.failure_code||`unknown`)}catch{}}}}var bH=0,xH=new Set,SH=()=>{for(let e of[...xH])try{e(bH>0)}catch{}},CH=()=>bH>0;function wH(e){return xH.add(e),()=>{xH.delete(e)}}function TH(e){let t=e?.turn;return typeof t==`function`&&(e.turn=async function(...e){bH+=1,SH();try{return await t.apply(this,e)}finally{--bH,SH()}}),e}var EH=`follow the reference clip's framing and camera motion exactly`,DH=`clay previs, neutral look`,OH=`motion and blocking come from the reference; keep timing`;function kH(e){return!Number.isFinite(e)||e<=0?`normal`:e<35?`wide`:e<=50?`normal`:`long`}function AH(e,t={}){if(!Number.isFinite(e)||e<=0)return`normal`;let n=or(e*Math.PI/180,t.sensorId,t.aspectRatio);return kH(Math.round(n*10)/10)}function jH(e){return Number.isFinite(e.focalMm)&&e.focalMm>0?kH(e.focalMm):AH(e.fovDeg,{sensorId:e.sensorId,aspectRatio:ir(e.aspect)})}function MH(e){return`${Number(e.toFixed(2))}s`}function NH(e){let t=[];return e?.dolly&&t.push(`smooth dolly move`),e?.crane&&t.push(`gentle crane move`),e?.rail&&t.push(`sliding rail move`),t.length>0?t.join(`; `):`locked-off camera, no move`}var PH=[`front`,`front right`,`right`,`back right`,`back`,`back left`,`left`,`front left`];function FH(e){if(!Number.isFinite(e))return``;let t=(e%360+360)%360;return PH[Math.round(t/45)%8]}function IH(e){return Number.isFinite(e)?e>=50?`high`:e<=10?`low`:`level`:``}function LH(e){return Number.isFinite(e)?e>=.8?`strong`:e>=.35?`moderate`:`dim`:`moderate`}function RH(e){return e?`${[IH(e.elevationDeg),FH(e.azimuthDeg)].filter(Boolean).join(` `)||`even`} key light, ${LH(e.intensity)}`:`no key light, ambient fill`}function zH(e,t={}){let n=t.target===`video`?`video`:`image`,r=t.referenceOwnsCamera!==!1,i=Math.max(0,(e.frameRange?.end??0)-(e.frameRange?.start??0)+1)/(e.fps||24),a=typeof e.intent==`string`?e.intent.trim():``,o=[`SHOT: ${e.shotTitle||`untitled shot`}, ${MH(i)}, ${e.aspect||``}`.trimEnd(),`LENS: ${e.focalMm}mm, ${jH(e)} shot`,r?`CAMERA: ${EH}`:`CAMERA: ${NH(e.cameraMove)}`,`LIGHT: ${RH(e.keyLight)}`,`CAST: ${(e.cast||[]).map(e=>e.name).join(`, `)||`none`}`,`LOOK: ${a||DH}`];return n===`video`&&o.push(`MOTION: ${OH}`),o.join(`
|
|
12
|
+
`)}var BH=``;function VH(e){return`${BH}${e}`}async function HH(e,t,n){let r=await e(VH(t),{headers:{"content-type":`application/json`},...n});if(!r.ok){let e=null;try{e=await r.clone().json()}catch{}let n=typeof e?.error==`string`?e.error:e?.error?.message,i=Error(n||`${t} responded ${r.status}`);throw i.status=r.status,e?.error&&typeof e.error==`object`&&Object.assign(i,e.error),e?.preservation&&typeof e.preservation==`object`&&(i.preservation=e.preservation),i}return r.json()}function UH({prompt:e,imageDataUrl:t,referenceDataUrl:n,references:r,composition:i,quality:a=`auto`,size:o}){return{prompt:e,imageDataUrl:t,...n?{referenceDataUrl:n}:{},...Array.isArray(r)&&r.length?{references:r}:{},...i?{composition:i}:{},quality:a,...o?{size:o}:{}}}function WH(e,{fetchImpl:t=globalThis.fetch?.bind(globalThis),signal:n}={}){return HH(t,`/agent/image`,{method:`POST`,body:JSON.stringify(UH(e)),signal:n})}var GH=`Use the first image (a clay blocking frame) as the layout: keep its composition and camera angle, and keep the pose but make it look natural. Render it as:`;function KH({meta:e,caption:t,imageDataUrl:n}){let r=typeof t==`string`?t.trim():``;return{prompt:`${GH}\n${zH(e,{target:`image`})}${r?`\n${r}`:``}`,imageDataUrl:n,quality:`auto`}}function qH(e){if(e?.code===`entitlement`)return z(`This account cannot generate images.`,`이 계정은 이미지를 생성할 수 없어요.`);if(e?.status===401||e?.code===`auth`)return z(`Sign in with ChatGPT in the Agent panel first.`,`먼저 Agent 패널에서 ChatGPT로 로그인하세요.`);let t=e?.message||z(`unknown error`,`알 수 없는 오류`);return z(`Stylize failed — ${t}`,`스타일화 실패 — ${t}`,`风格化失败 — ${t}`)}function JH(e,t){let n=typeof e==`string`?/^data:image\/png;base64,(.*)$/s.exec(e):null;if(!n)throw Error(z(`The image route did not return a PNG.`,`이미지 경로가 PNG를 돌려주지 않았어요.`));let r=atob(n[1]);if(r.length>t){let e=Math.round(t/1048576);throw Error(z(`The stylized image is larger than ${e} MB, so it was not added.`,`스타일화된 이미지가 ${e} MB보다 커서 추가하지 않았어요.`,`风格化图像超过 ${e} MB,因此未添加。`))}let i=new Uint8Array(r.length);for(let e=0;e<r.length;e+=1)i[e]=r.charCodeAt(e);return i}var YH=300,XH=Object.freeze([]),ZH=new Map,QH=new Set,$H=new Set,eU=XH;function tU(){eU=Object.freeze([...ZH].flatMap(([e,t])=>t.map(t=>({...t,key:`${e}/${t.key}`}))));for(let e of[...$H])try{e()}catch{}}function nU(e){if(e?.type===`sculpt.sketch`){let t=typeof e.callId==`string`&&e.callId?e.callId:`#${e.index}`;if(QH.has(t))return;let n=t!==`#${e.index}`&&ZH.delete(`#${e.index}`),r=(Array.isArray(e.groups)?e.groups:[]).filter(e=>e&&typeof e.key==`string`&&Array.isArray(e.parts)&&e.parts.length);if(r.length)ZH.set(t,r);else if(!ZH.delete(t)&&!n)return;tU()}else e?.type===`tool.done`&&typeof e.callId==`string`?(QH.add(e.callId),ZH.delete(e.callId)&&tU()):(e?.type===`done`||e?.type===`error`)&&rU()}function rU(){QH.clear(),ZH.size&&(ZH.clear(),tU())}function iU(e){return $H.add(e),()=>{$H.delete(e)}}var aU=()=>eU;function oU(e){let t=[],n=new Set;for(let r of Array.isArray(e)?e.slice(0,YH):[]){if(!r||typeof r!=`object`||n.has(r.id))continue;let{parent:e,mirror:i,...a}=r,o=no({version:1,parts:[a]});!o.ok||o.recipe.parts[0].op||(n.add(r.id),t.push({...o.recipe.parts[0],...typeof e==`string`&&e?{parent:e}:{},...i===!0?{mirror:!0}:{}}))}return lo({version:1,parts:t})}var sU=140,cU=(e,t=sU)=>{let n=String(e??``).replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n},lU=e=>{let t=String(e).replace(/([a-z])([A-Z])/g,`$1 $2`).split(/[._\s-]+/).filter(Boolean).join(` `).toLowerCase();return t?t[0].toUpperCase()+t.slice(1):`Editor action`},uU=e=>new Map((e?.actionIndex??[]).filter(e=>e?.id&&e.label).map(e=>[e.id,e.label]));function dU(e,t){let n=[...String(e??``).matchAll(/tools\.(\w+)\(\s*\{?\s*(?:action\s*:\s*["'`]([\w.]+)["'`])?/g)].map(([,e,n])=>n?t?.get(n)??lU(n):Ye[e]??lU(e)),r=[...new Set(n)];return r.length>3?`${r.slice(0,3).join(`, `)}…`:r.join(`, `)}function fU(e,t,n){let r=e===`run_action`&&typeof t?.action==`string`?t.action:null,i=r?t.args:t,a=e===`script`?/^\s*\/\/\s*(.+)/.exec(String(t?.code??``))?.[1]??dU(t?.code,n):i?.spec?.label??i?.caption??i?.label??(r?null:i?.visual&&i.visual!==`none`?i.visual.replace(`_`,` `):null);return{...r?{action:r,actionLabel:n?.get(r)??lU(r)}:{},...a?{subject:cU(a,80)}:{}}}function pU(e,t={}){return e.kind===`compose`||e.kind===`tool`?e.actionLabel?e.actionLabel:e.action?lU(e.action):e.name===`script`?z(`Script`,`스크립트`):Object.hasOwn(t,e.name)?t[e.name]:e.label||lU(e.name||`tool`):``}function mU(e,t){let n=[],r=e?.checks?.framing?.derivedSize;return r&&n.push(r),e?.geometry?.axisConsistent===!1&&n.push(z(`cameras cross the line`,`카메라가 축을 넘음`)),e?.verification?.status&&n.push(e.verification.status===`verified`?z(`motion checked`,`모션 확인`):z(`motion unverified`,`모션 미확인`)),e?.visualStatus===`attached`&&n.push(t?.visual===`contact_sheet`?z(`looked at a contact sheet`,`컨택트 시트 확인`):z(`looked at the frame`,`화면 확인`)),e?.stale&&n.push(z(`stale evidence`,`이전 상태 기준`)),n.join(` · `)}function hU(e){if(e.kind!==`tool`)return``;if(e.status===`failed`)return cU(String(e.error??e.failure?.message??z(`Failed`,`실패`)).replace(/^Error:\s*/,``));if(e.status===`cancelled`)return e.result?.status===`not_applied`?z(`not applied`,`적용 안 됨`):z(`result unknown`,`결과 불명`);let t=e.result;if(!t||typeof t!=`object`)return``;if(e.name===`script`){let e=Array.isArray(t.calls)?t.calls:[],n=e.filter(e=>e?.ok===!1),r=z(`${e.length} call${e.length===1?``:`s`}`,`호출 ${e.length}회`,`调用 ${e.length} 次`);return t.ok===!1?cU(`${r} · ${t.error?.message??z(`failed`,`실패`)}${t.rollback?z(` · its edits were rolled back`,` · 편집 되돌림`):``}`):cU(n.length?`${r} · ${z(`${n.length} refused`,`${n.length}회 거부`,`${n.length} 次拒绝`)}: ${n[0].code??n[0].message??``}`:r)}return e.name===`verify_result`?cU(mU(t,e.args)):typeof t.summary==`string`&&t.summary?cU(t.summary.replace(/\.$/,``)):t.status===`started`?z(`started`,`시작됨`):``}function gU(e){let t=e.progress;if(!t)return``;let n=t.label??(t.action?lU(t.action):lU(t.name??`call`));return z(`${n} (call ${t.index})`,`${n} (${t.index}번째 호출)`,`${n}(第 ${t.index} 次调用)`)}function _U(e){let t=String(e??``).split(/\n+/).map(e=>e.replace(/^[#*\s-]+|\*+$/g,``).trim()).filter(Boolean),n=t.at(-1)??``;return cU(n.length<24&&t.length>1?t.at(-2):n)}function vU(e,t,n,r){let i=e.at(-1);return i?.kind===`thinking`?[...e.slice(0,-1),{...i,text:i.text+t,updatedAt:n}]:[...e,{kind:`thinking`,id:r(),text:t,startedAt:n,updatedAt:n}]}var yU=(e,t)=>e.at(-1)?.kind===`thinking`&&!e.at(-1).endedAt?[...e.slice(0,-1),{...e.at(-1),endedAt:t}]:e;function bU(e,t,n,r,i){let a=yU(e,n),o=Number.isInteger(t.index)?t.index:0,s=a.findLastIndex(e=>e.kind===`compose`&&e.index===o),c={name:t.name,...t.action?{action:t.action,actionLabel:i?.get(t.action)??lU(t.action)}:{},...t.subject?{subject:cU(t.subject,80)}:{}};return s!==-1&&a[s].name===t.name?a.map((e,t)=>t===s?{...e,...c}:e):[...a,{kind:`compose`,id:r(),index:o,startedAt:n,...c}]}function xU(e,t){let n=yU(e,t.startedAt),r=n.findIndex(e=>e.kind===`compose`&&e.name===t.name);return r===-1?[...n,t]:n.map((e,n)=>n===r?{...t,subject:t.subject??e.subject}:e)}var SU=(e,t,n)=>[...e.filter(e=>e.kind!==`compose`).map(e=>e.kind===`tool`&&e.status===`running`?{...e,status:`cancelled`}:e),{kind:`turn-end`,id:n(),...t}],CU=new Set([`tool`,`thinking`,`compose`]);function wU(e,{streaming:t=!1}={}){let n=[];for(let t of e)(t.kind===`user`&&!t.steered||!n.length)&&n.push([]),n.at(-1).push(t);let r=[];return n.forEach((e,i)=>{let a=e.findLastIndex(e=>CU.has(e.kind)),o=e.find(e=>e.kind===`turn-end`)??null,s=i===n.length-1,c=null;e.forEach((e,n)=>{if(e.kind!==`turn-end`){if(!(CU.has(e.kind)||e.kind===`assistant`&&n<a&&c)){r.push({type:`item`,item:e});return}c||(c={type:`steps`,id:`steps:${e.id}`,steps:[],end:o,live:s&&t,last:s},r.push(c)),c.steps.push(e.kind===`assistant`?{...e,kind:`narration`}:e)}})}),r}function TU(e,t,n){let r=e.steps.filter(e=>e.kind===`tool`).length,i=r?` · ${z(`${r} step${r===1?``:`s`}`,`${r}단계`,`${r} 步`)}`:``;if(e.live){let r=e.steps[0]?.startedAt;return{tone:`busy`,text:`${z(`Working`,`작업 중`)}${i}${Number.isFinite(r)?` · ${n(t-r)}`:``}`}}let a=e.end,o=a&&Number.isFinite(a.durationMs)?` · ${n(a.durationMs)}`:``;return a?.status===`stopped`?{tone:`warn`,text:`${z(`Stopped`,`중지됨`)}${i}${o}`}:a?.status===`failed`?{tone:`alert`,text:`${z(`Failed`,`실패`)}${i}${o}`}:{tone:`ok`,text:`${z(`Done`,`완료`)}${i}${o}`}}function EU(e,t){let n=new Map([...t?.entityIndex??[],...t?.shots??[]].filter(e=>e?.id&&e.name).map(e=>[e.id,e.name])),r=[...new Set(e.map(e=>n.get(e)).filter(Boolean))],i=e.filter(e=>!n.has(e)).length;if(!r.length&&!i)return z(`Changed the scene`,`장면을 바꿈`);let a=r.slice(0,4).join(`, `),o=Math.max(0,r.length-4)+i;return z(`Changed ${a||`the scene`}${o>0?` and ${o} more`:``}`,`${a||`장면`}${o>0?` 외 ${o}개`:``} 변경`,`修改了 ${a||`场景`}${o>0?` 以及另外 ${o} 项`:``}`)}function DU(e){return e.steps.some(e=>e.result?.authored===!0||(e.result?.calls??[]).some(e=>e?.revision&&e.revision.after!==e.revision.before))?z(`Stopped by you. What already ran stays in the scene; Cmd+Z undoes this turn.`,`직접 중지했어요. 이미 실행된 편집은 장면에 남아 있고, Cmd+Z로 이번 턴을 되돌릴 수 있어요.`):e.steps.some(e=>e.kind===`tool`&&e.status===`cancelled`)?z(`Stopped by you while a step was running; its result is unknown.`,`단계 실행 중에 직접 중지했어요. 그 단계의 결과는 알 수 없어요.`):z(`Stopped by you before anything changed in the scene.`,`장면이 바뀌기 전에 직접 중지했어요.`)}var OU=new Set([`pending`,`active`,`done`]),kU=12,AU=80;function jU(e){if(!Array.isArray(e)||!e.length||e.length>kU)return null;let t=e.map(e=>({text:String(e?.text??``).replace(/\s+/g,` `).trim().slice(0,AU),status:e?.status}));return t.every(e=>e.text&&OU.has(e.status))?t:null}var MU=e=>e?.type===`plan.update`||e?.name===`plan`&&[`tool.compose`,`tool.start`,`tool.progress`].includes(e?.type);function NU(e,t,n){let r=t?.type===`plan.update`?jU(t.steps):null;if(!r)return e;let i=e.findLastIndex(e=>e.kind===`user`&&!e.steered),a=e.findIndex((e,t)=>t>i&&e.kind===`plan`);return a===-1?[...e.slice(0,i+1),{kind:`plan`,id:n(),steps:r},...e.slice(i+1)]:e.map((e,t)=>t===a?{...e,steps:r}:e)}function PU(e,t){let n=t===`done`||t===`stopped`?t:`failed`;return{...e,outcome:n,steps:e.steps.map(e=>e.status===`active`?{...e,status:n===`done`?`done`:`unfinished`}:e)}}var FU=(e,t)=>e.map(e=>e.kind===`plan`&&!e.outcome?PU(e,t):e);function IU(e){let t=[];for(let n of e)(n.kind!==`tool`||n.name!==`plan`)&&((n.kind===`user`||!t.length)&&t.push([]),t.at(-1).push(n));return t.flatMap(e=>{let t=e.filter(e=>e.kind!==`plan`),n=e.findLast(e=>e.kind===`plan`),r=n?jU(n.steps):null;if(!r)return t;let i=t.some(e=>e.kind===`failure`)?`failed`:t.at(-1)?.kind===`assistant`?`done`:`stopped`,a=+(t[0]?.kind===`user`);return[...t.slice(0,a),PU({...n,steps:r},i),...t.slice(a)]})}var LU=`cozyclay.workflow.agentPanel.width`,RU=1100,zU=`cozyclay.agent.session.studio`,BU=[`signed-out`,`signing-in`,`no-entitlement`,`ready`,`streaming`,`rate-limited`,`error`];function VU(e=globalThis.crypto){let t=e?.randomUUID?.();if(typeof t==`string`)return t;let n=new Uint8Array(16);e.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let r=[...n].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}var HU={queued:`Queued`,generating:`Generating`,preparing:`Preparing`,verifying:`Verifying`,repairing:`Repairing`,committing:`Installing`,reconciling:`Reconciling`,installed:`Installed`,review_required:`Needs review`,failed:`Failed`,cancelled:`Stopped`,stale_target:`Target changed`,stale_environment:`Scene changed`},UU=new Set([`installed`,`failed`,`cancelled`,`stale_target`,`stale_environment`]),WU=e=>UU.has(e),GU=e=>e===`installed`?`ok`:e===`review_required`?`warn`:WU(e)?`alert`:`busy`,KU=e=>Number.isFinite(e)?`${Math.round(e*100)}%`:``;function qU(e,t=null){if(e?.status===`installed`){let{installed:t,verification:n}=e,r=n.status===`verified`?`verified over ${n.evaluatedFrames} frames`:`installed unverified`;return`Installed ${t.durationSeconds}s of motion on ${t.characterId} — ${r}`}return e?.status===`undone`?`Undid ${e.undoneReceiptId}`:e?.status===`noop`?`Nothing to change`:e?.status===`transient`?`Changed the view only`:t?EU(e?.affectedIds??[],t):`Applied to ${e?.affectedIds?.join(`, `)||`the scene`}`}function JU(e){let t=Array.isArray(e?.efforts)?e.efforts:[];if(!t.length)return[];let n=e.defaultEffort&&t.includes(e.defaultEffort)?e.defaultEffort:t[0];return[n,...t.filter(e=>e!==n)]}var YU=[`Block a two-shot conversation in this scene`,`Render this frame as a storyboard panel`,`Suggest a camera move for the current shot`],XU=[z(`Block a two-shot`,`투샷 블로킹`),z(`Frame the selected character`,`선택한 캐릭터 구도 잡기`),z(`Light the set warmer`,`세트 조명 더 따뜻하게`)],ZU=`Image generation uses about 3-5x a normal turn`,QU={describe_workflow:`Read canvas`,add_workflow_node:`Add node`,update_workflow_node:`Edit node`,remove_workflow_node:`Remove node`,connect_workflow_nodes:`Connect nodes`,disconnect_workflow_nodes:`Disconnect nodes`,run_workflow:`Run workflow`,set_workflow_node_output:`Set node output`,focus_workflow_node:`Focus node`,add_reference_node:`Add reference image`},$U={inspect_studio:z(`Read the scene`,`장면 읽기`),operate_studio:z(`Selection and view`,`선택과 뷰`),arrange_objects:z(`Arrange objects`,`오브젝트 배치`),arrange_characters:z(`Arrange characters`,`캐릭터 배치`),patch_elements:z(`Edit properties`,`속성 편집`),frame_shot:z(`Frame the shot`,`샷 구도 잡기`),generate_motion:z(`Generate motion`,`모션 생성`),verify_result:z(`Verify the result`,`결과 검증`),undo_edit:z(`Undo an edit`,`편집 되돌리기`),run_action:z(`Run an editor action`,`편집기 동작 실행`)},eW=Object.freeze({workflow:Object.freeze({toolLabels:QU,toolBadge:`Canvas`,suggestions:YU,imageHint:ZU,imageEntitlement:!0,steer:!0,history:!0,persistWidth:!0,emptyTitle:`Direct the scene`,emptyHint:e=>`Ask for blocking, a camera move, or a rendered frame from \u201C${e}\u201D.`,composerPlaceholder:`Ask the agent to block, frame or render…`}),studio:Object.freeze({toolLabels:$U,toolBadge:z(`Scene`,`장면`),suggestions:XU,imageHint:null,imageEntitlement:!1,steer:!1,history:!0,persistWidth:!1,emptyTitle:z(`Direct the scene`,`장면을 연출하세요`),emptyHint:e=>z(`Ask for blocking, a camera move, or a motion take in \u201C${e}\u201D.`,`\u201C${e}\u201D\uC5D0\uC11C \uBE14\uB85C\uD0B9, \uCE74\uBA54\uB77C \uC6C0\uC9C1\uC784, \uBAA8\uC158 \uD14C\uC774\uD06C\uB97C \uC694\uCCAD\uD558\uC138\uC694.`,`在“${e}”中请求摆位、摄影机运动或动作片段。`),composerPlaceholder:z(`Ask the agent to block, frame or animate…`,`블로킹·구도·모션을 요청하세요…`)})});function tW(e){return Object.hasOwn(eW,e)?eW[e]:eW.workflow}function nW(e){let t=Number(e);return Number.isFinite(t)?Math.min(560,Math.max(300,Math.round(t))):360}function rW(e=globalThis.localStorage){try{let t=e?.getItem(LU);return t==null||t===``?360:nW(t)}catch{return 360}}function iW(e,t=globalThis.localStorage){try{t?.setItem(LU,String(nW(e)))}catch{}}var aW=`cozyclay.agent.model`;function oW(e=globalThis.localStorage){try{let t=e?.getItem(aW);return typeof t==`string`&&t?t:null}catch{return null}}function sW(e,t=globalThis.localStorage){try{typeof e==`string`&&e&&t?.setItem(aW,e)}catch{}}function cW(e,t=oW()){let n=Array.isArray(e)?e:[];return n.some(e=>e?.id===t)?t:n[0]?.id??``}function lW(e,t){if(!e.length)return!0;let n=e.find(e=>e.models?.some(e=>e.key===t));return!n||n.signedIn}function uW(e,t,n){return n&&t.some(e=>e.id===n)&&lW(e,n)?n:cW(t.filter(t=>lW(e,t.id)))}function dW(e,t){let n=e&&typeof e==`object`&&typeof t==`string`?e[t]:null;return n&&[`helper`,`vision`,`advisor`].every(e=>typeof n[e]==`string`&&n[e])?n:null}function fW(e){let t=String(e??``);return t.slice(t.indexOf(`/`)+1)}function pW(e,t=Date.now()){if(!e)return null;let n=typeof e==`number`?e:Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.max(0,n-t),i=Math.round(r/1e3),a=Math.floor(i/3600),o=Math.floor(i%3600/60),s=i%60;return a>0?`${a}h ${String(o).padStart(2,`0`)}m`:o>0?`${o}m ${String(s).padStart(2,`0`)}s`:`${s}s`}var mW={capture_blocking_frame:{verb:`Capture`,target:`blocking frame`},render_from_frame:{verb:`Render`,target:`from frame`},place_image_in_scene:{verb:`Place`,target:`image in scene`}};function hW(e){if(e?.label)return e.label;let t=mW[e?.name];if(t)return`${t.verb} ${t.target}`;let n=String(e?.name||`tool`).split(/[_\-\s]+/).filter(Boolean);if(!n.length)return`Run tool`;let r=n[0][0].toUpperCase()+n[0].slice(1);return n.length>1?`${r} ${n.slice(1).join(` `)}`:r}var gW={STEER_UNSUPPORTED:`This surface cannot steer a running turn.`,NO_ACTIVE_TURN:`That turn already ended — send it as a new message.`},_W=/^(TARGET_NOT_READY|CAPABILITY_MISSING|CONFIRMATION_REQUIRED):/;function vW(e){let t=Array.isArray(e?.issues)?e.issues:[],n=(Array.isArray(e?.fixes)?e.fixes:[]).filter(e=>typeof e?.action==`string`&&e.args&&typeof e.args==`object`),r=new Set(n.map(e=>e.issueIndex)),i=t.filter((e,t)=>(e?.severity===`blocker`||e?.severity===`concern`)&&!r.has(t)),a=e=>`- [${e.severity}] ${e.text}${e.evidence?` (${e.evidence})`:``}`;return n.length?[z(`Supervisor review — apply these fixes exactly, in order, in ONE script call, then verify_result; do not re-derive them:`,`감독 검토 — 아래 수정을 유추 없이 순서대로 script 1회로 실행하고 verify_result로 확인해 주세요:`),...n.map(e=>`- [${e.severity}] ${t[e.issueIndex]?.text??``} -> run_action ${JSON.stringify({action:e.action,args:e.args})}`),...i.length?[z(`Also check:`,`추가 확인:`),...i.map(a)]:[]].join(`
|
|
13
|
+
`):i.length?[z(`Supervisor review — please address:`,`감독 검토 — 다음을 고쳐 주세요:`),...i.map(a)].join(`
|
|
14
|
+
`):null}var yW={auth:`Your session expired. Sign in again to continue.`,entitlement:`This account cannot generate images.`,rate_limit:`You have hit the usage limit for this window.`,upstream:`The model service failed to answer.`,overloaded:`The model service is overloaded right now. Try again in a moment.`},bW=`Ready`,xW={auth:`session expired`,entitlement:`not on this plan`,rate_limit:`usage limit reached`,rate_limited:`usage limit reached`,overloaded:`service overloaded`,no_output:`no response`};function SW(e){if(!e)return`unknown error`;let t=xW[e.code];if(t)return t;let n=String(e.message??``).trim();return n?n.length>64?`${n.slice(0,63)}…`:n:String(e.code||`unknown error`)}function CW(e){let t=Number.isFinite(e)&&e>0?Math.floor(e/1e3):0;return t<60?`${t} s`:`${Math.floor(t/60)} m ${String(t%60).padStart(2,`0`)} s`}var wW=(e,t,n,r=``)=>({phase:e,kind:`live`,tone:`busy`,text:`${t} · ${CW(n)}`,ticking:!0,...r?{detail:r}:{}});function TW(e,{now:t=Date.now(),toolLabel:n=hW}={}){let r=e?.items??[],i=r.find(e=>e.kind===`image`&&e.apply?.status===`applying`);if(i)return wW(`editor`,`Waiting for the editor…`,t-(i.apply.startedAt??t));if(e?.streaming){let i=t-(e.turnStartedAt??t),a=r.findLast(e=>e.kind===`job`&&!WU(e.state));if(a){let e=KU(a.progress);return wW(`job`,`${HU[a.state]||a.state} motion${e?` ${e}`:``}`,i)}let o=r.findLast(e=>e.kind===`tool`&&e.status===`running`);if(o)return wW(`tool`,`Running ${n(o)}…`,i,o.progress?gU(o):o.subject);let s=r.at(-1);return s?.kind===`compose`?wW(`compose`,`Preparing ${n(s)}…`,i,s.subject):s?.kind===`thinking`?wW(`thinking`,`Thinking…`,i,_U(s.text)):s?.kind===`assistant`?wW(`reply`,`Writing the reply…`,i):s?.kind===`user`?wW(`sending`,i<2e3?`Sending…`:`Waiting for the model…`,i):wW(`thinking`,`Thinking…`,i)}let a=e?.lastTurn;return a&&t-a.endedAt<6e3?a.status===`stopped`?{phase:`stopped`,kind:`terminal`,tone:`warn`,text:`Stopped`,ticking:!0}:a.status===`failed`?{phase:`failed`,kind:`terminal`,tone:`alert`,text:`Failed: ${SW(a.failure)}`,ticking:!0}:{phase:`done`,kind:`terminal`,tone:`ok`,text:`Done · ${CW(a.durationMs)}`,ticking:!0}:{phase:`idle`,kind:`idle`,tone:``,text:bW,ticking:!1}}function EW(e){let t=[],n=e.split(`
|
|
15
|
+
`),r=n.pop()??``;for(let e of n){let n=e.trim();if(!n.startsWith(`data:`))continue;let r=n.slice(5).trim();if(r)try{t.push(JSON.parse(r))}catch{}}return{events:t,tail:r}}var DW=(e,t)=>{try{return e()}catch{return t}},OW=new Set([`auth`,`entitlement`,`rate_limit`,`overloaded`,`upstream`]);async function kW(e){let t=Number.isFinite(e?.status)?e.status:null,n=null;try{let t=await e.clone().json();n=typeof t?.error==`string`?{message:t.error}:t?.error&&typeof t.error==`object`?t.error:null}catch{}let r=typeof n?.message==`string`?n.message.trim():``,i=r?t!==null&&r.startsWith(`${t} `)?r:`${t??`Upstream`} — ${r}`:`The turn was refused with HTTP ${t??`error`}.`;return{code:OW.has(n?.code)?n.code:t===429?`rate_limit`:t===401?`auth`:`upstream`,message:i,...t===null?{}:{status:t},...n?.resetAt?{resetAt:n.resetAt}:{}}}var AW=3;function jW(e){let t=/"message"\s*:\s*"([^"]{1,160})"/.exec(String(e||``))?.[1],n=/\b(401|403)\b/.exec(String(e||``))?.[1];return`The model provider refused the credentials${n||t?` (${[n,t].filter(Boolean).join(`: `)})`:``}.`}var MW=e=>!Number.isFinite(e?.status)||[404,502,503].includes(e.status);function NW({fetchImpl:e=globalThis.fetch?.bind(globalThis),surface:t,capture:n=gB,now:r=()=>performance.now()}={}){let i=new Map,a=(t,n)=>HH(e,t,n);return{mock:!1,async status(){return a(`/oauth/status`)},async signIn(){return a(`/oauth/start`,{method:`POST`,body:`{}`})},async signOut(){return a(`/oauth/logout`,{method:`POST`,body:`{}`})},async models(){let e=await a(`/agent/models`),t=Array.isArray(e?.models)?e.models:[],n=Array.isArray(e?.providers)?e.providers.filter(e=>e?.id&&Array.isArray(e.models)):[],r=e?.roles?.byMain;return r&&typeof r==`object`&&!Array.isArray(r)?{providers:n,models:t,roles:{byMain:r}}:{providers:n,models:t}},async steer(e,t){return a(`/agent/turn/${encodeURIComponent(e)}/steer`,{method:`POST`,body:JSON.stringify(t)})},async providers(){let e=await a(`/agent/providers`);return Array.isArray(e?.providers)?e.providers:[]},async setProviderKey(e,t){return a(`/agent/providers/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({key:t})})},async removeProviderKey(e){return a(`/agent/providers/${encodeURIComponent(e)}`,{method:`DELETE`})},async listSessions(){let e=await a(`/agent/sessions?surface=${encodeURIComponent(t||`studio`)}`);return Array.isArray(e?.sessions)?e.sessions:[]},async loadSession(e){return a(`/agent/sessions/${encodeURIComponent(e)}`)},async stop(e){let t=typeof e==`string`||!e?{sessionId:e}:{surface:`studio`,sessionId:e.sessionId,turnId:e.turnId,...e.jobId?{jobId:e.jobId}:{}};return i.get(t.sessionId)?.cancel(),a(`/agent/stop`,{method:`POST`,body:JSON.stringify(t)})},async acceptJob({jobId:e,sessionId:t,turnId:n}){return a(`/agent/jobs/${encodeURIComponent(e)}/accept`,{method:`POST`,body:JSON.stringify({surface:`studio`,sessionId:t,turnId:n,explicitUnverifiedAcceptance:!0})})},async image(t,n){return WH(t,{fetchImpl:e,signal:n})},async video(e,t){return a(`/agent/video`,{method:`POST`,body:JSON.stringify(e),signal:t})},async videoProviders(){return a(`/agent/video/providers`)},async supervisor(t,n){let r=await e(VH(`/agent/turn/${encodeURIComponent(t)}/supervisor`),{headers:{accept:`application/json`},credentials:`same-origin`,signal:n});if(r?.status!==200)return null;let i=await r.json();return i?.type===`supervisor`&&[`reviewed`,`unavailable`].includes(i.verdict)?i:null},async turn(a,o,s){let{sessionId:c,text:l,attachFrame:u,model:d,effort:f,attachments:p,supervisor:m,tasks:h}=a,g=Array.isArray(p)&&p.length?{attachments:p}:{},_=a.surface===`studio`,v=_?a.turnId:null,y=yH({surface:DW(()=>[`studio`,`workflow`].includes(t)?t:/^\/workflow(?:\/|$)/.test(globalThis.location?.pathname||``)?`workflow`:`studio`,`studio`),capture:n,now:r,correlationId:v});a.onTurnId?.(_?v:y.turnId),i.set(c,y);let b=()=>{s.reason===`agent-stop`&&y.cancel()};s?.addEventListener(`abort`,b,{once:!0}),s?.aborted&&b();let x=!1,S,C=0,w=!1,T=e=>{if(e?.type===`execution_telemetry`||e?.type===`execution_tool_started`){y.frame(e);return}if(_&&Number.isFinite(e?.eventSeq)){if(e.eventSeq<=C)return;C=e.eventSeq}e?.type===`error`&&(S=CV(e)),e?.type===`done`&&(w=!0),(e?.type===`tool.start`||e?.type===`tool.done`)&&y.tool(e),o(e)},E=async e=>{let t=e.body.getReader();x=!0;try{let e=new TextDecoder,n=``;for(;;){let{value:r,done:i}=await t.read();if(i)break;n+=e.decode(r,{stream:!0});let a=EW(n);n=a.tail;for(let e of a.events)T(e)}for(let e of EW(`${n}\n`).events)e?.type!==`execution_telemetry`&&e?.type!==`execution_tool_started`&&T(e)}finally{t.releaseLock()}},D=JSON.stringify(_?{surface:`studio`,sessionId:c,turnId:v,text:l,context:a.context,...d?{model:d}:{},...f?{effort:f}:{},...u===void 0?{}:{attachFrame:!!u},...typeof m==`boolean`?{supervisor:m}:{},...g}:{sessionId:c,text:l,attachFrame:u,model:d,...f?{effort:f}:{},...g,...y.turnId?{turn_id:y.turnId}:{}});try{let t=await e(VH(_&&h?`/agent/main`:`/agent/turn`),{method:`POST`,headers:{"content-type":`application/json`,accept:`text/event-stream`,..._&&h?{"x-cozyclay-tasks":`on`}:{}},body:D,signal:s});if(!t.ok||!t.body){y.fail(await wV(t)),o({type:`error`,...await kW(t)}),o({type:`done`});return}let n=null;try{await E(t)}catch(e){n=e}for(let t=0;_&&v&&!w&&!s?.aborted&&t<AW;t+=1){let t;try{t=await e(VH(`/agent/turn/${encodeURIComponent(v)}/events?after=${C}`),{headers:{accept:`text/event-stream`},signal:s})}catch{break}if(!t?.ok||!t.body)break;n=null;try{await E(t)}catch(e){n=e}}if(n)throw n;S&&y.fail(S)}catch(e){throw!s?.aborted&&(!x||S)&&y.fail(S||CV(e)),e}finally{s?.removeEventListener(`abort`,b),i.get(c)===y&&i.delete(c)}}}}function PW(e=globalThis.location?.search||``){let t=new URLSearchParams(e);if(t.get(`agent`)!==`mock`)return null;let n=t.get(`state`);return{state:BU.includes(n)?n:`ready`,speed:Number(t.get(`speed`))||1}}var FW={signedIn:!0,email:`director@cozyclay.org`,plan:`Plus`,accountId:`acct_mock_126`,expiresAt:null},IW=[{delay:40,event:{type:`text.delta`,text:`Framing a wide two-shot from the current blocking. `}},{delay:120,event:{type:`text.delta`,text:`Capturing the viewport first.`}},{delay:120,event:{type:`tool.start`,callId:`call-1`,name:`capture_blocking_frame`,label:`Capture blocking frame`,args:{shot:`current`}}},{delay:260,event:{type:`tool.done`,callId:`call-1`,ok:!0,elapsedMs:268,result:{width:1280,height:720}}},{delay:90,event:{type:`tool.start`,callId:`call-2`,name:`render_from_frame`,label:`Render from frame`,args:{style:`storyboard`,strength:.6}}},{delay:420,event:{type:`tool.done`,callId:`call-2`,ok:!0,elapsedMs:1412,result:{imageId:`img-1`}}},{delay:80,event:{type:`image`,imageId:`img-1`,dataUrl:`data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22512%22%20height%3D%22288%22%20viewBox%3D%220%200%20512%20288%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22g%22%20x1%3D%220%22%20y1%3D%220%22%20x2%3D%221%22%20y2%3D%221%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%232a2f52%22%2F%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%235b3550%22%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Crect%20width%3D%22512%22%20height%3D%22288%22%20fill%3D%22url(%23g)%22%2F%3E%3Ccircle%20cx%3D%22150%22%20cy%3D%22150%22%20r%3D%2252%22%20fill%3D%22%23ef759d%22%20opacity%3D%220.85%22%2F%3E%3Crect%20x%3D%22250%22%20y%3D%22112%22%20width%3D%22180%22%20height%3D%22112%22%20rx%3D%2210%22%20fill%3D%22%238994ff%22%20opacity%3D%220.8%22%2F%3E%3Crect%20y%3D%22240%22%20width%3D%22512%22%20height%3D%2248%22%20fill%3D%22%23101116%22%20opacity%3D%220.55%22%2F%3E%3Ctext%20x%3D%2224%22%20y%3D%22272%22%20font-family%3D%22Inter%2Csans-serif%22%20font-size%3D%2218%22%20fill%3D%22%23edf0fb%22%3Emock%20render%20%C2%B7%20wide%20two-shot%3C%2Ftext%3E%3C%2Fsvg%3E`,width:512,height:288,prompt:`wide two-shot, storyboard ink`}},{delay:60,event:{type:`quota`,plan:`Plus`,primary:{usedPercent:46,windowMinutes:300,resetAt:null},credits:{has:!0}}},{delay:40,event:{type:`done`}}],LW={ok:!0,commandId:`cmd-mock-1`,receiptId:`receipt-mock-1`,host:{workspaceId:`tab-mock`,documentEpoch:`doc-mock`,sceneId:`scene-mock`,sceneEpoch:`scene-open-mock`},status:`applied`,authored:!0,revision:{before:41,after:42},affectedIds:[`char-a`],delta:[{id:`char-a`,after:{position:{x:-.8,y:0,z:.4}}}],checks:{coverage:`affected-targets`},undo:{historyEntryId:`history-mock-1`,entries:1,canUndoDirect:!0},warnings:[]},RW=[{delay:40,event:{type:`text.delta`,text:`Reading the scene before I move anyone. `}},{delay:120,event:{type:`tool.start`,callId:`studio-1`,name:`inspect_studio`,label:`inspect studio`,args:{scope:`selection`}}},{delay:220,event:{type:`tool.done`,callId:`studio-1`,ok:!0,elapsedMs:214,result:{entities:2}}},{delay:90,event:{type:`text.delta`,text:`Blocking the two-shot now.`}},{delay:120,event:{type:`tool.start`,callId:`studio-2`,name:`arrange_characters`,label:`arrange characters`,args:{ops:[{op:`update`,characterId:`char-a`,position:{world:{x:-.8,y:0,z:.4}}}]}}},{delay:320,event:{type:`tool.done`,callId:`studio-2`,ok:!0,elapsedMs:332,result:{ok:!0,receiptId:LW.receiptId}}},{delay:60,event:{type:`receipt`,receipt:LW}},{delay:40,event:{type:`done`}}],zW=[[`openai-codex`,`ChatGPT (OpenAI Codex)`],[`anthropic`,`Anthropic`],[`openai`,`OpenAI`],[`google`,`Google Gemini`],[`openrouter`,`OpenRouter`],[`cliproxy`,`CLIProxyAPI`]],BW=`google`,VW={"openai-codex":[{id:`gpt-6-astra`,label:`gpt-6-astra`,efforts:[`none`,`low`,`medium`,`high`,`xhigh`],defaultEffort:`medium`},{id:`gpt-5.1-codex`,label:`gpt-5.1-codex`,efforts:[`low`,`medium`,`high`],defaultEffort:`medium`}],anthropic:[{id:`claude-sonnet-4-5`,label:`Claude Sonnet 4.5`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}],openai:[{id:`gpt-5.1`,label:`GPT-5.1`,efforts:[`none`,`low`,`medium`,`high`,`xhigh`],defaultEffort:`medium`}],google:[{id:`gemini-3-pro`,label:`Gemini 3 Pro`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}],openrouter:[{id:`deepseek-v3`,label:`DeepSeek V3`,efforts:[`none`],defaultEffort:`none`}],cliproxy:[{id:`claude-sonnet-5`,label:`Claude Sonnet 5`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`medium`}]},HW={id:`gpt-6-live-preview`,label:`gpt-6 live preview`,efforts:[`none`,`low`,`medium`,`high`],defaultEffort:`high`},UW=8,WW=`cozyclay.mock.agent.status-calls`,GW=`cozyclay.mock.agent.model-calls`,KW=e=>{try{globalThis.localStorage?.setItem(e,String(Number(globalThis.localStorage.getItem(e)||0)+1))}catch{}};function qW(e={state:`ready`}){let t=e?.state||`ready`,n=e?.surface===`studio`,r=e?.speed>0?e.speed:1,i=e=>new Promise(t=>setTimeout(t,Math.max(0,e/r))),a=new Set,o=t===`signed-out`?`out`:t===`signing-in`?`pending`:`in`,s=()=>zW.map(([e,t])=>{let n=e===`openai-codex`?o===`in`?`chatgpt`:null:e===BW?`env`:a.has(e)?`file`:null;return{id:e,label:t,authSource:n,signedIn:!!n}}),c=null,l=0;return{mock:!0,state:t,async status(){KW(WW);let e=s().filter(e=>e.id!==`openai-codex`&&e.signedIn).length;return o===`pending`?{signedIn:!1,pending:!0,email:null,plan:null,accountId:null,expiresAt:null,providersConfigured:a.size}:o===`out`?{signedIn:!1,email:null,plan:null,accountId:null,expiresAt:null,providersConfigured:a.size}:t===`no-entitlement`?{...FW,plan:`Free`,entitlements:{image:!1},providersConfigured:e}:{...FW,entitlements:{image:!0},providersConfigured:e}},async signIn(){return o=`in`,{ok:!0,authorizeUrl:`https://auth.example.invalid/mock`}},async signOut(){return o=`out`,{ok:!0}},async models(){KW(GW);let e=s().map(e=>{let t=VW[e.id]??[],n=e.id===`openai-codex`&&o===`in`?[...t,HW]:t;return{...e,models:n.map(t=>({...t,key:`${e.id}/${t.id}`,input:[`text`,`image`]}))}});return{providers:e,models:e.flatMap(e=>e.models.map(e=>({...e,id:e.key})))}},async providers(){return s()},async setProviderKey(e,t){if(e===`openai-codex`)throw Object.assign(Error(`Use ChatGPT sign-in for OpenAI Codex.`),{status:400});if(typeof t!=`string`||t.trim().length<UW)throw Object.assign(Error(`That key was refused: it is too short.`),{status:400});return a.add(e),{ok:!0}},async removeProviderKey(e){return a.delete(e),{ok:!0}},async stop(){return c=null,{ok:!0}},async steer(e,t){if(n)throw Object.assign(Error(`409 — Steering a Studio turn is not supported.`),{status:409,code:`STEER_UNSUPPORTED`});if(!c||e!==c)throw Object.assign(Error(`409 — This turn already ended.`),{status:409,code:`NO_ACTIVE_TURN`});try{globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-steer`,JSON.stringify({turnId:e,text:t?.text??null,attachments:t?.attachments?.length??0}))}catch{}return{ok:!0,queued:!0}},async acceptJob(){return{ok:!0}},async listSessions(){if(!n)return[];let e=[];try{for(let t=0;t<globalThis.localStorage.length;t+=1){let n=globalThis.localStorage.key(t);if(!n?.startsWith(`cozyclay.mock.agent.session.`))continue;let r=JSON.parse(globalThis.localStorage.getItem(n));r?.meta&&e.push(r.meta)}}catch{}return e.sort((e,t)=>Date.parse(t.updatedAt||0)-Date.parse(e.updatedAt||0)).slice(0,50)},async loadSession(e){try{let t=JSON.parse(globalThis.localStorage.getItem(`cozyclay.mock.agent.session.${e}`));if(t?.transcript)return t}catch{}throw Error(`Mock session not found.`)},async applyImage({requestId:e}){return{ok:!0,receiptId:`mock-${e}`}},async turn(e,r,a){let o=`mock-turn-${++l}`;c=o,e?.onTurnId?.(o);try{globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-turn`,JSON.stringify({turnId:o,model:e?.model??null,effort:e?.effort??null,text:e?.text??null}))}catch{}try{n&&e?.sessionId&&globalThis.localStorage?.setItem(`cozyclay.mock.agent.last-turn-session`,e.sessionId)}catch{}let s=[],u=n&&e?.sessionId?`cozyclay.mock.agent.session.${e.sessionId}`:null;if(u){try{s=JSON.parse(globalThis.localStorage.getItem(u))?.transcript||[]}catch{s=[]}s.push({kind:`user`,text:e.text})}let d=t=>{if(u){if(t.type===`text.delta`){let e=s.at(-1);e?.kind===`assistant`?e.text+=t.text:s.push({kind:`assistant`,text:t.text})}else if(t.type===`tool.start`)s.push({kind:`tool`,name:t.name,label:t.label,ok:!0,elapsedMs:null,callId:t.callId});else if(t.type===`tool.done`){let e=[...s].reverse().find(e=>e.kind===`tool`&&e.callId===t.callId);e&&Object.assign(e,{ok:t.ok,elapsedMs:t.elapsedMs})}else t.type===`receipt`&&s.push({kind:`receipt`,receiptId:t.receipt?.receiptId,summary:t.receipt?.status===`applied`?`Applied to the scene`:`Receipt`});try{globalThis.localStorage.setItem(u,JSON.stringify({sessionId:e.sessionId,transcript:s,meta:{sessionId:e.sessionId,surface:`studio`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),sceneName:`Mock scene`,firstText:s.find(e=>e.kind===`user`)?.text||``}}))}catch{}}r(t)};if(t===`rate-limited`){d({type:`text.delta`,text:`Framing a wide two-shot from the current blocking.`}),d({type:`quota`,plan:`Plus`,primary:{usedPercent:100,windowMinutes:300,resetAt:new Date(Date.now()+252e4).toISOString()},credits:{has:!1}}),d({type:`error`,code:`rate_limit`,message:yW.rate_limit,resetAt:new Date(Date.now()+252e4).toISOString()}),d({type:`done`}),c=null;return}if(t===`error`){d({type:`text.delta`,text:n?`Reading the scene first.`:`Capturing the viewport first.`}),d(n?{type:`tool.start`,callId:`call-1`,name:`inspect_studio`,label:`inspect studio`,args:{scope:`selection`}}:{type:`tool.start`,callId:`call-1`,name:`capture_blocking_frame`,label:`Capture blocking frame`,args:{shot:`current`}}),d({type:`tool.done`,callId:`call-1`,ok:!1,elapsedMs:812,error:n?`The scene is not ready`:`Viewport is not ready`}),d({type:`error`,code:`upstream`,message:yW.upstream}),d({type:`done`}),c=null;return}for(let e of n?RW:IW){if(a?.aborted||(await i(e.delay),a?.aborted))break;d(e.event)}c=null,await i(240),a?.aborted&&d({type:`done`})}}}function JW(e={}){let t=e.mockConfig===void 0?PW():e.mockConfig;return TH(t?qW({surface:e.surface,...t}):NW(e))}function YW(e){let t=e?.outcome;return t?.status===`already_applied`?null:t&&t.mutated===!1?{status:`not_applied`,code:t.code??`CANCELLED`,mutated:!1}:{status:`unknown`,code:t?.code??null,mutated:`unknown`}}function XW(e){return new Promise(t=>{let n=r=>{r.detail?.requestId===e.requestId&&(globalThis.removeEventListener(`cozyclay:agent-image-result`,n),t({ok:!!r.detail.ok,error:r.detail.error,receiptId:r.detail.receiptId}))};globalThis.addEventListener?.(`cozyclay:agent-image-result`,n),!(globalThis.dispatchEvent&&!globalThis.dispatchEvent(new CustomEvent(`cozyclay:agent-image`,{cancelable:!0,detail:e})))&&(globalThis.removeEventListener?.(`cozyclay:agent-image-result`,n),t({ok:!1,error:`No editor accepted the image. Open the scene that should receive it.`}))})}function ZW({transport:e,surface:t=`workflow`,buildContext:n=null,requestImageAction:r=null,onAuthLost:i=null,onReceipt:a=null,newId:o=VU,clock:s=()=>Date.now()}={}){let c=t===`studio`,l=new Set,u=new Set,d=new Set,f=null,p=null,m=null,h=new Set,g=new Map,_={sessionId:o(),turnId:null,draft:``,pendingAttachments:[],items:[],streaming:!1,quota:null,rateLimit:null,lastPrompt:``,turnStartedAt:null,lastTurn:null},v=e=>{_={..._,...e};for(let e of[...l])e(_)},y=e=>v({items:e(_.items)}),b=(e,t)=>y(n=>n.map(n=>e(n)?{...n,...t}:n)),x=e=>_.items.find(t=>t.kind===`job`&&t.jobId===e);function S(e){if(!e?.jobId||!Qe.jobStates.includes(e.state))return;let t=typeof e.progress==`number`&&Number.isFinite(e.progress)?Math.min(1,Math.max(0,e.progress)):null;y(n=>{let r=n.find(t=>t.kind===`job`&&t.jobId===e.jobId),i={kind:`job`,id:r?.id??`job:${e.jobId}`,jobId:e.jobId,commandId:e.commandId??r?.commandId??null,state:e.state,phase:typeof e.phase==`string`?e.phase:r?.phase??null,progress:t??r?.progress??null,verification:r?.verification??null,receiptId:r?.receiptId??null,outcome:r?.outcome??null,acceptance:e.state===`review_required`?r?.acceptance??{status:`required`}:r?.acceptance??null};return r?n.map(e=>e===r?i:e):[...n,i]})}function C(e){let t;try{t=Pn(e)}catch(e){y(t=>[...t,{kind:`failure`,id:o(),failure:{code:e?.code||`INVALID_RECEIPT`,message:e?.message||`The host returned an unreadable receipt.`,preserved:{authoredState:`unknown`},recovery:{action:`inspect`}}}]);return}if(t.ok===!1){let e=`failure:${t.commandId}:${t.code}`;if(u.has(e))return;u.add(e),y(n=>[...n.map(e=>e.kind===`job`&&e.commandId===t.commandId&&!WU(e.state)?{...e,state:`failed`,phase:t.phase,acceptance:null}:e),{kind:`failure`,id:e,failure:t}]);return}if(!u.has(t.receiptId)){u.add(t.receiptId),y(e=>[...e.map(e=>e.kind===`job`&&e.jobId===t.jobId?{...e,state:t.status===`installed`?`installed`:e.state,verification:t.verification??null,receiptId:t.receiptId,acceptance:t.explicitUnverifiedAcceptance?{status:`accepted`}:null}:e),{kind:`receipt`,id:`receipt:${t.receiptId}`,receiptId:t.receiptId,receipt:t,summary:qU(t,c?DW(()=>n?.()??null,null):null)}]);try{a?.(t)}catch{}}}function w(t){if(typeof e.supervisor!=`function`)return;let n=new AbortController;h.add(n),Promise.resolve().then(()=>e.supervisor(t,n.signal)).then(e=>{!e||n.signal.aborted||y(n=>[...n,{...e,kind:`supervisor`,id:`supervisor:${t}`}])}).catch(()=>{}).finally(()=>h.delete(n))}let T=()=>{for(let e of h)e.abort();h.clear()};function E(e){if(p&&[`text.delta`,`tool.start`,`tool.done`,`image`,`job.state`,`job.progress`,`receipt`,`error`].includes(e?.type)&&(p.produced=!0),p&&(e?.type===`tool.done`&&(e.ok?e.result?.authored===!0:_W.test(String(e.error??``)))||e?.type===`receipt`&&e.receipt?.authored===!0)&&(p.reviewable=!0),e?.type===`text.delta`){y(t=>{let n=t[t.length-1];return n?.kind===`assistant`?[...t.slice(0,-1),{...n,text:n.text+e.text}]:[...t,{kind:`assistant`,id:o(),text:e.text}]});return}if(MU(e)){y(t=>NU(t,e,o));return}if(e?.type===`tool.start`){y(t=>xU(t,{kind:`tool`,id:e.callId||o(),callId:e.callId,name:e.name,label:e.label,args:e.args,status:`running`,startedAt:s(),...fU(e.name,e.args,g)}));return}if(e?.type===`thinking.delta`){y(t=>vU(t,String(e.text??``),s(),o));return}if(e?.type===`tool.compose`){y(t=>bU(t,e,s(),o,g));return}if(e?.type===`tool.progress`){b(t=>t.kind===`tool`&&t.callId===e.callId&&t.status===`running`,{progress:{index:e.index,name:e.name,label:g.get(e.action),action:e.action,status:e.status,summary:e.summary}});return}if(e?.type===`tool.done`){b(t=>t.kind===`tool`&&t.callId===e.callId,{status:e.ok?`done`:`failed`,elapsedMs:e.elapsedMs,result:e.result,error:e.error});let t=e.result;if(e.ok&&t&&typeof t==`object`&&t.ok===!0&&typeof t.receiptId==`string`&&Array.isArray(t.affectedIds))try{a?.(t)}catch{}return}if(e?.type===`image`){y(t=>[...t,{kind:`image`,id:e.imageId||o(),imageId:e.imageId,dataUrl:e.dataUrl,width:e.width,height:e.height,prompt:e.prompt,placed:!1,apply:null}]);return}if(e?.type===`job.state`||e?.type===`job.progress`){S(e);return}if(e?.type===`receipt`){C(e.receipt);return}if(e?.type===`quota`){v({quota:{plan:e.plan,usedPercent:e.primary?.usedPercent,windowMinutes:e.primary?.windowMinutes,resetAt:e.primary?.resetAt,credits:e.credits}});return}if(e?.type!==`error`)return;let t={code:e.code||`upstream`,message:e.code===`unauthorized`?jW(e.message):e.message||yW[e.code]||`The turn failed.`,...Number.isFinite(e.status)?{status:e.status}:{}};if(p&&(p.failure=t),e.code===`rate_limit`){v({rateLimit:{resetAt:e.resetAt||null,message:e.message||yW.rate_limit}});return}if(e.code===`auth`){i?.();return}y(e=>{let n=e.findLastIndex(e=>e.kind===`user`),r=e.findLastIndex((e,t)=>t>n&&e.kind===`tool`&&e.status===`failed`);return r===-1?[...e,{kind:`failure`,id:o(),failure:{...t,recovery:{action:t.code===`unauthorized`?`fix_key`:`retry`,retryAllowed:!0}}}]:e.map((e,n)=>n===r?{...e,failure:t}:e)})}function D(e,t,n){if(!e||d.has(e))return;d.add(e);let r=!!t?.ok,i={apply:{requestId:e,status:r?`settled`:`failed`,error:r?null:t?.error||`The editor did not apply the image.`,receiptId:t?.receiptId??null}};r&&(i.placed=n===`place`),b(t=>t.kind===`image`&&t.apply?.requestId===e,i)}async function O(e,t){let n=_.items.find(t=>t.kind===`image`&&t.id===e);if(!n||n.apply?.status===`applying`||(t===`place`?n.placed:!n.placed))return;let i=o();b(t=>t.kind===`image`&&t.id===e,{apply:{requestId:i,status:`applying`,error:null,receiptId:null,startedAt:s()}});let a={action:t,requestId:i,imageId:n.imageId,dataUrl:n.dataUrl,width:n.width,height:n.height,prompt:n.prompt};try{D(i,await(r??XW)(a),t)}catch(e){D(i,{ok:!1,error:String(e?.message||e)},t)}}let k=()=>{T(),u.clear(),d.clear(),v({sessionId:o(),turnId:null,items:[],pendingAttachments:[],rateLimit:null,lastPrompt:``,turnStartedAt:null,lastTurn:null})};return{getState:()=>_,subscribe(e){return l.add(e),()=>l.delete(e)},setDraft:e=>v({draft:String(e??``)}),note:e=>{String(e??``).trim()&&v({items:[..._.items,{kind:`assistant`,id:o(),text:String(e)}]})},addAttachments(e){let t=(Array.isArray(e)?e:[]).filter(e=>typeof e?.dataUrl==`string`&&e.dataUrl.startsWith(`data:image/`)).map(e=>({id:o(),dataUrl:e.dataUrl,...e.name?{name:String(e.name).slice(0,120)}:{}})),{attachments:n,rejected:r}=aV(_.pendingAttachments,t,4),i=n.length-_.pendingAttachments.length;return v({pendingAttachments:n}),{added:i,rejected:r}},removeAttachment:e=>v({pendingAttachments:_.pendingAttachments.filter(t=>t.id!==e)}),clearAttachments:()=>v({pendingAttachments:[]}),async send(t,r={}){let i=String(t??``).trim();if(!i||_.streaming)return;let a=o(),l=c?n?.()??null:null;if(g=uU(l),c&&!l){E({type:`error`,code:`upstream`,message:`The editor is not ready to describe the scene yet.`});return}let u=s(),d={produced:!1,failure:null,reviewable:!1};p=d;let h=(Array.isArray(r.attachments)?r.attachments:_.pendingAttachments).slice(0,4).map(({dataUrl:e,name:t})=>({dataUrl:e,...t?{name:t}:{}}));v({lastPrompt:i,rateLimit:null,turnId:a,streaming:!0,draft:``,pendingAttachments:[],turnStartedAt:u,lastTurn:null,items:[..._.items,{kind:`user`,id:o(),text:i,attachFrame:!!r.attachFrame,attachments:h}]}),f=new AbortController;let b=f.signal;try{await e.turn({onTurnId:e=>{m=e},...c?{surface:`studio`,turnId:a,context:l}:{},sessionId:_.sessionId,text:i,...h.length?{attachments:h}:{},attachFrame:!!r.attachFrame,model:r.model,effort:r.effort??void 0,...typeof r.supervisor==`boolean`?{supervisor:r.supervisor}:{},...r.tasks?{tasks:!0}:{}},e=>{nU(e),E(e)},b)}catch(e){b.aborted||E({type:`error`,code:`upstream`,message:String(e?.message||e)})}finally{if(f?.signal===b&&(f=null),p===d){m=null,rU(),!d.produced&&!d.failure&&!b.aborted&&(d.failure={code:`no_output`,message:`The turn ended without a response.`,recovery:{action:`retry`,retryAllowed:!0}},y(e=>[...e,{kind:`failure`,id:o(),failure:d.failure}]));let e=s();p=null;let t={status:b.aborted?`stopped`:d.failure?`failed`:`done`,endedAt:e,durationMs:e-u,failure:d.failure};v({streaming:!1,turnStartedAt:null,lastTurn:t,items:FU(SU(_.items,t,o),t.status)}),c&&d.reviewable&&r.supervisor===!0&&!b.aborted&&w(a)}}},async steer(t,n={}){let r=String(t??``).trim();if(!r)return{ok:!1,code:`EMPTY`,message:``};if(!_.streaming||!m||typeof e.steer!=`function`)return{ok:!1,code:`NO_ACTIVE_TURN`,message:gW.NO_ACTIVE_TURN};let i=(Array.isArray(n.attachments)?n.attachments:_.pendingAttachments).slice(0,4).map(({dataUrl:e,name:t})=>({dataUrl:e,...t?{name:t}:{}}));try{await e.steer(m,{text:r,...i.length?{attachments:i}:{}})}catch(e){let t=typeof e?.code==`string`?e.code:`upstream`;return{ok:!1,code:t,message:gW[t]||String(e?.message||e)}}return v({draft:``,pendingAttachments:[],items:[..._.items,{kind:`user`,id:o(),text:r,steered:!0,attachments:i}]}),{ok:!0,code:null,message:``}},stop(){let t=[..._.items].reverse().find(e=>e.kind===`job`&&!WU(e.state));f?.abort(`agent-stop`),f=null;let n=c?{sessionId:_.sessionId,turnId:_.turnId,...t?{jobId:t.jobId}:{}}:_.sessionId;if(Promise.resolve(e.stop?.(n)).then(e=>{if(!t)return;let n=YW(e);n&&(b(e=>e.kind===`job`&&e.jobId===t.jobId&&!WU(e.state),{state:n.status===`not_applied`?`cancelled`:`reconciling`,phase:null,outcome:n,acceptance:null}),b(e=>e.kind===`tool`&&e.status===`running`,{status:`cancelled`,result:n,elapsedMs:null}))}).catch(()=>{}),!_.streaming){v({streaming:!1});return}let r=s();v({streaming:!1,turnStartedAt:null,lastTurn:{status:`stopped`,endedAt:r,durationMs:r-(_.turnStartedAt??r),failure:null}})},async acceptJob(t){let n=x(t);if(!(!n||n.acceptance?.status!==`required`)){b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`accepting`}});try{let n=await e.acceptJob?.({jobId:t,sessionId:_.sessionId,turnId:_.turnId});n?.receipt?C(n.receipt):b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`required`,error:`The host did not acknowledge the acceptance.`}})}catch(e){b(e=>e.kind===`job`&&e.jobId===t,{acceptance:{status:`required`,error:String(e?.message||e)}})}}},applyImage:e=>O(e,`place`),undoImage:e=>O(e,`remove`),acknowledgeImageAction:({requestId:e,ok:t,error:n,receiptId:r})=>{let i=_.items.find(t=>t.kind===`image`&&t.apply?.requestId===e);D(e,{ok:t,error:n,receiptId:r},i?.placed?`remove`:`place`)},clearRateLimit:()=>v({rateLimit:null}),clearContext:k,newSession:k,restore:(e,t=_.sessionId)=>{T(),u.clear(),d.clear();let n=new Set,r=IU((Array.isArray(e)?e:[]).flatMap(e=>{if(e?.kind===`user`||e?.kind===`assistant`){let t=Array.isArray(e.attachments)?e.attachments.filter(e=>typeof e?.dataUrl==`string`):[];return[{kind:e.kind,id:o(),text:String(e.text??``),...t.length?{attachments:t}:{}}]}return e?.kind===`tool`?[{kind:`tool`,id:o(),callId:o(),name:e.name||`tool`,label:e.label,ok:e.ok,elapsedMs:e.elapsedMs,status:e.ok===!1?`failed`:`done`}]:e?.kind===`receipt`?e.receiptId&&n.has(e.receiptId)?[]:(e.receiptId&&(n.add(e.receiptId),u.add(e.receiptId)),[{kind:`receipt`,id:`receipt:${e.receiptId||o()}`,receiptId:e.receiptId,summary:e.summary||`Receipt`,receipt:{status:`applied`,warnings:[],verification:{status:`verified`}}}]):e?.kind===`failure`?[{kind:`failure`,id:o(),failure:{code:e.code||`upstream`,message:String(e.message||`The turn failed.`),recovery:{action:`retry`,retryAllowed:!0}}}]:e?.kind===`plan`?[{kind:`plan`,id:o(),steps:e.steps}]:[]})),i=[...r].reverse().find(e=>e.kind===`user`)?.text||``;return v({sessionId:t,turnId:null,items:r,rateLimit:null,lastPrompt:i,turnStartedAt:null,lastTurn:null,streaming:!1}),r}}}var QW=`cozyclay.agent.tasks`;function $W(e=globalThis.localStorage){try{return e?.getItem(QW)===`on`}catch{return!1}}function eG(e,t=globalThis.localStorage){try{t?.setItem(QW,e?`on`:`off`)}catch{}}var tG={queued:z(`Queued`,`대기열`),waiting:z(`Waiting for scope`,`영역 대기`),starting:z(`Starting`,`시작 중`),running:z(`Running`,`작업 중`),paused:z(`Paused: Studio lost`,`일시정지: Studio 연결 끊김`),review:z(`Being checked`,`확인 중`),done:z(`Done`,`완료`),failed:z(`Failed`,`실패`),cancelled:z(`Cancelled`,`취소됨`)},nG=new Set([`queued`,`waiting`,`starting`,`running`,`paused`]),rG=()=>({order:[],tasks:{},after:0});function iG(e,t){if(!t||typeof t!=`object`)return e;let n=Number.isFinite(t.eventSeq)?Math.max(e.after,t.eventSeq):e.after,r=(t,r)=>{let i=e.tasks[t];if(!i&&!r.title)return{...e,after:n};let a={notes:[],...i,...r,taskId:t};return{...e,after:n,order:i?e.order:[...e.order,t],tasks:{...e.tasks,[t]:a}}},i=(t,i)=>e.tasks[t]?r(t,{notes:[...e.tasks[t].notes,i].slice(-4)}):{...e,after:n};if(t.type===`task.sceneChanged`)return i(t.taskId,z(`The scene changed during a reload: ${t.keys.join(`, `)}`,`새로고침 중에 장면이 바뀜: ${t.keys.join(`, `)}`,`重新加载期间场景发生变化:${t.keys.join(`, `)}`));if(t.type===`task.userEdit`)return i(t.taskId,z(`You changed ${t.keys.join(`, `)}; the task reads it again`,`${t.keys.join(`, `)}을(를) 직접 바꿈: 작업이 다시 읽어요`,`你修改了 ${t.keys.join(`, `)};任务会重新读取`));if(t.type===`task.undone`)return e.tasks[t.taskId]?r(t.taskId,{undone:!0}):e;if(typeof t.type==`string`&&t.type.startsWith(`task.`)&&t.taskId&&t.status){let{type:e,at:n,eventSeq:i,...a}=t;return r(t.taskId,{...a,...e===`task.started`||e===`task.resumed`?{progress:``}:{}})}return{...e,after:n}}function aG(e,t=[]){return t.reduce((e,t)=>e.tasks[t.taskId]?e:iG(e,{type:`task.seed`,...t}),e)}function oG(e,t=e=>e.name){return e?.type===`tool.start`?t(e):e?.type===`error`?z(`Error: ${e.message??e.code}`,`오류: ${e.message??e.code}`,`错误:${e.message??e.code}`):null}function sG(e){let t=/(?:waits for|held by) task \S+ \((.+)\)/.exec(String(e??``))?.[1];return t?z(`Starts after "${t}"`,`'${t}' 끝나면 시작`,`在“${t}”之后开始`):/scope is held/.test(String(e??``))?z(`Starts when another task frees its part`,`다른 작업이 끝나면 시작`):e??``}function cG(e){return e.status===`running`?e.progress||z(`Working…`,`작업 중…`):e.status===`done`?e.undone?z(`Undone`,`되돌림`):String(e.summary?.reply??``).split(/(?<=[.!?。])\s/)[0]||tG.done:e.reason?sG(e.reason):tG[e.status]??e.status}var lG={timeline:z(`timeline`,`타임라인`),stage:z(`stage`,`무대`),scene:z(`scene`,`장면`),object:z(`object`,`오브젝트`),character:z(`character`,`캐릭터`),shot:z(`shot`,`샷`)},uG=e=>lG[String(e).split(`:`)[0]]??String(e);function dG(e){let t={failed:[],running:[],waiting:[],done:[]};for(let n of e.order){let r=e.tasks[n];t[r.status===`failed`||r.status===`paused`?`failed`:r.status===`running`||r.status===`starting`?`running`:nG.has(r.status)||r.status===`review`?`waiting`:`done`].push(r)}return t}var fG=e=>(e??[]).filter(e=>e.kind===`tool`&&[`dispatch_task`,`dispatch_plan`].includes(e.name)).flatMap(e=>e.name===`dispatch_plan`?e.result?.tasks??[]:[e.result]).map(e=>e?.taskId??e?.duplicateOf).filter(Boolean);function pG(){let e={board:rG(),activity:null,client:null,undo:null,open:null},t=new Set;return{get:()=>e,set:n=>{e={...e,...n};for(let e of t)e()},subscribe:e=>(t.add(e),()=>t.delete(e))}}var mG=pG(),hG=e=>Number.isFinite(e?.cost)&&e.cost>0?`$${e.cost.toFixed(2)}`:``;function gG(e,t){let n=e=>(e??[]).filter(e=>e?.taskId===t).length;return{waiting:n(e?.waiting),running:n(e?.running)}}function _G(e,t){if(t?.type===`task.begun`||t?.type===`task.scope`)return{...e,[t.taskId]:t.scope??[]};if(t?.type===`task.finished`||t?.type===`task.cancelled`){let{[t.taskId]:n,...r}=e;return r}return e}function vG({fetchImpl:e=globalThis.fetch?.bind(globalThis),url:t=VH}={}){let n=async(n,r)=>{let i=await e(t(n),{credentials:`same-origin`,headers:{accept:`application/json`,"content-type":`application/json`},...r}),a=await i.json().catch(()=>({}));if(!i.ok)throw Object.assign(Error(a?.error?.message??`${i.status}`),{status:i.status,code:a?.error?.code});return a};async function r(n,r,i){let a=await e(t(n),{credentials:`same-origin`,headers:{accept:`text/event-stream`},signal:i});if(!a.ok||!a.body)throw Object.assign(Error(`${a.status}`),{status:a.status});let o=a.body.getReader(),s=new TextDecoder,c=``;try{for(;;){let{value:e,done:t}=await o.read();if(t)break;let n=EW(c+s.decode(e,{stream:!0}));c=n.tail;for(let e of n.events)r(e)}}finally{o.releaseLock()}}let i=e=>encodeURIComponent(e);return{board:e=>n(`/agent/main/${i(e)}/board`),events:(e,t,n,a)=>r(`/agent/main/${i(e)}/events?after=${t}`,n,a),frames:(e,t,n)=>r(`/agent/turn/${i(e)}/events?after=0`,t,n),cancel:e=>n(`/agent/task/${i(e)}/cancel`,{method:`POST`,body:`{}`}),steer:(e,t)=>n(`/agent/task/${i(e)}/steer`,{method:`POST`,body:JSON.stringify({text:t})})}}export{rU as $,rr as $i,dD as $n,il as $r,AB as $t,KU as A,ge as Aa,ma as Ai,rM as An,Bl as Ar,pV as At,XW as B,k as Ba,kr as Bi,PD as Bn,xl as Br,Wz as Bt,MW as C,It as Ca,Fa as Ci,gF as Cn,Cu as Cr,UV as Ct,NW as D,jn as Da,Ba as Di,PM as Dn,Ql as Dr,YB as Dt,JW as E,Nn as Ea,Va as Ei,nF as En,pu as Er,ZB as Et,lW as F,Te as Fa,Ii as Fi,AD as Fn,Sl as Fr,NB as Ft,vW as G,g as Ga,jr as Gi,BD as Gn,Qc as Gr,aB as Gt,fW as H,u as Ha,Nr as Hi,RD as Hn,_l as Hr,zz as Ht,uW as I,b as Ia,ji as Ii,UD as In,Al as Ir,MR as It,hU as J,i as Ja,tr as Ji,qD as Jn,Uc as Jr,Iz as Jt,gU as K,v as Ka,gr as Ki,GD as Kn,Zc as Kr,hB as Kt,tW as L,y as La,ui as Li,VD as Ln,vl as Lr,NR as Lt,CW as M,we as Ma,Xi as Mi,zj as Mn,kl as Mr,PB as Mt,WU as N,Se as Na,ea as Ni,QD as Nn,Ol as Nr,MB as Nt,TW as O,kn as Oa,Ha as Oi,IM as On,Jl as Or,XB as Ot,GU as P,Ce as Pa,ta as Pi,MD as Pn,Nl as Pr,jB as Pt,wU as Q,er as Qi,sD as Qn,$c as Qr,gB as Qt,oW as R,ee as Ra,vr as Ri,HD as Rn,Cl as Rr,yB as Rt,zU as S,An as Sa,po as Si,_F as Sn,hu as Sr,zV as St,ZW as T,Pn as Ta,La as Ti,fF as Tn,bu as Tr,QB as Tt,sW as U,h as Ua,Pr as Ui,WD as Un,yl as Ur,Xz as Ut,dW as V,l as Va,Er as Vi,KD as Vn,Ml as Vr,Vz as Vt,iW as W,_ as Wa,Dr as Wi,ED as Wn,Dl as Wr,$z as Wt,DU as X,o as Xa,mr as Xi,DD as Xn,Wc as Xr,cB as Xt,TU as Y,a as Ya,$n as Yi,kD as Yn,Hc as Yr,_B as Yt,_U as Z,n as Za,cr as Zi,OD as Zn,Bc as Zr,bB as Zt,sG as _,Je as _a,mo as _i,IF as _n,rd as _r,HV as _t,hG as a,ir as aa,V as ai,aL as an,b_ as ar,WH as at,yW as b,Dn as ba,no as bi,bF as bn,Bu as br,VV as bt,rG as c,Jn as ca,W as ci,RI as cn,O_ as cr,JH as ct,iG as d,Xn as da,q as di,VI as dn,Rh as dr,hH as dt,Qn as ea,Xc as ei,vB as en,lD as er,nU as et,_G as f,Zn as fa,K as fi,WI as fn,tf as fr,wH as ft,cG as g,Ze as ga,H as gi,MF as gn,md as gr,oH as gt,eG as h,Rt as ha,U as hi,NF as hn,_d as hr,rH as ht,gG as i,or as ia,Y as ii,KL as in,D_ as ir,KH as it,pW as j,ie as ja,Sa as ji,Aj as jn,bl as jr,tV as jt,JU as k,On as ka,Oa as ki,iM as kn,Yl as kr,nV as kt,oG as l,Yn as la,G as li,BI as ln,Dg as lr,zH as lt,aG as m,Ke as ma,X as mi,PF as mn,Zd as mr,iH as mt,tG as n,pr as na,xs as ni,vR as nn,JT as nr,oU as nt,vG as o,ar as oa,J as oi,iL as on,x_ as or,HH as ot,uG as p,qe as pa,Do as pi,JF as pn,Qd as pr,aH as pt,pU as q,c as qa,hr as qi,ND as qn,Gc as qr,xB as qt,dG as r,sr as ra,Fo as ri,fR as rn,kx as rr,iU as rt,fG as s,qn as sa,ho as si,HI as sn,C_ as sr,qH as st,nG as t,_r as ta,Us as ti,DR as tn,LE as tr,aU as tt,$W as u,z as ua,Oo as ui,zI as un,sg as ur,CH as ut,mG as v,Wt as va,Ja as vi,FF as vn,od as vr,BV as vt,nW as w,et as wa,Na as wi,uF as wn,vu as wr,bV as wt,HU as x,tt as xa,ro as xi,xF as xn,Wu as xr,RV as xt,RU as y,$e as ya,lo as yi,TF as yn,Uu as yr,LV as yt,rW as z,A as za,Or as zi,TD as zn,jl as zr,Lz as zt};
|