@threenative/core 0.3.12 → 0.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/capabilities.json +1047 -44
- package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
- package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
- package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
- package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
- package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
- package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
- package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
- package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
- package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
- package/dist/chunk-VP43GIWW.js +18 -0
- package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
- package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
- package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
- package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
- package/dist/hot.d.ts +5 -4
- package/dist/hot.js +5 -8
- package/dist/index.d.ts +871 -1018
- package/dist/index.js +4786 -1631
- package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
- package/dist/playtest.d.ts +5 -4
- package/dist/playtest.js +6 -5
- package/dist/quality-BADStsTn.d.ts +868 -0
- package/dist/react.d.ts +3 -2
- package/dist/render-environment.d.ts +170 -0
- package/dist/render-environment.js +352 -0
- package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
- package/dist/spells/index.js +1 -1
- package/dist/ui-layer.js +3 -2
- package/dist/worker.js +12 -5
- package/dist/world.d.ts +280 -16
- package/dist/world.js +1529 -642
- package/mcp/animation-server.mjs +1 -1
- package/mcp/engine-server.mjs +135 -11
- package/mcp/servers.mjs +4 -4
- package/package.json +10 -6
- package/scripts/ensure-mcp.mjs +6 -1
- package/src/animation-batch.ts +193 -0
- package/src/animation-layers.ts +7 -3
- package/src/animation.ts +209 -29
- package/src/asset-cache.ts +3 -3
- package/src/asset-memo.ts +202 -0
- package/src/assets.ts +436 -131
- package/src/auto-batch.ts +190 -44
- package/src/clustered-batch.ts +146 -3
- package/src/clustered-mesh.ts +548 -20
- package/src/compute-driven.ts +1 -1
- package/src/config.ts +8 -0
- package/src/debug.ts +119 -22
- package/src/dev-global.ts +54 -0
- package/src/displaced-surface.ts +428 -0
- package/src/engine-hooks.ts +37 -0
- package/src/frame-budget.ts +35 -3
- package/src/game-boot-phase.ts +269 -0
- package/src/game-dev-tools.ts +7 -14
- package/src/game-frame-loop.ts +45 -82
- package/src/game-startup.ts +145 -70
- package/src/game-ui.ts +84 -0
- package/src/game.ts +168 -552
- package/src/gamepad-mappings.ts +269 -0
- package/src/generated/console-markers.ts +14 -0
- package/src/geometry-capture.ts +28 -4
- package/src/gpu-readings.ts +98 -0
- package/src/gpu-scene-bvh.ts +149 -36
- package/src/grass-field.ts +628 -0
- package/src/hot.ts +4 -7
- package/src/index.ts +227 -8
- package/src/input.ts +237 -25
- package/src/instanced-batch-lod.ts +3 -8
- package/src/interpolation.ts +171 -40
- package/src/look/ao-admission.ts +4 -3
- package/src/look/auto-exposure.ts +5 -16
- package/src/look/default-tone-mapping.ts +41 -5
- package/src/look/local-exposure.ts +2 -7
- package/src/look/quad-pass.ts +21 -0
- package/src/look/quality.ts +4 -0
- package/src/look/unreal-bloom.ts +4 -13
- package/src/look/world-environment.ts +58 -115
- package/src/merge-parts.ts +20 -24
- package/src/model-lod.ts +97 -14
- package/src/particle-significance.ts +12 -0
- package/src/particles.ts +19 -10
- package/src/platform.ts +23 -4
- package/src/profiling/FrameStages.ts +5 -6
- package/src/profiling/Spans.ts +3 -17
- package/src/profiling/debug-telemetry.ts +2 -6
- package/src/profiling/render-list-validate.ts +6 -15
- package/src/projection-marker.ts +2 -1
- package/src/quiet-markers.ts +3 -10
- package/src/render/cpu-bvh.ts +100 -0
- package/src/render/depth-pyramid.ts +6 -14
- package/src/render/environment/environmentContribution.ts +202 -0
- package/src/render/environment/environmentRadiance.ts +44 -0
- package/src/render/environment/environmentSampleCache.ts +56 -0
- package/src/render/environment/environmentSampling.ts +201 -0
- package/src/render/environment/environmentSnapshot.ts +71 -0
- package/src/render/environment/gate.ts +57 -0
- package/src/render/material-key.ts +21 -1
- package/src/render/mesh-pool.ts +3 -19
- package/src/render/probe-trace.ts +872 -0
- package/src/render/probe-volume.ts +780 -34
- package/src/render/radiance-cache.ts +17 -0
- package/src/render/screen-probe-gather.ts +303 -0
- package/src/render/short-range-ao.ts +274 -0
- package/src/render/virtual-shadow-partial.ts +13 -0
- package/src/render/virtual-shadow.ts +18 -16
- package/src/render/world-impostor-surface.ts +207 -9
- package/src/render/world-impostor.ts +5 -2
- package/src/render-camera-cull.ts +105 -4
- package/src/render-environment.ts +41 -0
- package/src/renderer-config.ts +36 -0
- package/src/renderer-facts.ts +37 -0
- package/src/renderer.ts +78 -32
- package/src/resolution-scaler.ts +3 -2
- package/src/scatter-field.ts +496 -0
- package/src/scene-entry-inspectors.ts +61 -0
- package/src/snow-field.ts +1 -0
- package/src/startup-offscreen-bytes.ts +84 -0
- package/src/state.ts +16 -3
- package/src/static-transform.ts +100 -25
- package/src/streamed-textures.ts +112 -0
- package/src/streaming.ts +68 -4
- package/src/texture-streaming.ts +331 -0
- package/src/tile-ring.ts +294 -0
- package/src/version.ts +1 -1
- package/src/warmup.ts +15 -2
- package/src/worker.ts +12 -2
- package/src/world-bundle-safety.ts +55 -10
- package/src/world-cell-batches.ts +166 -200
- package/src/world-cell-chunks.ts +3 -7
- package/src/world-cell-data.ts +7 -0
- package/src/world-cell-impostors.ts +20 -8
- package/src/world-cell-models.ts +36 -8
- package/src/world-cell-options.ts +2 -14
- package/src/world-cell-placements.ts +194 -90
- package/src/world-cell-prewarm.ts +39 -4
- package/src/world-cell-records.ts +401 -0
- package/src/world-cell-render-bundles.ts +2 -2
- package/src/world-cell-render-gpu-dress.ts +17 -19
- package/src/world-cell-render-main-cull.ts +73 -17
- package/src/world-cell-render-util.ts +18 -5
- package/src/world-cell-render.ts +13 -5
- package/src/world-cell-residency.ts +15 -6
- package/src/world-cell-stale.ts +238 -0
- package/src/world-cells.ts +23 -6
- package/src/world-gpu-flags.ts +18 -50
- package/src/world-gpu-reference.ts +22 -8
- package/src/world-gpu-scene.ts +44 -24
- package/src/world-gpu-shadow.ts +21 -8
- package/src/world-gpu-types.ts +41 -13
- package/src/world-load-limiter.ts +5 -0
- package/src/world-model-sections.ts +80 -0
- package/src/world-river-ribbon.ts +273 -0
- package/src/world-root-frame.ts +39 -0
- package/src/world-shore-field.ts +91 -0
- package/src/world-static-pose.ts +163 -0
- package/src/world-surface-sampler.ts +48 -0
- package/src/world-terrain-splat.ts +10 -18
- package/src/world-tile-budget.ts +4 -11
- package/src/world-tiles.ts +79 -12
- package/src/world-validate.ts +6 -14
- package/src/world-warm.ts +51 -0
- package/src/world-water-bodies.ts +113 -3
- package/src/world.ts +13 -0
package/mcp/animation-server.mjs
CHANGED
|
@@ -252,7 +252,7 @@ void main() {
|
|
|
252
252
|
}`,$e={meshphysical_vert:yk,meshphysical_frag:Sk},ae={common:{diffuse:{value:new ft(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ce},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ce}},envmap:{envMap:{value:null},envMapRotation:{value:new Ce},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ce}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ce}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ce},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ce},normalScale:{value:new mn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ce},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ce}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ce}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ce}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ft(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:[]},probesMin:{value:[]},probesMax:{value:[]},probesResolution:{value:[]}},points:{diffuse:{value:new ft(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0},uvTransform:{value:new Ce}},sprite:{diffuse:{value:new ft(16777215)},opacity:{value:1},center:{value:new mn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ce},alphaMap:{value:null},alphaMapTransform:{value:new Ce},alphaTest:{value:0}}},VE={basic:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.fog])},lambert:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},envMapIntensity:{value:1}}])},phong:{uniforms:Nt([ae.common,ae.specularmap,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},specular:{value:new ft(1118481)},shininess:{value:30},envMapIntensity:{value:1}}])},standard:{uniforms:Nt([ae.common,ae.envmap,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.roughnessmap,ae.metalnessmap,ae.fog,ae.lights,{emissive:{value:new ft(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}])},toon:{uniforms:Nt([ae.common,ae.aomap,ae.lightmap,ae.emissivemap,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.gradientmap,ae.fog,ae.lights,{emissive:{value:new ft(0)}}])},matcap:{uniforms:Nt([ae.common,ae.bumpmap,ae.normalmap,ae.displacementmap,ae.fog,{matcap:{value:null}}])},points:{uniforms:Nt([ae.points,ae.fog])},dashed:{uniforms:Nt([ae.common,ae.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}])},depth:{uniforms:Nt([ae.common,ae.displacementmap])},normal:{uniforms:Nt([ae.common,ae.bumpmap,ae.normalmap,ae.displacementmap,{opacity:{value:1}}])},sprite:{uniforms:Nt([ae.sprite,ae.fog])},background:{uniforms:{uvTransform:{value:new Ce}}},backgroundCube:{uniforms:{backgroundRotation:{value:new Ce}}},distance:{uniforms:Nt([ae.common,ae.displacementmap,{referencePosition:{value:new qe},nearDistance:{value:1},farDistance:{value:1e3}}])},shadow:{uniforms:Nt([ae.lights,ae.fog,{color:{value:new ft(0)},opacity:{value:1}}])}};VE.physical={uniforms:Nt([VE.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ce},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ce},clearcoatNormalScale:{value:new mn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ce},diffuseRoughness:{value:0},diffuseRoughnessMap:{value:null},diffuseRoughnessMapTransform:{value:new Ce},dispersion:{value:0},retroreflectivity:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ce},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ce},sheen:{value:0},sheenColor:{value:new ft(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ce},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ce},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ce},transmissionSamplerSize:{value:new mn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ce},attenuationDistance:{value:0},attenuationColor:{value:new ft(0)},specularColor:{value:new ft(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ce},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ce},anisotropyVector:{value:new mn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ce}}]),vertexShader:$e.meshphysical_vert,fragmentShader:$e.meshphysical_frag};var Ik=new Ce;Ik.set(-1,0,0,0,1,0,0,0,1);var Ck=new Ce;Ck.set(-1,0,0,0,1,0,0,0,1);var Pk=t=>{let e=t.toLowerCase();if(e==="left")return t==="LEFT"?"RIGHT":"Right";if(e==="right")return t==="RIGHT"?"LEFT":"Left"};function jE(t){let e=t.replace(/left|right/giu,i=>Pk(i)??i);if(e!==t)return e;let r=t.replace(/(^|[._\s-])([lrLR])(?=$|[._\s-]|\d)/gu,(i,n,s)=>`${n}${s==="L"?"R":s==="R"?"L":s==="l"?"r":"l"}`);return r===t?void 0:r}function GE(t,e){let r=[],i=[];return t.forEach((n,s)=>{let o=e(n);o!==void 0&&(r.push(s),i.push(o));}),{source:r,times:i}}function HE(t,e){let r=new qe(t[0]??0,t[1]??0,t[2]??0).applyQuaternion(new Pt(e[0]??0,e[1]??0,e[2]??0,e[3]??1).invert());return [r.x,r.y,r.z]}var Nk=()=>new Jt().registerExtensions(Qt);function gn(t,e,r){let{times:i,values:n}=t,s=i.length,o=t.interpolation==="CUBICSPLINE",a=o?e*3:e,c=(_,y)=>n[_*a+(o?e:0)+y]??0,l=i[0]??0,u=i[s-1]??l,d=_=>Array.from({length:e},(y,R)=>c(_,R));if(s===0)return new Array(e).fill(0);if(r<=l)return d(0);if(r>=u)return d(s-1);let f=1;for(;f<s&&(i[f]??0)<r;)f+=1;let p=f-1,g=i[p]??0,m=i[f]??g,S=d(p);if(t.interpolation==="STEP"||m-g<=1e-9)return S;let h=(r-g)/(m-g),v=d(f);return S.map((_,y)=>_+((v[y]??0)-_)*h)}function Ok(t,e,r){let i=e.get(t.getName()),n=[...t.getTranslation()],s=[...t.getRotation()],o=[...t.getScale()],a=i?.get("translation");a!==void 0&&n.splice(0,3,...gn(a,3,r));let c=i?.get("rotation");c!==void 0&&s.splice(0,4,...gn(c,4,r));let l=i?.get("scale");return l!==void 0&&o.splice(0,3,...gn(l,3,r)),{matrix:new nn().compose(new qe(n[0]??0,n[1]??0,n[2]??0),new Pt(s[0]??0,s[1]??0,s[2]??0,s[3]??1),new qe(o[0]??1,o[1]??1,o[2]??1)),translation:n}}function qE(t,e){let r=0;for(let i of e.get(t.getName())?.values()??[])r=Math.max(r,i.times.at(-1)??0);for(let i of t.listChildren())r=Math.max(r,qE(i,e));return r}async function jh(t,e,r=30){return v0(await Nk().read(t),e,r)}function v0(t,e,r=30){let i=t.getRoot().listAnimations().find(p=>p.getName()===e);if(i===void 0){let p=t.getRoot().listAnimations().map(g=>g.getName());throw new Error(`The GLB has no clip '${e}'. It carries: ${p.length===0?"none":p.join(", ")}.`)}let n=new Map;for(let p of i.listChannels()){let g=p.getTargetNode(),m=p.getSampler(),S=p.getTargetPath();if(g===null||m===null||S===null)continue;let h=m.getInput()?.getArray(),v=m.getOutput()?.getArray();if(h==null||v===null||v===void 0)continue;let _=n.get(g.getName())??new Map;_.set(S,{interpolation:m.getInterpolation(),times:h,values:v}),n.set(g.getName(),_);}let s=t.getRoot().listScenes().flatMap(p=>p.listChildren()),o=s.reduce((p,g)=>Math.max(p,qE(g,n)),0),a=t.getRoot().listSkins().flatMap(p=>p.listJoints()).map(p=>p.getName()),c=new Set(a.length>0?a:t.getRoot().listNodes().map(p=>p.getName()).filter(p=>p.length>0)),l=[...c],u={},d=Math.max(1,Math.round(o*r)),f=[];for(let p=0;p<=d;p+=1){let g=Math.min(o,p/r),m={},S={},h={},v=(_,y,R)=>{let T=y.clone().multiply(Ok(_,n,g).matrix),b=_.getName();if(c.has(b)){let E=new qe().setFromMatrixPosition(T),M=new Pt().setFromRotationMatrix(T),N=new Pt().setFromRotationMatrix(y);m[b]=[E.x,E.y,E.z],S[b]=[M.x,M.y,M.z,M.w],h[b]=[N.x,N.y,N.z,N.w],R!==void 0&&c.has(R)&&(u[b]=R);}for(let E of _.listChildren())v(E,T,b);};for(let _ of s)v(_,new nn);f.push({parents:h,positions:m,rotations:S,time:g});}return {bones:l,duration:o,fps:r,frames:f,parentsOf:u}}var zk=()=>new Jt().registerExtensions(Qt),Gh=t=>t==="rotation"?4:3;function xi(t){let e=t.getSampler(),r=e?.getInput()?.getArray(),i=e?.getOutput()?.getArray();if(!(e===null||r===null||r===void 0||i===null||i===void 0))return {interpolation:e.getInterpolation(),times:r,values:i}}function Fa(t,e,r,i,n){let s=e.getSampler();if(s===null)return;let o=t.getRoot().listBuffers()[0]??t.createBuffer(),a=t.createAccessor(`${e.getTargetNode()?.getName()}.time`).setType("SCALAR").setArray(new Float32Array(r)).setBuffer(o),c=t.createAccessor(`${e.getTargetNode()?.getName()}.${e.getTargetPath()}`).setType(n===4?"VEC4":"VEC3").setArray(new Float32Array(i)).setBuffer(o);s.setInput(a).setOutput(c).setInterpolation("LINEAR");}function WE(t,e,r,i){for(let n of e.listChannels()){let s=xi(n);if(s===void 0)continue;let o=n.getTargetPath()??"translation",a=Gh(o),c=s.interpolation==="CUBICSPLINE",l=c?a*3:a,{source:u,times:d}=GE([...s.times],r);if(d.length===0)throw new Error(`'${e.getName()}' keeps no keyframes in that window; the edit would leave an empty clip.`);let f=[];for(let p of u)for(let g=0;g<l;g+=1)f.push(s.values[p*l+g]??0);if(i!==void 0){let p=gn(s,a,0),g=i,m=d.findIndex(v=>v>g),S=m===-1?d.length:m;d.splice(S,0,g);let h=c?Array.from({length:3*a},(v,_)=>_>=a&&_<a*2?p[_-a]??0:0):p;f.splice(S*l,0,...h);}Fa(t,n,d,f,a),c?n.getSampler()?.setInterpolation("CUBICSPLINE"):s.interpolation==="STEP"&&n.getSampler()?.setInterpolation("STEP");}}function $k(t){let e=0;for(let r of t.listChannels())e=Math.max(e,xi(r)?.times.at(-1)??0);return e}function Dk(t,e,r,i){for(let n of e.listChannels()){let s=xi(n);if(s===void 0)continue;let o=Gh(n.getTargetPath()??"translation"),a=s.interpolation==="CUBICSPLINE",c=a?o*3:o,u=[...gn(s,o,r),...a?new Array(o).fill(0):[]],d=[...gn(s,o,i),...a?new Array(o).fill(0):[]],f=[0],p=[...u];for(let g=0;g<s.times.length;g+=1){let m=s.times[g]??0;if(!(m<=r||m>=i)){f.push(m-r);for(let S=0;S<c;S+=1)p.push(s.values[g*c+S]??0);}}f.push(i-r),p.push(...d),Fa(t,n,f,p,o),a&&n.getSampler()?.setInterpolation("CUBICSPLINE");}}function Lk(t,e,r){let i=e.listChannels(),n=0;for(let a of i){let c=xi(a);c!==void 0&&(n=Math.max(n,c.times.at(-1)??0));}let s=Math.max(1,Math.round(n*r)),o=Array.from({length:s+1},(a,c)=>Math.min(n,c/r));for(let a of i){let c=xi(a);if(c===void 0)continue;let l=Gh(a.getTargetPath()??"translation"),u=o.flatMap(d=>gn(c,l,d));Fa(t,a,o,u,l);}}function kk(t,e){let r=new Map(t.getRoot().listNodes().map(i=>[i.getName(),i]));for(let i of e.listChannels()){let n=i.getTargetNode(),s=xi(i);if(n===null||s===void 0)continue;let o=i.getTargetPath()??"translation",a=Gh(o),c=[];for(let d=0;d+a<=s.values.length;d+=a){let f=Array.from({length:a},(p,g)=>s.values[d+g]??0);o==="translation"&&(f[0]=-(f[0]??0)),o==="rotation"&&(f[1]=-(f[1]??0),f[2]=-(f[2]??0)),c.push(...f);}Fa(t,i,[...s.times],c,a);let l=jE(n.getName()),u=l===void 0?void 0:r.get(l);u!==void 0&&i.setTargetNode(u);}}function Uk(t,e,r){let i=v0(t,e.getName()),n=r.feet.length>0?r.feet:i.bones.filter(s=>/foot/iu.test(s));if(n.length===0)throw new Error("No foot bones to lock: name them with 'feet'.");for(let s of n){let o=i.frames.map(g=>g.positions[s]?.[1]??0),a=Math.min(...o),c=e.listChannels().find(g=>g.getTargetNode()?.getName()===s&&g.getTargetPath()==="translation");if(c===void 0)continue;let l=xi(c);if(l===void 0)continue;let u=[],d=[],f,p=false;i.frames.forEach((g,m)=>{let S=g.positions[s];if(S===void 0)return;(S[1]??0)<=a+r.contact?(f??=S,p=true):(p=false,f=void 0);let v=p&&f!==void 0?[(f[0]??0)-(S[0]??0),0,(f[2]??0)-(S[2]??0)]:[0,0,0],_=HE(v,g.parents[s]??[0,0,0,1]);u.push(g.time),d.push((gn(l,3,g.time)[0]??0)+_[0],(gn(l,3,g.time)[1]??0)+_[1],(gn(l,3,g.time)[2]??0)+_[2]);}),Fa(t,c,u,d,3);}}function Fk(t,e,r){switch(r.kind){case "trim":{if(r.end<=r.start)throw new Error("trim needs an end after its start.");let i=$k(e);if(r.start>=i||r.end>i+1e-6)throw new Error(`trim asks for ${r.start}\u2013${r.end}s but '${e.getName()}' is ${i}s long.`);Dk(t,e,r.start,r.end);return}case "retime":if(!(r.speed>0))throw new Error("retime needs a speed above zero.");WE(t,e,i=>i/r.speed);return;case "loop-point":WE(t,e,i=>i<=r.time?i:void 0,r.time);return;case "resample":if(!(r.fps>0))throw new Error("resample needs an fps above zero.");Lk(t,e,r.fps);return;case "mirror":kk(t,e);return;case "foot-lock":Uk(t,e,r);return}}function KE(t,e,r){let i=t.getRoot().listAnimations().filter(n=>n.getName()===e);if(i.length===0)throw new Error(`The GLB has no clip '${e}' to edit.`);for(let n of r)for(let s of i)Fk(t,s,n);}async function ZE(t){return zk().read(t)}function Bk(t){let e=new Map;for(let r of t)r.op==="modify"&&e.set(r.clip,[...e.get(r.clip)??[],r.edit]);return e}async function XE(t,e){let r=await ZE(t.host),i=t.ops.some(o=>o.op==="attach")?await Iy(r,t):void 0,n=Bk(t.ops);for(let[o,a]of n)KE(r,o,a);return await new Jt().registerExtensions(Qt).write(e,r),{clips:i?.clips??[],edits:[...n.values()].reduce((o,a)=>o+a.length,0),file:e,modified:[...n.keys()]}}var ks=Object.freeze({contact:.03,jitter:.05,penetration:.01,seam:5,skate:.02,stretch:.02}),y0=(t,e)=>Math.hypot((t[0]??0)-(e[0]??0),(t[1]??0)-(e[1]??0),(t[2]??0)-(e[2]??0)),Vk=(t,e)=>Math.hypot((t[0]??0)-(e[0]??0),(t[2]??0)-(e[2]??0));function jk(t,e){let r=n=>Math.hypot(n[0]??0,n[1]??0,n[2]??0,n[3]??1)||1,i=((t[0]??0)*(e[0]??0)+(t[1]??0)*(e[1]??0)+(t[2]??0)*(e[2]??0)+(t[3]??1)*(e[3]??1))/(r(t)*r(e));return 2*Math.acos(Math.min(1,Math.abs(i)))*180/Math.PI}function S0(t,e=2){let r=[],i,n;for(let s of t)(i===void 0||n===void 0||s-n>e)&&(i!==void 0&&n!==void 0&&r.push({from:i,to:n}),i=s),n=s;return i!==void 0&&n!==void 0&&r.push({from:i,to:n}),r}function Gk(t,e,r,i){let n=[];for(let s of e){let o=t.frames.map(p=>p.positions[s]?.[1]??0),a=Math.min(...o),c=t.frames.map((p,g)=>({index:g,frame:p})).filter(({frame:p})=>(p.positions[s]?.[1]??0)<=a+i),l,u,d=()=>{u!==void 0&&(u.worst>r&&n.push({bone:s,detail:`the planted foot slid ${(u.worst*1e3).toFixed(0)} mm between frames ${u.first} and ${u.last}`,fromFrame:u.first,fromTime:t.frames[u.first]?.time??0,kind:"foot-skate",limit:r,measured:u.worst,toFrame:u.last,toTime:t.frames[u.last]?.time??0}),u=void 0,l=void 0);},f;for(let{index:p,frame:g}of c){f!==void 0&&p-f>1&&d(),l??=g;let m=Vk(g.positions[s]??[0,0,0],l.positions[s]??[0,0,0]);u??={first:p,last:p,worst:0},u.last=p,u.worst=Math.max(u.worst,m),f=p;}d();}return n}function Hk(t,e,r){let i=[];for(let n of e){let s=t.frames.map((o,a)=>({index:a,y:o.positions[n]?.[1]})).filter(({y:o})=>o!==void 0&&o<-r);for(let o of S0(s.map(({index:a})=>a))){let a=s.filter(({index:c})=>c>=o.from&&c<=o.to).reduce((c,{y:l})=>Math.min(c,l??0),0);i.push({bone:n,detail:`reaches ${(Math.abs(a)*1e3).toFixed(0)} mm below the floor`,fromFrame:o.from,fromTime:t.frames[o.from]?.time??0,kind:"ground-penetration",limit:r,measured:Math.abs(a),toFrame:o.to,toTime:t.frames[o.to]?.time??0});}}return i}function qk(t,e){let r=t.frames[0],i=t.frames.at(-1);if(r===void 0||i===void 0||t.frames.length<3)return [];let n,s=0;for(let o of t.bones){let a=r.rotations[o],c=i.rotations[o];if(a===void 0||c===void 0)continue;let l=jk(a,c);l<=e||(s+=1,(n===void 0||l>n.angle)&&(n={angle:l,bone:o}));}return n===void 0?[]:[{bone:n.bone,detail:`the clip ends ${n.angle.toFixed(1)}\xB0 from where it started${s>1?`, and ${s-1} more bones with it`:""}`,fromFrame:0,fromTime:r.time,kind:"loop-seam",limit:e,measured:n.angle,toFrame:t.frames.length-1,toTime:i.time}]}function Wk(t,e,r){let i=[];for(let n of e){let s=t.frames.map(l=>l.positions[n]),o=[],a=new Map,c=0;for(let l=1;l<s.length-1;l+=1){let u=s[l-1],d=s[l],f=s[l+1];if(u===void 0||d===void 0||f===void 0)continue;let p=y0([2*(d[0]??0)-(u[0]??0),2*(d[1]??0)-(u[1]??0),2*(d[2]??0)-(u[2]??0)],[f[0]??0,f[1]??0,f[2]??0]);p>r&&(o.push(l),a.set(l,Math.max(a.get(l)??0,p)),c=Math.max(c,p));}for(let l of S0(o.map(u=>u)))i.push({bone:n,detail:`a frame-direction spike of ${((a.get(l.from)??c)*1e3).toFixed(0)} mm`,fromFrame:l.from,fromTime:t.frames[l.from]?.time??0,kind:"jitter",limit:r,measured:c,toFrame:l.to,toTime:t.frames[l.to]?.time??0});}return i}function Kk(t,e){let r=t.frames[0];if(r===void 0)return [];let i=[];for(let[n,s]of Object.entries(t.parentsOf)){let o=y0(r.positions[n]??[0,0,0],r.positions[s]??[0,0,0]);if(o<=1e-6)continue;let a=t.frames.map((l,u)=>({index:u,ratio:Math.abs(y0(l.positions[n]??[0,0,0],l.positions[s]??[0,0,0])/o-1)})).filter(({ratio:l})=>l>e);if(a.length===0)continue;let c=a.reduce((l,{ratio:u})=>Math.max(l,u),0);for(let l of S0(a.map(({index:u})=>u)))i.push({bone:n,detail:`distance to its parent '${s}' changes by ${(c*100).toFixed(1)}%`,fromFrame:l.from,fromTime:t.frames[l.from]?.time??0,kind:"bone-stretch",limit:e,measured:c,toFrame:l.to,toTime:t.frames[l.to]?.time??0});}return i}var Zk=new Set(["left-foot","right-foot"]);async function JE(t,e,r={}){let i=r.scale??1,n={contact:(r.thresholds?.contact??ks.contact)/i,jitter:(r.thresholds?.jitter??ks.jitter)/i,penetration:(r.thresholds?.penetration??ks.penetration)/i,seam:r.thresholds?.seam??ks.seam,skate:(r.thresholds?.skate??ks.skate)/i,stretch:r.thresholds?.stretch??ks.stretch},s=await jh(t,e,r.fps??30),o=Sh(s.bones).filter(c=>Zk.has(c.id)).map(c=>c.node),a=[...Gk(s,o,n.skate,n.contact),...Hk(s,s.bones,n.penetration),...qk(s,n.seam),...Wk(s,s.bones,n.jitter),...Kk(s,n.stretch)];return {bones:s.bones.length,clip:e,defects:a,duration:s.duration,file:t,fps:s.fps,frames:s.frames.length,passed:a.length===0,scale:i,thresholds:n}}var Jk=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let i=0;i<8;i+=1)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0;}return t})();function Yk(t){let e=4294967295;for(let r of t)e=(Jk[(e^r)&255]??0)^e>>>8;return (e^4294967295)>>>0}function x0(t,e){let r=Buffer.alloc(4);r.writeUInt32BE(e.length,0);let i=Buffer.concat([Buffer.from(t,"ascii"),Buffer.from(e)]),n=Buffer.alloc(4);return n.writeUInt32BE(Yk(i),0),Buffer.concat([r,i,n])}function YE(t,e,r){let i=Buffer.alloc(13);i.writeUInt32BE(t,0),i.writeUInt32BE(e,4),i[8]=8,i[9]=6,i[10]=0,i[11]=0,i[12]=0;let n=t*4,s=Buffer.alloc((n+1)*e);for(let o=0;o<e;o+=1)s[o*(n+1)]=0,Buffer.from(r.buffer,r.byteOffset+o*n,n).copy(s,o*(n+1)+1);return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),x0("IHDR",i),x0("IDAT",deflateSync(s,{level:9})),x0("IEND",new Uint8Array)])}var b0=[9,13,11],tU=[183,243,74],nU=[39,48,44];function ew(t,e,r,i){let[n,s]=e,[o,a]=r,c=Math.max(1,Math.ceil(Math.max(Math.abs(o-n),Math.abs(a-s))));for(let l=0;l<=c;l+=1){let u=Math.round(n+(o-n)*l/c),d=Math.round(s+(a-s)*l/c);if(u<0||d<0||u>=t.width||d>=t.height)continue;let f=t.width*d+u<<2;t.data[f]=i[0]??0,t.data[f+1]=i[1]??0,t.data[f+2]=i[2]??0,t.data[f+3]=255;}}async function tw(t){let e=await jh(t.file,t.clip,t.fps??30),r=Math.max(1,t.columns??6),i=Math.max(48,t.height??160),n=Math.min(r,e.frames.length),s=Math.max(1,Math.floor((e.frames.length-1)/Math.max(1,n-1))),o=Array.from({length:n},(_,y)=>Math.min(e.frames.length-1,y*s)),a={data:new Uint8Array(i*n*i*4),height:i,width:i*n};for(let _=0;_<a.width*a.height;_+=1){let y=_<<2;a.data[y]=b0[0],a.data[y+1]=b0[1],a.data[y+2]=b0[2],a.data[y+3]=255;}let c=o.flatMap(_=>e.bones.map(y=>e.frames[_]?.positions[y]).filter(y=>y!==void 0)),l=c.map(_=>_[0]),u=c.map(_=>_[1]),d=Math.min(...l,0),f=Math.max(...l,1),p=Math.min(...u,0),g=Math.max(...u,1),m=Math.max(1e-6,Math.max(f-d,g-p)),S=i*.12,h=(_,y,R)=>[Math.round(R*i+S+(_-d)/m*(i-S*2)),Math.round(i-S-(y-p)/m*(i-S*2))];o.forEach((_,y)=>{let R=e.frames[_];if(R!==void 0){ew(a,h(d,p,y),h(f,p,y),nU);for(let T of e.bones){let b=R.positions[T];b!==void 0&&ew(a,h(b[0],0,y),h(b[0],b[1],y),tU);}}});let v=YE(a.width,a.height,a.data);return await mkdir(Gr.dirname(Gr.resolve(t.output)),{recursive:true}),await writeFile(t.output,v),{bytes:v.length,columns:n,frames:e.frames.length}}var rU=String.raw`
|
|
253
253
|
:root{color-scheme:dark;font-family:"IBM Plex Mono","Azeret Mono",ui-monospace,monospace;background:#080b0a;color:#dce4de;--line:#27302c;--line2:#38433e;--panel:#111613;--panel2:#171d1a;--acid:#b7f34a;--cyan:#68d9d0;--muted:#77837c;--red:#ff705d}*{box-sizing:border-box}body{margin:0;overflow:hidden;background:#080b0a}button{cursor:pointer}.lab{height:100vh;display:grid;grid-template-rows:50px 1fr 26px}.bar{display:flex;align-items:center;gap:14px;padding:0 14px;border-bottom:1px solid var(--line);background:#0d120f}.brand{font:800 13px sans-serif;letter-spacing:.18em}.brand b{display:inline-grid;place-items:center;width:24px;height:24px;margin-right:9px;background:var(--acid);color:#101808}.bar small,.status{color:var(--muted)}.grow{flex:1}.bar button{border:1px solid #789e3f;border-radius:2px;background:var(--acid);color:#111908;padding:8px 14px;font:800 10px inherit}.body{min-height:0;display:grid;grid-template-columns:230px minmax(0,1fr) 285px}.side{overflow:auto;background:var(--panel)}.left{border-right:1px solid var(--line)}.right{border-left:1px solid var(--line)}.section{padding:13px;border-bottom:1px solid var(--line)}h2{margin:0 0 10px;color:var(--muted);font-size:9px;letter-spacing:.16em;text-transform:uppercase}label{display:grid;gap:5px;margin-bottom:10px;color:#91a097;font-size:9px;text-transform:uppercase}select,input{width:100%;border:1px solid var(--line);border-radius:2px;background:#090d0b;color:#dce4de;padding:8px;font:10px inherit;outline:none}select:focus,input:focus{border-color:var(--acid)}input:disabled{opacity:.38}.workspace{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(280px,1fr) 224px;background:#090d0b}.viewport{position:relative;min-width:0;min-height:0}.viewport canvas{display:block;width:100%;height:100%}.title{position:absolute;top:18px;left:18px;pointer-events:none;font:800 23px sans-serif}.title small{display:block;margin-top:6px;color:var(--acid);font:9px ui-monospace;letter-spacing:.14em}.tools{position:absolute;bottom:16px;left:50%;display:flex;transform:translateX(-50%);border:1px solid var(--line2);background:#090d0be8}.tools button,.preset button{border:0;background:none;color:var(--muted);padding:9px 15px;font:9px inherit;text-transform:uppercase}.tools button.on{background:#263328;color:var(--acid)}.tools button:disabled{opacity:.28;cursor:not-allowed}.release-note{position:absolute;top:18px;right:18px;padding:7px 10px;border:1px solid #8b493d;background:#2b1713d9;color:#ff9b86;font-size:9px;letter-spacing:.13em}.landmarks{display:grid;gap:5px}.landmark{display:grid;grid-template-columns:8px 1fr auto;gap:8px;align-items:center;width:100%;padding:8px;border:1px solid transparent;border-radius:2px;background:#0c110f;color:var(--muted);font:10px inherit;text-align:left}.landmark.on{border-color:#668c34;color:#dce4de}.landmark i{width:6px;height:6px;border-radius:50%;background:#71b9ff}.landmark.detected i{background:var(--acid)}.landmark small{font-size:8px;color:#69756f}.axis{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}.axis label{margin:0}.preset{display:grid;grid-template-columns:repeat(4,1fr);margin-top:8px}.preset button{padding:7px 2px;border:1px solid var(--line)}.wide,.editor-bar button,.segmented button{border:1px solid var(--line2);border-radius:2px;background:#1a211d;color:#dce4de;padding:8px;font:10px inherit}.wide{width:100%}.secondary{color:var(--muted)!important;background:#0d1210!important}.segmented{display:grid;grid-template-columns:1fr 1fr;gap:3px}.segmented button.on{border-color:var(--acid);color:var(--acid);background:#243021}.segmented button.danger.on{border-color:var(--red);color:#ff9b86;background:#321a16}.hint{margin:8px 0 0;color:var(--muted);font-size:9px;line-height:1.5}.status{display:flex;justify-content:space-between;align-items:center;padding:0 12px;border-top:1px solid var(--line);font-size:9px}.status b{color:var(--acid)}.error{position:absolute;top:18px;right:18px;max-width:360px;padding:10px;border:1px solid #81452f;background:#321a12;color:#ffb08a;font-size:10px}.saved{color:var(--acid);font-size:9px}.dope-editor{min-width:0;border-top:1px solid #46504b;background:#101512;box-shadow:0 -12px 30px #0008}.editor-bar{height:44px;display:flex;align-items:center;gap:7px;padding:6px 9px;border-bottom:1px solid var(--line2);background:#171c19}.editor-bar select{width:180px;padding:7px}.editor-bar button{white-space:nowrap;padding:7px 10px}.editor-bar button:disabled{opacity:.3;cursor:not-allowed}.editor-bar .transport{width:34px;border-color:#738d47;color:var(--acid);font-size:13px}.timecode{min-width:90px;color:#e1e7e3;font-size:11px;letter-spacing:.08em}.timecode i{color:var(--muted);font-style:normal}.compact{display:flex}.sheet{position:relative;height:179px;display:grid;grid-template-columns:132px 1fr;grid-template-rows:27px repeat(4,38px);overflow:hidden;background:repeating-linear-gradient(90deg,transparent 0,transparent calc(10% - 1px),#252d29 calc(10% - 1px),#252d29 10%)}.ruler-label{grid-column:1;grid-row:1}.ruler{position:relative;grid-column:2;grid-row:1;border-bottom:1px solid var(--line2);background:#0c100e}.ruler span{position:absolute;bottom:5px;transform:translateX(-50%);color:#68736d;font-size:8px}.lane-row{display:contents}.lane-label{z-index:3;display:flex;align-items:center;gap:8px;padding-left:13px;border-right:1px solid var(--line2);border-bottom:1px solid #222a26;background:#151a17;color:#87938c;font-size:9px;letter-spacing:.1em}.lane-label i{width:6px;height:6px;border:1px solid var(--cyan);transform:rotate(45deg)}.lane-track{position:relative;border-bottom:1px solid #222a26;background:#0d120f66}.key-diamond{position:absolute;z-index:4;top:14px;width:10px;height:10px;padding:0;transform:translate(-50%,-50%) rotate(45deg);border:1px solid #e2ffae;background:var(--acid);box-shadow:0 0 0 2px #0a0e0c}.attachment-lane .lane-label{grid-column:1;grid-row:5}.event-clip{align-self:center;grid-column:2;grid-row:5;height:23px;margin:0 8px;padding:6px 10px;border-left:3px solid var(--cyan);background:#17312d;color:#8ce7df;font-size:9px;letter-spacing:.08em}.event-clip.released{border-left-color:var(--red);background:#321a16;color:#ff9b86}.playhead{position:absolute;z-index:6;top:0;bottom:0;width:1px;background:#f3f7f4;pointer-events:none}.playhead b{position:absolute;top:0;left:-4px;width:9px;height:9px;background:#f3f7f4;clip-path:polygon(0 0,100% 0,50% 100%)}.scrubber{position:absolute;z-index:7;top:0;right:0;bottom:0;left:132px;width:calc(100% - 132px);height:100%;margin:0;padding:0;opacity:0;cursor:ew-resize}.ruler{grid-column:2;grid-row:1}.lane-row:nth-of-type(1) .lane-label,.lane-row:nth-of-type(1) .lane-track{grid-row:2}.lane-row:nth-of-type(2) .lane-label,.lane-row:nth-of-type(2) .lane-track{grid-row:3}.lane-row:nth-of-type(3) .lane-label,.lane-row:nth-of-type(3) .lane-track{grid-row:4}.lane-row .lane-label{grid-column:1}.lane-row .lane-track{grid-column:2}@media(max-width:980px){.body{grid-template-columns:210px 1fr}.right{display:none}.workspace{grid-template-rows:minmax(260px,1fr) 224px}.compact{display:none}}
|
|
254
254
|
`;function nw(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll('"',""")}function rw(t){return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Pose Lab \u2014 ${nw(t)}</title><style>${rU}</style></head><body><div id="root" data-project="${nw(t)}"></div><script type="module" src="/app.js"></script></body></html>`}var aU=new URL("./client/app.js",import.meta.url),cU=256e3;function iw(t,e){if(e.length===0||Gr.isAbsolute(e)||e.split(/[\\/]/u).some(n=>n.length===0||n.startsWith(".")))return;let r=Gr.resolve(t),i=Gr.resolve(r,e);return i.startsWith(`${r}${Gr.sep}`)?i:void 0}async function lU(t){let e=[],r=new Set([".git","build","dist","node_modules"]),i=async(n,s,o)=>{if(o>6||e.length>=2e3)return;let a=await readdir(n,{withFileTypes:true}).catch(()=>[]);for(let c of a){if(c.name.startsWith(".")||r.has(c.name))continue;let l=s.length===0?c.name:`${s}/${c.name}`;c.isDirectory()?await i(Gr.join(n,c.name),l,o+1):c.name.toLowerCase().endsWith(".glb")&&e.push(l);}};return await i(t,"",0),e.sort((n,s)=>n.localeCompare(s))}async function uU(t){let e=[],r=0;for await(let i of t){let n=Buffer.from(i);if(r+=n.length,r>cU)throw new Error("Request exceeds 256 KB.");e.push(n);}return JSON.parse(Buffer.concat(e).toString("utf8"))}function Hh(t,e,r,i){t.writeHead(e,{"cache-control":"no-store","content-type":i,"x-content-type-options":"nosniff"}),t.end(r);}function Rn(t,e,r){Hh(t,e,JSON.stringify(r),"application/json; charset=utf-8");}async function ow(t={}){let e=Gr.resolve(t.project??process.cwd()),r=t.port??4192;await readdir(e).catch(()=>{throw new Error(`Project directory does not exist: ${e}`)});let i=createServer(async(s,o)=>{try{let a=new URL(s.url??"/","http://pose-lab");if(s.method==="GET"&&(a.pathname==="/"||a.pathname==="/pose"))return Hh(o,200,rw(Gr.basename(e)),"text/html; charset=utf-8");if(s.method==="GET"&&a.pathname==="/app.js")return Hh(o,200,await readFile(aU),"text/javascript; charset=utf-8");if(s.method==="GET"&&a.pathname==="/favicon.ico")return o.writeHead(204),o.end();if(s.method==="GET"&&a.pathname==="/api/models")return Rn(o,200,{models:await lU(e)});if(s.method==="GET"&&a.pathname==="/api/model"){let c=a.searchParams.get("path")??"",l=c.endsWith(".glb")?iw(e,c):void 0;if(l===void 0)return Rn(o,404,{error:"GLB not found."});let u=await readFile(l).catch(()=>{});return u===void 0?Rn(o,404,{error:"GLB not found."}):Hh(o,200,u,"model/gltf-binary")}if(a.pathname==="/api/recipe"){let c=a.searchParams.get("path")??"",l=c.endsWith(".json")?iw(e,c):void 0;if(l===void 0)return Rn(o,404,{error:"Recipe not found."});if(s.method==="GET"){let u=await readFile(l,"utf8").catch(()=>{});return u===void 0?Rn(o,404,{error:"Recipe not found."}):Rn(o,200,{recipe:JSON.parse(u),path:c})}if(s.method==="PUT"){let u=await uU(s);return typeof u.recipe!="object"||u.recipe===null?Rn(o,400,{error:"Body must contain a recipe object."}):(await mkdir(Gr.dirname(l),{recursive:!0}),await writeFile(l,`${JSON.stringify(u.recipe,null,2)}
|
|
255
|
-
`,"utf8"),Rn(o,200,{path:c,saved:!0}))}}return Rn(o,404,{error:"Not found."})}catch(a){return Rn(o,500,{error:a instanceof Error?a.message:String(a)})}});await new Promise((s,o)=>{i.once("error",o),i.listen(r,"127.0.0.1",s);});let n=i.address();return {port:typeof n=="object"&&n!==null?n.port:r,close:()=>new Promise((s,o)=>i.close(a=>a?o(a):s()))}}var fU=B.object({position:B.tuple([B.number(),B.number(),B.number()]),rotation:B.tuple([B.number(),B.number(),B.number()]),scale:B.tuple([B.number(),B.number(),B.number()])}),_w=B.enum(yh.map(t=>t.id)),pU=B.object({attachment:B.enum(["attached","detached"]).optional(),clip:B.string().min(1).max(200),time:B.number().min(0).max(600),transform:fU}),mU=B.object({file:B.string().min(1)}),cw=B.object({bones:B.array(B.string()),bytes:B.number(),clips:B.array(B.object({channels:B.number(),duration:B.number(),horizontalTravel:B.number(),inPlace:B.boolean(),name:B.string()})),extensionsUsed:B.array(B.string()),file:B.string(),generator:B.string(),inPlace:B.boolean(),landmarks:B.array(B.object({id:B.string(),label:B.string(),node:B.string(),source:B.enum(["detected","estimated"])})),meshes:B.number(),rootBone:B.string().nullable(),skins:B.number(),warnings:B.array(B.string())}),lw=B.object({anchor:_w.default("right-hand"),attached:B.string().min(1).optional(),bone:B.string().min(1).optional(),host:B.string().min(1).optional(),keys:B.array(pU).max(2e3).optional(),log:B.string().min(1).optional(),output:B.string().min(1).optional(),recipe:B.string().min(1).optional()}),uw=B.object({anchor:B.string(),attached:B.string(),clips:B.array(B.string()),detached:B.array(B.string()),file:B.string(),log:B.string(),node:B.string()}),dw=B.object({clip:B.string().min(1).max(200),file:B.string().min(1),filmstrip:B.string().min(1).optional(),fps:B.number().int().min(1).max(240).default(30),scale:B.number().positive().default(1)}),hw=B.object({bones:B.number(),clip:B.string(),filmstrip:B.string().nullable(),defects:B.array(B.object({bone:B.string(),detail:B.string(),fromFrame:B.number(),fromTime:B.number(),kind:B.enum(["bone-stretch","foot-skate","ground-penetration","jitter","loop-seam"]),limit:B.number(),measured:B.number(),toFrame:B.number(),toTime:B.number()})),duration:B.number(),file:B.string(),fps:B.number(),frames:B.number(),passed:B.boolean(),scale:B.number(),thresholds:B.object({contact:B.number(),jitter:B.number(),penetration:B.number(),seam:B.number(),skate:B.number(),stretch:B.number()})}),gU=B.discriminatedUnion("kind",[B.object({end:B.number().min(0),kind:B.literal("trim"),start:B.number().min(0)}),B.object({kind:B.literal("retime"),speed:B.number().positive()}),B.object({kind:B.literal("loop-point"),time:B.number().min(0)}),B.object({fps:B.number().positive(),kind:B.literal("resample")}),B.object({kind:B.literal("mirror")}),B.object({contact:B.number().min(0).default(.03),feet:B.array(B.string().min(1)).max(8).default([]),kind:B.literal("foot-lock")})]),fw=B.object({clip:B.string().min(1).max(200),edits:B.array(gU).min(1).max(64),file:B.string().min(1),log:B.string().min(1).optional(),output:B.string().min(1).optional()}),pw=B.object({clips:B.array(B.string()),edits:B.number(),file:B.string(),log:B.string(),modified:B.array(B.string())}),R0=B.object({anchor:_w.default("right-hand"),attach:B.string().min(1).optional(),host:B.string().min(1).optional(),output:B.string().min(1).optional(),port:B.number().int().min(0).max(65535).optional(),project:B.string().min(1).optional()}),mw=B.object({port:B.number(),url:B.string()}),Ba=t=>({destructiveHint:false,idempotentHint:true,openWorldHint:false,readOnlyHint:t}),En=t=>[{type:"text",text:JSON.stringify(t)}];function _U(t,e,r){if(r!==void 0){let s=yh.find(o=>o.id===e);if(s===void 0)throw new Error(`Unknown anchor '${e}'.`);return {id:e,label:s.label,node:r,source:"detected"}}let i=t.find(s=>s.id===e);if(i!==void 0)return i;let n=t.map(s=>`${s.id} \u2192 ${s.node}`);throw new Error(`The host names no '${e}' landmark. It answers to: ${n.length===0?"none":n.join(", ")}. Pass 'bone' to name one directly.`)}function vU(t){return {position:t.position,rotation:t.rotation,scale:t.scale}}function vw(t){let e=Gr.parse(t);return Gr.join(e.dir,`${e.name}.anim.glb`)}async function yU(t){return t.filmstrip===void 0?null:(await tw({clip:t.clip,file:t.file,fps:t.fps,output:t.filmstrip}),Gr.resolve(t.filmstrip))}async function SU(t){let e=(t.keys??[]).map(s=>({attachment:s.attachment,clip:s.clip,op:"key",time:s.time,transform:vU(s.transform)})),r;if(t.recipe!==void 0){r=Ry(JSON.parse(await readFile(t.recipe,"utf8")));for(let s of e)r=Ey(r,s);}else {if(t.host===void 0||t.attached===void 0)throw new Error("Pass 'host' and 'attached', or a 'recipe' that names both.");let s=await Py(t.host);r={host:t.host,ops:[{anchor:_U(s.landmarks,t.anchor,t.bone),attached:t.attached,op:"attach"},...e],version:4};}let i=t.log??wy(r.host);return await My(i,r),{...await hE(r,t.output??vw(r.host)),log:Gr.resolve(i)}}var gw;function yw(t){return gw??=(async()=>{let e=await ow({...t.port===void 0?{}:{port:t.port},...t.project===void 0?{}:{project:t.project}}),r=new URLSearchParams;return t.host!==void 0&&r.set("host",t.host),t.attach!==void 0&&r.set("attach",t.attach),t.output!==void 0&&r.set("output",t.output),r.set("anchor",t.anchor),{port:e.port,url:`http://127.0.0.1:${e.port}/pose?${r.toString()}`}})(),gw}function xU(){let t=new Aa({name:"threenative-animation",version:"0.1.
|
|
255
|
+
`,"utf8"),Rn(o,200,{path:c,saved:!0}))}}return Rn(o,404,{error:"Not found."})}catch(a){return Rn(o,500,{error:a instanceof Error?a.message:String(a)})}});await new Promise((s,o)=>{i.once("error",o),i.listen(r,"127.0.0.1",s);});let n=i.address();return {port:typeof n=="object"&&n!==null?n.port:r,close:()=>new Promise((s,o)=>i.close(a=>a?o(a):s()))}}var fU=B.object({position:B.tuple([B.number(),B.number(),B.number()]),rotation:B.tuple([B.number(),B.number(),B.number()]),scale:B.tuple([B.number(),B.number(),B.number()])}),_w=B.enum(yh.map(t=>t.id)),pU=B.object({attachment:B.enum(["attached","detached"]).optional(),clip:B.string().min(1).max(200),time:B.number().min(0).max(600),transform:fU}),mU=B.object({file:B.string().min(1)}),cw=B.object({bones:B.array(B.string()),bytes:B.number(),clips:B.array(B.object({channels:B.number(),duration:B.number(),horizontalTravel:B.number(),inPlace:B.boolean(),name:B.string()})),extensionsUsed:B.array(B.string()),file:B.string(),generator:B.string(),inPlace:B.boolean(),landmarks:B.array(B.object({id:B.string(),label:B.string(),node:B.string(),source:B.enum(["detected","estimated"])})),meshes:B.number(),rootBone:B.string().nullable(),skins:B.number(),warnings:B.array(B.string())}),lw=B.object({anchor:_w.default("right-hand"),attached:B.string().min(1).optional(),bone:B.string().min(1).optional(),host:B.string().min(1).optional(),keys:B.array(pU).max(2e3).optional(),log:B.string().min(1).optional(),output:B.string().min(1).optional(),recipe:B.string().min(1).optional()}),uw=B.object({anchor:B.string(),attached:B.string(),clips:B.array(B.string()),detached:B.array(B.string()),file:B.string(),log:B.string(),node:B.string()}),dw=B.object({clip:B.string().min(1).max(200),file:B.string().min(1),filmstrip:B.string().min(1).optional(),fps:B.number().int().min(1).max(240).default(30),scale:B.number().positive().default(1)}),hw=B.object({bones:B.number(),clip:B.string(),filmstrip:B.string().nullable(),defects:B.array(B.object({bone:B.string(),detail:B.string(),fromFrame:B.number(),fromTime:B.number(),kind:B.enum(["bone-stretch","foot-skate","ground-penetration","jitter","loop-seam"]),limit:B.number(),measured:B.number(),toFrame:B.number(),toTime:B.number()})),duration:B.number(),file:B.string(),fps:B.number(),frames:B.number(),passed:B.boolean(),scale:B.number(),thresholds:B.object({contact:B.number(),jitter:B.number(),penetration:B.number(),seam:B.number(),skate:B.number(),stretch:B.number()})}),gU=B.discriminatedUnion("kind",[B.object({end:B.number().min(0),kind:B.literal("trim"),start:B.number().min(0)}),B.object({kind:B.literal("retime"),speed:B.number().positive()}),B.object({kind:B.literal("loop-point"),time:B.number().min(0)}),B.object({fps:B.number().positive(),kind:B.literal("resample")}),B.object({kind:B.literal("mirror")}),B.object({contact:B.number().min(0).default(.03),feet:B.array(B.string().min(1)).max(8).default([]),kind:B.literal("foot-lock")})]),fw=B.object({clip:B.string().min(1).max(200),edits:B.array(gU).min(1).max(64),file:B.string().min(1),log:B.string().min(1).optional(),output:B.string().min(1).optional()}),pw=B.object({clips:B.array(B.string()),edits:B.number(),file:B.string(),log:B.string(),modified:B.array(B.string())}),R0=B.object({anchor:_w.default("right-hand"),attach:B.string().min(1).optional(),host:B.string().min(1).optional(),output:B.string().min(1).optional(),port:B.number().int().min(0).max(65535).optional(),project:B.string().min(1).optional()}),mw=B.object({port:B.number(),url:B.string()}),Ba=t=>({destructiveHint:false,idempotentHint:true,openWorldHint:false,readOnlyHint:t}),En=t=>[{type:"text",text:JSON.stringify(t)}];function _U(t,e,r){if(r!==void 0){let s=yh.find(o=>o.id===e);if(s===void 0)throw new Error(`Unknown anchor '${e}'.`);return {id:e,label:s.label,node:r,source:"detected"}}let i=t.find(s=>s.id===e);if(i!==void 0)return i;let n=t.map(s=>`${s.id} \u2192 ${s.node}`);throw new Error(`The host names no '${e}' landmark. It answers to: ${n.length===0?"none":n.join(", ")}. Pass 'bone' to name one directly.`)}function vU(t){return {position:t.position,rotation:t.rotation,scale:t.scale}}function vw(t){let e=Gr.parse(t);return Gr.join(e.dir,`${e.name}.anim.glb`)}async function yU(t){return t.filmstrip===void 0?null:(await tw({clip:t.clip,file:t.file,fps:t.fps,output:t.filmstrip}),Gr.resolve(t.filmstrip))}async function SU(t){let e=(t.keys??[]).map(s=>({attachment:s.attachment,clip:s.clip,op:"key",time:s.time,transform:vU(s.transform)})),r;if(t.recipe!==void 0){r=Ry(JSON.parse(await readFile(t.recipe,"utf8")));for(let s of e)r=Ey(r,s);}else {if(t.host===void 0||t.attached===void 0)throw new Error("Pass 'host' and 'attached', or a 'recipe' that names both.");let s=await Py(t.host);r={host:t.host,ops:[{anchor:_U(s.landmarks,t.anchor,t.bone),attached:t.attached,op:"attach"},...e],version:4};}let i=t.log??wy(r.host);return await My(i,r),{...await hE(r,t.output??vw(r.host)),log:Gr.resolve(i)}}var gw;function yw(t){return gw??=(async()=>{let e=await ow({...t.port===void 0?{}:{port:t.port},...t.project===void 0?{}:{project:t.project}}),r=new URLSearchParams;return t.host!==void 0&&r.set("host",t.host),t.attach!==void 0&&r.set("attach",t.attach),t.output!==void 0&&r.set("output",t.output),r.set("anchor",t.anchor),{port:e.port,url:`http://127.0.0.1:${e.port}/pose?${r.toString()}`}})(),gw}function xU(){let t=new Aa({name:"threenative-animation",version:"0.1.12"});return t.registerTool("animation_inspect",{annotations:Ba(true),description:"Inspect a local rigged GLB: bones, skeleton landmarks, clips with durations, root-motion travel and in-place detection, meshes, skins and extensions. Reads one local file and writes nothing.",inputSchema:mU,outputSchema:cw,title:"Inspect a rig and its clips"},async e=>{try{let r=cw.parse(await Py(e.file));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_attach",{annotations:Ba(false),description:"Attach a prop GLB to a bone, with per-clip keyed offsets, and bake it into an ordinary GLB beside the source. Writes the v4 op log (<model>.anim.json) next to the source GLB and the baked GLB; a version 3 pose recipe loads as the same ops and still bakes.",inputSchema:lw,outputSchema:uw,title:"Attach a prop to a bone and bake it"},async e=>{try{let r=uw.parse(await SU(lw.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_verify",{annotations:Ba(true),description:"Measure one clip for the defects a still frame cannot show: a planted foot that slides (2 cm), ground penetration (1 cm), a loop seam (5\xB0), a one-frame jitter spike, and bones whose length changes. Every defect names the bone and the frame range it spans. Thresholds are in metres; pass `scale` for a model that is not (Mixamo and Quaternius are centimetres: 0.01).",inputSchema:dw,outputSchema:hw,title:"Verify a clip's motion"},async e=>{try{let r=dw.parse(e),i=hw.parse({...await JE(r.file,r.clip,{fps:r.fps,scale:r.scale}),filmstrip:await yU(r)});return {content:En(i),structuredContent:i}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_modify",{annotations:Ba(false),description:"Edit one clip \u2014 trim, retime, move the loop point, resample, mirror, lock planted feet \u2014 writing each edit into the op log and rendering the result from the source GLB. Rendering twice from one log gives the same bytes, so the log is the change and the GLB is derived.",inputSchema:fw,outputSchema:pw,title:"Edit a clip and render it from the log"},async e=>{try{let r=fw.parse(e),i=r.log??wy(r.file),s=await lE(i).catch(async()=>({host:r.file,ops:[],version:4}));for(let c of r.edits)s=Ey(s,{clip:r.clip,edit:c,op:"modify"});await My(i,s);let o=await XE(s,r.output??vw(r.file)),a=pw.parse({...o,log:Gr.resolve(i)});return {content:En(a),structuredContent:a}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t.registerTool("animation_open_view",{annotations:Ba(false),description:"Start the animation calibrator page on 127.0.0.1 and return its URL. A human drags the prop into place there; the same operations an agent calls are what the page records.",inputSchema:R0,outputSchema:mw,title:"Open the animation calibrator"},async e=>{try{let r=mw.parse(await yw(R0.parse(e)));return {content:En(r),structuredContent:r}}catch(r){return {content:En({message:r instanceof Error?r.message:String(r)}),isError:true}}}),t}function bU(){nR(()=>xU());}function TU(){let t=process.argv[1];if(t===void 0)return false;try{return realpathSync(t)===realpathSync(fileURLToPath(import.meta.url))}catch{return false}}TU()&&(process.argv[2]==="--view"?yw(R0.parse({project:process.cwd()})).then(({url:t})=>process.stdout.write(`Animation view: ${t}
|
|
256
256
|
`),t=>{process.stderr.write(`${t instanceof Error?t.message:String(t)}
|
|
257
257
|
`),process.exitCode=1;}):bU());/*! Bundled license information:
|
|
258
258
|
|
package/mcp/engine-server.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { realpathSync, readFileSync, existsSync, mkdirSync, rmSync, writeFileSync, appendFileSync, mkdtempSync, renameSync, readdirSync } from 'fs';
|
|
2
|
+
import { realpathSync, statSync, readFileSync, existsSync, mkdirSync, rmSync, writeFileSync, appendFileSync, mkdtempSync, renameSync, readdirSync } from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { createInterface } from 'readline';
|
|
5
5
|
import { fileURLToPath } from 'url';
|
|
@@ -673,15 +673,23 @@ function validateManifest(value, file) {
|
|
|
673
673
|
}
|
|
674
674
|
return value;
|
|
675
675
|
}
|
|
676
|
+
var manifestCache = /* @__PURE__ */ new Map();
|
|
676
677
|
function loadCapabilityManifest(file = defaultManifestPath()) {
|
|
677
678
|
let raw;
|
|
679
|
+
let stamp;
|
|
678
680
|
try {
|
|
681
|
+
const stat = statSync(file);
|
|
682
|
+
stamp = `${stat.mtimeMs}:${stat.size}`;
|
|
683
|
+
const cached = manifestCache.get(file);
|
|
684
|
+
if (cached?.stamp === stamp) return cached.manifest;
|
|
679
685
|
raw = readFileSync(file, "utf8");
|
|
680
686
|
} catch (error) {
|
|
681
687
|
throw manifestError(file, `cannot read committed manifest: ${String(error)}`);
|
|
682
688
|
}
|
|
683
689
|
try {
|
|
684
|
-
|
|
690
|
+
const manifest = validateManifest(JSON.parse(raw), file);
|
|
691
|
+
manifestCache.set(file, { stamp, manifest });
|
|
692
|
+
return manifest;
|
|
685
693
|
} catch (error) {
|
|
686
694
|
if (error instanceof Error && error.message.startsWith("TN_ENGINE_CAPABILITIES_MANIFEST:"))
|
|
687
695
|
throw error;
|
|
@@ -704,10 +712,23 @@ function suffixStripped(token) {
|
|
|
704
712
|
return token;
|
|
705
713
|
}
|
|
706
714
|
var STOP_WORD_STEMS = new Set([...STOP_WORDS].map(stem));
|
|
715
|
+
function splitSymbolCase(value) {
|
|
716
|
+
return value.replace(/([a-z0-9])([A-Z])/gu, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/gu, "$1 $2");
|
|
717
|
+
}
|
|
707
718
|
function capabilitySituationTokens(value) {
|
|
708
|
-
return value.toLocaleLowerCase().split(/[^a-z0-9]+/u).filter((token) => token.length > 1 && !STOP_WORDS.has(token)).map(stem).filter((token) => !STOP_WORD_STEMS.has(token));
|
|
719
|
+
return splitSymbolCase(value).toLocaleLowerCase().split(/[^a-z0-9]+/u).filter((token) => token.length > 1 && !STOP_WORDS.has(token)).map(stem).filter((token) => !STOP_WORD_STEMS.has(token));
|
|
720
|
+
}
|
|
721
|
+
var tokenCache = /* @__PURE__ */ new Map();
|
|
722
|
+
var TOKEN_CACHE_LIMIT = 2e4;
|
|
723
|
+
function tokens(value) {
|
|
724
|
+
let cached = tokenCache.get(value);
|
|
725
|
+
if (cached === void 0) {
|
|
726
|
+
if (tokenCache.size >= TOKEN_CACHE_LIMIT) tokenCache.clear();
|
|
727
|
+
cached = Object.freeze(capabilitySituationTokens(value));
|
|
728
|
+
tokenCache.set(value, cached);
|
|
729
|
+
}
|
|
730
|
+
return cached;
|
|
709
731
|
}
|
|
710
|
-
var tokens = capabilitySituationTokens;
|
|
711
732
|
function tokenWeights(entries) {
|
|
712
733
|
const frequency = /* @__PURE__ */ new Map();
|
|
713
734
|
let situations = 0;
|
|
@@ -725,6 +746,36 @@ function tokenWeights(entries) {
|
|
|
725
746
|
function weightOf(weights, token) {
|
|
726
747
|
return weights.get(token) ?? 0;
|
|
727
748
|
}
|
|
749
|
+
function nameWords(value) {
|
|
750
|
+
return tokens(value.replace(/([a-zA-Z])(\d+)/gu, "$1 $2")).filter((token) => !/\d/u.test(token));
|
|
751
|
+
}
|
|
752
|
+
function normaliseName(value) {
|
|
753
|
+
return value.toLocaleLowerCase().replace(/[^a-z0-9]+/gu, "");
|
|
754
|
+
}
|
|
755
|
+
function spelledWords(value) {
|
|
756
|
+
return value.toLocaleLowerCase().split(/[^a-z0-9]+/u).filter((word) => word.length > 0);
|
|
757
|
+
}
|
|
758
|
+
function spellsName(situation, symbol) {
|
|
759
|
+
const words = spelledWords(situation);
|
|
760
|
+
const whole = normaliseName(symbol);
|
|
761
|
+
for (let start = 0; start < words.length; start += 1) {
|
|
762
|
+
let piece = "";
|
|
763
|
+
for (let end = start; end < words.length && end < start + 4; end += 1) {
|
|
764
|
+
piece += normaliseName(words[end] ?? "");
|
|
765
|
+
if (piece === whole) return true;
|
|
766
|
+
if (piece.length >= whole.length) break;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
return false;
|
|
770
|
+
}
|
|
771
|
+
function nameTokenWeights(entries) {
|
|
772
|
+
return tokenWeights(
|
|
773
|
+
entries.map((entry) => ({
|
|
774
|
+
aliases: [nameWords(entry.symbol).join(" ")],
|
|
775
|
+
situations: [entry.summary]
|
|
776
|
+
}))
|
|
777
|
+
);
|
|
778
|
+
}
|
|
728
779
|
var DISTINCTIVE_SITUATION_SHARE = 0.02;
|
|
729
780
|
var DISTINCTIVE_FLOOR = Math.log(1 + 1 / DISTINCTIVE_SITUATION_SHARE);
|
|
730
781
|
var AGREEMENT_WEIGHT = 0.4;
|
|
@@ -785,6 +836,62 @@ function situationScore(query, situations, aliases, weights) {
|
|
|
785
836
|
const matchedSituation = readable.matchedSituation.length > 0 ? readable.matchedSituation : best >= RELEVANCE_FLOOR ? readable.bestReadableSituation : "";
|
|
786
837
|
return matchedSituation.length > 0 ? { matchedSituation, score: best } : { matchedSituation: "", score: 0 };
|
|
787
838
|
}
|
|
839
|
+
var EXACT_SYMBOL_LEAD = 4;
|
|
840
|
+
var NAME_BASE_LEAD = 2;
|
|
841
|
+
var NAME_SHARE_LEAD = 1.4;
|
|
842
|
+
var SYMBOL_WEIGHT_FLOOR = 4.2;
|
|
843
|
+
var SINGLE_WORD_SHARE_FLOOR = 0.3;
|
|
844
|
+
function scoreSymbolName(symbol, situation, queryTokens, weights) {
|
|
845
|
+
const name = [...new Set(nameWords(symbol))];
|
|
846
|
+
if (name.length === 0) return void 0;
|
|
847
|
+
const nameWeights = name.map((token) => weightOf(weights, token));
|
|
848
|
+
const specificity = nameWeights.reduce((sum, weight) => sum + weight, 0);
|
|
849
|
+
const requestTotal = [...queryTokens].reduce((sum, token) => sum + weightOf(weights, token), 0);
|
|
850
|
+
const share = requestTotal === 0 ? 0 : specificity / requestTotal;
|
|
851
|
+
const nameScore = NAME_BASE_LEAD + NAME_SHARE_LEAD * Math.min(1, share);
|
|
852
|
+
if (spellsName(situation, symbol)) {
|
|
853
|
+
if (normaliseName(situation) === normaliseName(symbol)) {
|
|
854
|
+
return { score: EXACT_SYMBOL_LEAD, specificity };
|
|
855
|
+
}
|
|
856
|
+
if (name.length === 1) {
|
|
857
|
+
if (weightOf(weights, name[0] ?? "") < SYMBOL_WEIGHT_FLOOR) return void 0;
|
|
858
|
+
if (share < SINGLE_WORD_SHARE_FLOOR) return void 0;
|
|
859
|
+
return { score: (NAME_BASE_LEAD + NAME_SHARE_LEAD) * Math.min(1, share), specificity };
|
|
860
|
+
}
|
|
861
|
+
return { score: nameScore, specificity };
|
|
862
|
+
}
|
|
863
|
+
if (name.length < 2) return void 0;
|
|
864
|
+
const queryWords = new Set(nameWords(situation));
|
|
865
|
+
if (!name.every((token) => queryWords.has(token))) return void 0;
|
|
866
|
+
if (Math.max(...nameWeights) < SYMBOL_WEIGHT_FLOOR) return void 0;
|
|
867
|
+
return { score: nameScore, specificity };
|
|
868
|
+
}
|
|
869
|
+
var SUMMARY_WEIGHT = 0.4;
|
|
870
|
+
function summaryScore(summary, queryTokens, queryText, weights) {
|
|
871
|
+
const candidate = scorePhrase(summary, queryTokens, queryText, weights);
|
|
872
|
+
return candidate === void 0 ? 0 : candidate.score * SUMMARY_WEIGHT;
|
|
873
|
+
}
|
|
874
|
+
function capabilityScore(query, entry, weights, nameWeights, situation) {
|
|
875
|
+
const situations = {
|
|
876
|
+
...situationScore(query, entry.situations, entry.aliases, weights),
|
|
877
|
+
specificity: 0
|
|
878
|
+
};
|
|
879
|
+
if (query.length === 0) return situations;
|
|
880
|
+
const queryTokens = new Set(query);
|
|
881
|
+
const symbol = scoreSymbolName(entry.symbol, situation, queryTokens, nameWeights);
|
|
882
|
+
const summary = summaryScore(entry.summary, queryTokens, query.join(" "), nameWeights);
|
|
883
|
+
const symbolScore = symbol?.score ?? 0;
|
|
884
|
+
const best = Math.max(situations.score, symbolScore, summary);
|
|
885
|
+
if (best <= situations.score) return situations;
|
|
886
|
+
if (symbol !== void 0 && symbolScore >= best) {
|
|
887
|
+
return { matchedSituation: entry.symbol, score: symbolScore, specificity: symbol.specificity };
|
|
888
|
+
}
|
|
889
|
+
return {
|
|
890
|
+
matchedSituation: situations.matchedSituation || entry.situations[0] || entry.summary,
|
|
891
|
+
score: best,
|
|
892
|
+
specificity: 0
|
|
893
|
+
};
|
|
894
|
+
}
|
|
788
895
|
function notOwnedSituationScore(query, situations) {
|
|
789
896
|
if (query.length === 0) return { matchedSituation: "", score: 0 };
|
|
790
897
|
const queryText = query.join(" ");
|
|
@@ -881,10 +988,19 @@ function withReferenceTools(situation, response) {
|
|
|
881
988
|
guidance: `Reverse engineer the game with engine_search_references, then engine_reference_detail for its pinned cards. ${response.guidance}`
|
|
882
989
|
};
|
|
883
990
|
}
|
|
991
|
+
var weightCache = /* @__PURE__ */ new WeakMap();
|
|
992
|
+
function manifestWeights(entries) {
|
|
993
|
+
let cached = weightCache.get(entries);
|
|
994
|
+
if (cached === void 0) {
|
|
995
|
+
cached = { weights: tokenWeights(entries), nameWeights: nameTokenWeights(entries) };
|
|
996
|
+
weightCache.set(entries, cached);
|
|
997
|
+
}
|
|
998
|
+
return cached;
|
|
999
|
+
}
|
|
884
1000
|
function searchMechanics(situation, manifest, scope) {
|
|
885
1001
|
const query = tokens(situation);
|
|
886
1002
|
const limit = scope === "request" ? MAX_COMPLETE_REQUEST_RESULTS : MAX_SITUATION_RESULTS;
|
|
887
|
-
const weights =
|
|
1003
|
+
const { weights, nameWeights } = manifestWeights(manifest.entries);
|
|
888
1004
|
const notOwned = notOwnedMatch(manifest, query);
|
|
889
1005
|
if (notOwned !== void 0 && isSpecificNotOwnedMatch(query, notOwned.matchedSituation)) {
|
|
890
1006
|
return {
|
|
@@ -893,10 +1009,10 @@ function searchMechanics(situation, manifest, scope) {
|
|
|
893
1009
|
verdict: "none"
|
|
894
1010
|
};
|
|
895
1011
|
}
|
|
896
|
-
const results = manifest.entries.map((entry) => ({ entry, ...
|
|
1012
|
+
const results = manifest.entries.map((entry) => ({ entry, ...capabilityScore(query, entry, weights, nameWeights, situation) })).filter(
|
|
897
1013
|
({ matchedSituation, score }) => matchedSituation.length > 0 && score >= RELEVANCE_FLOOR
|
|
898
1014
|
).sort(
|
|
899
|
-
(left, right) => right.score - left.score || `${left.entry.importPath}:${left.entry.symbol}`.localeCompare(
|
|
1015
|
+
(left, right) => right.score - left.score || right.specificity - left.specificity || `${left.entry.importPath}:${left.entry.symbol}`.localeCompare(
|
|
900
1016
|
`${right.entry.importPath}:${right.entry.symbol}`
|
|
901
1017
|
)
|
|
902
1018
|
).filter(
|
|
@@ -905,11 +1021,14 @@ function searchMechanics(situation, manifest, scope) {
|
|
|
905
1021
|
) === index
|
|
906
1022
|
).slice(0, limit).map(({ entry, matchedSituation, score }) => ({
|
|
907
1023
|
constraints: entry.constraints,
|
|
1024
|
+
...entry.deprecated === void 0 ? {} : { deprecated: entry.deprecated },
|
|
908
1025
|
example: entry.example,
|
|
909
1026
|
importPath: entry.importPath,
|
|
910
1027
|
matchedSituation,
|
|
1028
|
+
...entry.overrides === void 0 ? {} : { overrides: entry.overrides },
|
|
911
1029
|
...entry.requires === void 0 ? {} : { requires: entry.requires },
|
|
912
1030
|
score,
|
|
1031
|
+
signature: entry.signature,
|
|
913
1032
|
summary: entry.summary,
|
|
914
1033
|
symbol: entry.symbol
|
|
915
1034
|
}));
|
|
@@ -944,7 +1063,7 @@ var TOOL_DEFINITIONS = [
|
|
|
944
1063
|
{
|
|
945
1064
|
annotations: { destructiveHint: false, openWorldHint: false, readOnlyHint: true },
|
|
946
1065
|
name: "engine_search_capabilities",
|
|
947
|
-
description: 'Search the installed engine by concrete gameplay mechanic. Decompose genres first. Use scope "request" for the mechanically explicit full request and "mechanic" for each focused search; matchedSituation and score explain every result. The response verdict "none" is an actionable answer with guidance, not a failed search.',
|
|
1066
|
+
description: 'Search the installed engine by concrete gameplay mechanic or by an exact exported symbol name. Decompose genres first. Use scope "request" for the mechanically explicit full request and "mechanic" for each focused search; matchedSituation and score explain every result. A row carries the answer (importPath, signature, example, constraints, overrides, deprecations), so call engine_capability_detail only for a symbol the search did not return. The response verdict "none" is an actionable answer with guidance, not a failed search.',
|
|
948
1067
|
inputSchema: {
|
|
949
1068
|
additionalProperties: false,
|
|
950
1069
|
properties: {
|
|
@@ -1073,7 +1192,7 @@ function writeLine(value) {
|
|
|
1073
1192
|
`);
|
|
1074
1193
|
}
|
|
1075
1194
|
function toolText(value) {
|
|
1076
|
-
return { content: [{ text: JSON.stringify(value
|
|
1195
|
+
return { content: [{ text: JSON.stringify(value), type: "text" }] };
|
|
1077
1196
|
}
|
|
1078
1197
|
async function searchReferences(situation, limit = 5) {
|
|
1079
1198
|
const local = loadLocalReferenceGames();
|
|
@@ -1266,7 +1385,7 @@ async function handleLine(line2, manifestFile) {
|
|
|
1266
1385
|
capabilities: { tools: { listChanged: false } },
|
|
1267
1386
|
instructions: AUTHORING_INSTRUCTIONS,
|
|
1268
1387
|
protocolVersion: "2025-06-18",
|
|
1269
|
-
serverInfo: { name: "threenative-engine-mcp", version: "0.2.
|
|
1388
|
+
serverInfo: { name: "threenative-engine-mcp", version: "0.2.15" }
|
|
1270
1389
|
});
|
|
1271
1390
|
}
|
|
1272
1391
|
if (request.method === "tools/list") {
|
|
@@ -1293,7 +1412,12 @@ async function runCli(argv, manifestFile = defaultManifestPath(), io = {
|
|
|
1293
1412
|
{ arguments: JSON.parse(json), name },
|
|
1294
1413
|
manifestFile
|
|
1295
1414
|
);
|
|
1296
|
-
|
|
1415
|
+
let text2 = result.content[0].text;
|
|
1416
|
+
try {
|
|
1417
|
+
text2 = JSON.stringify(JSON.parse(text2), null, 2);
|
|
1418
|
+
} catch {
|
|
1419
|
+
}
|
|
1420
|
+
io.stdout(`${text2}
|
|
1297
1421
|
`);
|
|
1298
1422
|
return 0;
|
|
1299
1423
|
} catch (error) {
|
package/mcp/servers.mjs
CHANGED
|
@@ -51,11 +51,11 @@ export const MCP_SERVERS = Object.freeze({
|
|
|
51
51
|
* separately. The pinned engine version remains an emergency fallback for a legacy development
|
|
52
52
|
* checkout whose bundle has not been built. */
|
|
53
53
|
export const MCP_PACKAGES = Object.freeze({
|
|
54
|
-
assets: Object.freeze({ name: "threenative-asset-mcp", version: "0.
|
|
55
|
-
terrain: Object.freeze({ name: "@threenative/terrain", version: "0.1.
|
|
54
|
+
assets: Object.freeze({ name: "threenative-asset-mcp", version: "0.16.0" }),
|
|
55
|
+
terrain: Object.freeze({ name: "@threenative/terrain", version: "0.1.11" }),
|
|
56
56
|
sculpt: Object.freeze({ name: "threenative-sculpt-mcp", version: "0.2.2" }),
|
|
57
|
-
engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.
|
|
58
|
-
animation: Object.freeze({ name: "threenative-animation-mcp", version: "0.1.
|
|
57
|
+
engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.15" }),
|
|
58
|
+
animation: Object.freeze({ name: "threenative-animation-mcp", version: "0.1.12" }),
|
|
59
59
|
// `args` fixes the launch for every host. The Chrome flags are `WEBGPU_BROWSER_ARGS` from
|
|
60
60
|
// `@threenative/playtest`, so a DevTools trace profiles the same adapter a playtest does and not
|
|
61
61
|
// SwiftShader. An isolated profile keeps the user's own Chrome profile out, and the two opt-outs
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threenative/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.15",
|
|
4
4
|
"license": "MIT AND GPL-2.0-or-later",
|
|
5
5
|
"description": "The small vanilla Three.js game runtime foundation.",
|
|
6
6
|
"keywords": [
|
|
@@ -71,6 +71,10 @@
|
|
|
71
71
|
"types": "./dist/world.d.ts",
|
|
72
72
|
"import": "./dist/world.js"
|
|
73
73
|
},
|
|
74
|
+
"./render/environment": {
|
|
75
|
+
"types": "./dist/render-environment.d.ts",
|
|
76
|
+
"import": "./dist/render-environment.js"
|
|
77
|
+
},
|
|
74
78
|
"./net": {
|
|
75
79
|
"types": "./dist/net.d.ts",
|
|
76
80
|
"import": "./dist/net.js"
|
|
@@ -93,7 +97,7 @@
|
|
|
93
97
|
"chrome-devtools-mcp": "1.11.0",
|
|
94
98
|
"three": "0.187.0",
|
|
95
99
|
"three-mesh-bvh": "0.9.14",
|
|
96
|
-
"threenative-asset-mcp": "0.
|
|
100
|
+
"threenative-asset-mcp": "0.16.0",
|
|
97
101
|
"threenative-sculpt-mcp": "0.2.2",
|
|
98
102
|
"zustand": "5.0.14"
|
|
99
103
|
},
|
|
@@ -107,12 +111,12 @@
|
|
|
107
111
|
"tsup": "8.5.1",
|
|
108
112
|
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
109
113
|
"@typescript/native": "npm:typescript@7.0.2",
|
|
110
|
-
"@threenative/playtest": "0.3.
|
|
111
|
-
"threenative-engine-mcp": "0.2.
|
|
112
|
-
"threenative-animation-mcp": "0.1.
|
|
114
|
+
"@threenative/playtest": "0.3.15",
|
|
115
|
+
"threenative-engine-mcp": "0.2.15",
|
|
116
|
+
"threenative-animation-mcp": "0.1.12"
|
|
113
117
|
},
|
|
114
118
|
"peerDependencies": {
|
|
115
|
-
"@threenative/playtest": ">=0.3.
|
|
119
|
+
"@threenative/playtest": ">=0.3.15 <0.4.0",
|
|
116
120
|
"react": ">=19.2.0 <20",
|
|
117
121
|
"react-reconciler": ">=0.33.0 <0.34"
|
|
118
122
|
},
|
package/scripts/ensure-mcp.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { pathToFileURL } from "node:url";
|
|
4
5
|
// Installing ThreeNative wires its MCP servers into the project. An agent authoring a game here
|
|
@@ -39,5 +40,9 @@ export function runMcpSetup(environment = process.env, cwd = process.cwd()) {
|
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
const entry = process.argv[1];
|
|
42
|
-
|
|
43
|
+
// Node resolves the main module's symlinks, and pnpm links core into node_modules, so compare real paths.
|
|
44
|
+
if (
|
|
45
|
+
entry !== undefined &&
|
|
46
|
+
pathToFileURL(realpathSync(path.resolve(entry))).href === import.meta.url
|
|
47
|
+
)
|
|
43
48
|
runMcpSetup();
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRD-828: the frame's animation work, queued and then run in one crossing.
|
|
3
|
+
*
|
|
4
|
+
* A rig's per-frame loop reads and writes engine state per action — the stress lab measured 1,323
|
|
5
|
+
* crossings a frame, eight of the ten busiest classes inside `AnimationPlayer.update`, `#syncStride`
|
|
6
|
+
* and `#evaluate`. The backend can run that whole loop in C++ (`tn_anim_tick`), so a player that can
|
|
7
|
+
* be described by data queues a descriptor here instead of crossing per property, and the frame calls
|
|
8
|
+
* one flush.
|
|
9
|
+
*
|
|
10
|
+
* The fallback is not a mode: when the backend installs no executor (a surface-only runtime, or a
|
|
11
|
+
* build without the entry point), nothing is ever queued and every player keeps its own loop.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** One rig, in the terms the batch entry takes. Numbers only: the backend resolves the objects. */
|
|
15
|
+
export interface IAnimationTickRig {
|
|
16
|
+
readonly mixer: object;
|
|
17
|
+
/** The rig's current action, or null for a rig with nothing playing (its mixer still steps). */
|
|
18
|
+
readonly action: object | null;
|
|
19
|
+
/** The body the stride is measured from, or null to measure none. */
|
|
20
|
+
readonly strideRoot: object | null;
|
|
21
|
+
/** The interval the body's movement is divided by: a held tick banks its own `dt` into this. */
|
|
22
|
+
readonly dt: number;
|
|
23
|
+
/** This tick's own time. The engine banks it at the rate in force; the caller never reads a scale back. */
|
|
24
|
+
readonly elapsed: number;
|
|
25
|
+
/** True on the tick that poses the rig; a held tick measures the stride and advances nothing. */
|
|
26
|
+
readonly step: boolean;
|
|
27
|
+
/** The player spent ticks this batch did not, so the banked advance the engine holds is already spent. */
|
|
28
|
+
readonly reset: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* The rate this rule last applied to the action, or 0 when its scale is the game's own. The engine is
|
|
31
|
+
* the only writer of a rate, but the player is the side that knows whether it wrote one.
|
|
32
|
+
*/
|
|
33
|
+
readonly lastRate: number;
|
|
34
|
+
/** Metres of ground the clip covers per clip-second, measured when the clip was analysed. */
|
|
35
|
+
readonly clipGroundSpeed: number;
|
|
36
|
+
readonly strideSync: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What the batch did with one rig, read back in the order the rigs were queued. */
|
|
40
|
+
export interface IAnimationTickResult {
|
|
41
|
+
readonly strideRate: number;
|
|
42
|
+
readonly groundSpeed: number;
|
|
43
|
+
readonly finished: boolean;
|
|
44
|
+
readonly changed: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The backend's entry point, installed on `globalThis` by `@threenative/three-native`'s web backend. */
|
|
48
|
+
export type AnimationTickExecutor = (
|
|
49
|
+
rigs: readonly IAnimationTickRig[],
|
|
50
|
+
status: Float64Array,
|
|
51
|
+
) => void;
|
|
52
|
+
|
|
53
|
+
const EXECUTOR_KEY = "__tnAnimationTick";
|
|
54
|
+
/** 3 doubles per rig: stride rate, ground speed, flags (bit 0 finished, bit 1 changed). */
|
|
55
|
+
const STATUS_STRIDE = 3;
|
|
56
|
+
|
|
57
|
+
/** The executor this realm's backend installed, or undefined when it batches nothing. */
|
|
58
|
+
export function animationTickExecutor(): AnimationTickExecutor | undefined {
|
|
59
|
+
const host = globalThis as { [EXECUTOR_KEY]?: unknown };
|
|
60
|
+
const candidate = host[EXECUTOR_KEY];
|
|
61
|
+
return typeof candidate === "function" ? (candidate as AnimationTickExecutor) : undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface IQueuedRig {
|
|
65
|
+
readonly rig: IAnimationTickRig;
|
|
66
|
+
apply(result: IAnimationTickResult): void;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const queue: IQueuedRig[] = [];
|
|
70
|
+
const pending: IAnimationTickRig[] = [];
|
|
71
|
+
let status = new Float64Array(STATUS_STRIDE * 256);
|
|
72
|
+
|
|
73
|
+
/** Queues one rig for this frame's batch. Called from `AnimationPlayer.update`. */
|
|
74
|
+
export function queueAnimationTick(
|
|
75
|
+
rig: IAnimationTickRig,
|
|
76
|
+
apply: (result: IAnimationTickResult) => void,
|
|
77
|
+
): void {
|
|
78
|
+
queue.push({ rig, apply });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** How many rigs are waiting for the flush (a player that wants to know whether it queued). */
|
|
82
|
+
export function queuedAnimationTicks(): number {
|
|
83
|
+
return queue.length;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Runs every queued rig in one call and hands each its result. Returns the number of batches run (0 or
|
|
88
|
+
* 1), which is the frame's crossing count for animation.
|
|
89
|
+
*
|
|
90
|
+
* Fail closed on the shape: a backend that answers a different number of rigs than it was given would
|
|
91
|
+
* silently leave a rig unadvanced, so that throws instead.
|
|
92
|
+
*/
|
|
93
|
+
export function flushAnimationTicks(): number {
|
|
94
|
+
const count = queue.length;
|
|
95
|
+
if (count === 0) return 0;
|
|
96
|
+
const executor = animationTickExecutor();
|
|
97
|
+
if (executor === undefined) {
|
|
98
|
+
// Nothing to run it: the players that queued took the data path only because availability was
|
|
99
|
+
// checked at queue time, so this is a backend that uninstalled mid-frame.
|
|
100
|
+
queue.length = 0;
|
|
101
|
+
pending.length = 0;
|
|
102
|
+
throw new Error("TN_ANIM_TICK_EXECUTOR_GONE: a rig was queued and no executor is installed.");
|
|
103
|
+
}
|
|
104
|
+
if (status.length < count * STATUS_STRIDE) status = new Float64Array(count * STATUS_STRIDE);
|
|
105
|
+
pending.length = count;
|
|
106
|
+
for (let i = 0; i < count; i += 1) {
|
|
107
|
+
const entry = queue[i];
|
|
108
|
+
if (entry !== undefined) pending[i] = entry.rig;
|
|
109
|
+
}
|
|
110
|
+
countEngineBatch(1);
|
|
111
|
+
try {
|
|
112
|
+
executor(pending, status);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
// A failed call leaves the rigs unadvanced and their descriptors stale: dropping them is the only
|
|
115
|
+
// state that cannot advance a rig twice, and the throw still reaches the caller.
|
|
116
|
+
queue.length = 0;
|
|
117
|
+
pending.length = 0;
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
for (let i = 0; i < count; i += 1) {
|
|
121
|
+
const at = i * STATUS_STRIDE;
|
|
122
|
+
const flags = status[at + 2] as number;
|
|
123
|
+
queue[i]?.apply({
|
|
124
|
+
strideRate: status[at] as number,
|
|
125
|
+
groundSpeed: status[at + 1] as number,
|
|
126
|
+
finished: (flags & 1) !== 0,
|
|
127
|
+
changed: (flags & 2) !== 0,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
queue.length = 0;
|
|
131
|
+
pending.length = 0;
|
|
132
|
+
return 1;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* One batch is one crossing for a whole frame's rigs; a reader that settles the queue mid-frame turns
|
|
137
|
+
* that into one batch per rig, which is a bug that looks like a slow engine. Counted where the playtest
|
|
138
|
+
* bounds read it (`TN_FRAME_BUDGET.counters.engine`), so a regression names itself.
|
|
139
|
+
*/
|
|
140
|
+
function countEngineBatch(batches: number): void {
|
|
141
|
+
const host = globalThis as { __tnEngineCost?: Record<string, number> };
|
|
142
|
+
if (host.__tnEngineCost === undefined) host.__tnEngineCost = {};
|
|
143
|
+
const bag = host.__tnEngineCost;
|
|
144
|
+
bag.animationTickBatches = (bag.animationTickBatches ?? 0) + batches;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Drops the queue without running it: a scene teardown must not advance rigs it is destroying. */
|
|
148
|
+
export function clearAnimationTicks(): void {
|
|
149
|
+
queue.length = 0;
|
|
150
|
+
pending.length = 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The queue is what turns N per-rig loops into one call: the smallest check that fails if the
|
|
155
|
+
* read-back stops lining up with the rigs that were queued.
|
|
156
|
+
*/
|
|
157
|
+
export function demo(): string {
|
|
158
|
+
const seen: number[] = [];
|
|
159
|
+
const saved = (globalThis as { [EXECUTOR_KEY]?: unknown })[EXECUTOR_KEY];
|
|
160
|
+
(globalThis as { [EXECUTOR_KEY]?: unknown })[EXECUTOR_KEY] = (
|
|
161
|
+
rigs: readonly IAnimationTickRig[],
|
|
162
|
+
out: Float64Array,
|
|
163
|
+
) => {
|
|
164
|
+
for (let i = 0; i < rigs.length; i += 1) {
|
|
165
|
+
out[i * STATUS_STRIDE] = (rigs[i] as IAnimationTickRig).dt * 10;
|
|
166
|
+
out[i * STATUS_STRIDE + 1] = 2;
|
|
167
|
+
out[i * STATUS_STRIDE + 2] = 3;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
try {
|
|
171
|
+
const rig = (dt: number): IAnimationTickRig => ({
|
|
172
|
+
mixer: {},
|
|
173
|
+
action: null,
|
|
174
|
+
strideRoot: null,
|
|
175
|
+
dt,
|
|
176
|
+
elapsed: dt,
|
|
177
|
+
step: true,
|
|
178
|
+
reset: false,
|
|
179
|
+
lastRate: 0,
|
|
180
|
+
clipGroundSpeed: 1,
|
|
181
|
+
strideSync: true,
|
|
182
|
+
});
|
|
183
|
+
queueAnimationTick(rig(0.1), (result) => seen.push(result.strideRate));
|
|
184
|
+
queueAnimationTick(rig(0.2), (result) => seen.push(result.strideRate));
|
|
185
|
+
if (queuedAnimationTicks() !== 2) throw new Error("queue length");
|
|
186
|
+
if (flushAnimationTicks() !== 1) throw new Error("one batch");
|
|
187
|
+
if (seen.join(",") !== "1,2") throw new Error(`read-back order: ${seen.join(",")}`);
|
|
188
|
+
if (queuedAnimationTicks() !== 0) throw new Error("queue drained");
|
|
189
|
+
return "demo: ok";
|
|
190
|
+
} finally {
|
|
191
|
+
(globalThis as { [EXECUTOR_KEY]?: unknown })[EXECUTOR_KEY] = saved;
|
|
192
|
+
}
|
|
193
|
+
}
|