mjswan 0.7.0 → 0.7.1-beta.1

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.
@@ -15594,4 +15594,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
15594
15594
  }`},JK=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(Q.areEqual(t,n)&&Q.areEqual(n,r)),o=t,s=Q.size(t);if(a){let e=lR.calcShape(lR.calcShape(t,n,!1),r,!1);if(!e)throw Error(`Can't perform where op on the given tensors`);o=e,s=Q.size(o)}let c=Math.ceil(s/4);return{name:`Where`,shaderCache:{inputDependencies:[`rank`,`rank`,`rank`]},getShaderSource:t=>qK(t,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(s/64/4)},programUniforms:[{type:12,data:c},...ZR(r,t,n,o)]})}},YK=e=>{e.compute(JK(e.inputs))}}),ZK,QK=Z(()=>{yB(),OB(),NB(),LB(),NV(),qV(),eH(),qH(),aU(),lU(),hU(),DU(),NU(),IU(),VU(),GU(),XU(),tW(),oW(),xW(),qW(),QW(),nG(),aG(),dG(),kW(),xG(),VG(),KG(),XG(),tK(),mB(),SK(),VW(),EK(),FK(),BK(),LW(),KK(),yz(),kV(),XK(),ZK=new Map([[`Abs`,[BB]],[`Acos`,[VB]],[`Acosh`,[HB]],[`Add`,[LV]],[`ArgMax`,[_B,vB]],[`ArgMin`,[gB,vB]],[`Asin`,[UB]],[`Asinh`,[WB]],[`Atan`,[GB]],[`Atanh`,[KB]],[`Attention`,[DB]],[`AveragePool`,[MG,jG]],[`BatchNormalization`,[MB]],[`BiasAdd`,[IB]],[`BiasSplitGelu`,[MV]],[`Cast`,[JB,qB]],[`Ceil`,[ZB]],[`Clip`,[XB]],[`Concat`,[QV,$V]],[`Conv`,[KH,HH]],[`ConvTranspose`,[iU,eU]],[`Cos`,[QB]],[`Cosh`,[$B]],[`CumSum`,[sU,cU]],[`DepthToSpace`,[pU,mU]],[`DequantizeLinear`,[WG,GG]],[`Div`,[RV]],[`Einsum`,[TU,EU]],[`Elu`,[tV,eV]],[`Equal`,[zV]],[`Erf`,[rV]],[`Exp`,[iV]],[`Expand`,[MU]],[`FastGelu`,[FU]],[`Floor`,[aV]],[`FusedConv`,[KH,HH]],[`Gather`,[BU,zU]],[`GatherElements`,[eW,$U]],[`GatherBlockQuantized`,[JU,YU]],[`GatherND`,[UU,WU]],[`Gelu`,[oV]],[`Gemm`,[aW,iW]],[`GlobalAveragePool`,[FG,PG]],[`GlobalMaxPool`,[BG,zG]],[`Greater`,[UV]],[`GreaterOrEqual`,[GV]],[`GridSample`,[yW,bW]],[`GroupQueryAttention`,[KW]],[`HardSigmoid`,[mV,pV]],[`InstanceNormalization`,[ZW]],[`LayerNormalization`,[tG]],[`LeakyRelu`,[sV,eV]],[`Less`,[WV]],[`LessOrEqual`,[KV]],[`Log`,[TV]],[`MatMul`,[iG]],[`MatMulNBits`,[lG,uG]],[`MaxPool`,[LG,RG]],[`Mul`,[BV]],[`MultiHeadAttention`,[OW,wW]],[`Neg`,[lV]],[`Not`,[cV]],[`Pad`,[bG]],[`Pow`,[VV]],[`QuickGelu`,[OV,eV]],[`Range`,[YG]],[`Reciprocal`,[uV]],[`ReduceMin`,[lB]],[`ReduceMean`,[iB]],[`ReduceMax`,[cB]],[`ReduceSum`,[dB]],[`ReduceProd`,[uB]],[`ReduceL1`,[aB]],[`ReduceL2`,[oB]],[`ReduceLogSum`,[pB]],[`ReduceLogSumExp`,[sB]],[`ReduceSumSquare`,[fB]],[`Relu`,[dV]],[`Resize`,[bK,xK]],[`RotaryEmbedding`,[BW]],[`ScatterND`,[eK,$G]],[`Sigmoid`,[fV]],[`Sin`,[hV]],[`Sinh`,[gV]],[`Slice`,[NK,PK]],[`SkipLayerNormalization`,[TK]],[`Split`,[FW,IW]],[`Sqrt`,[_V]],[`Softmax`,[RK,zK]],[`Sub`,[HV]],[`Tan`,[vV]],[`Tanh`,[bV]],[`ThresholdedRelu`,[wV,eV]],[`Tile`,[GK]],[`Transpose`,[_z,vz]],[`Where`,[YK]]])}),$K,eq=Z(()=>{qI(),sR(),lz(),$K=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){PI(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let s=[];for(let e of t)s.push({binding:s.length,resource:{buffer:e.buffer}});for(let e of n)s.push({binding:s.length,resource:{buffer:e.buffer}});i&&s.push({binding:s.length,resource:i});let c=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:s,label:e.programInfo.name});if(this.backend.sessionStatus===`capturing`){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:c,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}o.setPipeline(e.computePipeline),o.setBindGroup(0,c),o.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType===`at-passes`)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),FI(e.programInfo.name)}dispose(){}build(e,t){PI(e.name);let n=this.backend.device,r=[];[{feature:`shader-f16`,extension:`f16`},{feature:`subgroups`,extension:`subgroups`}].forEach(e=>{n.features.has(e.feature)&&r.push(`enable ${e.extension};`)});let i=cz(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${r.join(`
15595
15595
  `)}
15596
15596
  ${i.additionalImplementations}
15597
- ${a}`,s=n.createShaderModule({code:o,label:e.name});oR(`verbose`,()=>`[WebGPU] ${e.name} shader code: ${o}`);let c=n.createComputePipeline({compute:{module:s,entryPoint:`main`},layout:`auto`,label:e.name});return FI(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e==`number`?e:e.x,n=typeof e==`number`?1:e.y||1,r=typeof e==`number`?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw Error(`Total dispatch size exceeds WebGPU maximum.`);return[o,o,o]}else return[o,o,1]}}}),tq={};qF(tq,{WebGpuBackend:()=>aq});var nq,rq,iq,aq,oq=Z(()=>{qI(),ZL(),sR(),gR(),UR(),QK(),eq(),nq=(e,t)=>{if(t.length!==e.length)throw Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let i=e[r].dataType;switch(t[r]){case`none`:n.push(``);break;case`type`:n.push(`${i}`);break;case`rank`:{let t=e[r].dims.length;n.push(`${i};${t}`);break}case`dims`:{let t=e[r].dims.join(`,`);n.push(`${i};${t}`);break}default:throw Error(`unsupported input dependency: ${t[r]}`)}}return n.join(`|`)},rq=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+=`[`+e.shaderCache.hint+`]`),r+=`:`+n+`:${nq(t,e.shaderCache?.inputDependencies??Array(t.length).fill(`dims`))}`,r},iq=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},aq=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus=`default`,this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw Error(`currentKernelCustomData(): currentKernelId is null. (should not happen)`);let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i(`chromium-experimental-timestamp-query-inside-passes`)||i(`timestamp-query`),i(`shader-f16`),i(`subgroups`),this.device=await t.requestDevice(r),this.adapterInfo=new iq(t.info||await t.requestAdapterInfo()),this.gpuDataManager=HR(this),this.programManager=new $K(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,iR(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<`u`&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||=this.device.createCommandEncoder(),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType===`at-passes`&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&=(this.computePassEncoder.end(),null)}flush(){if(!this.commandEncoder)return;PI(),this.endComputePass();let e;this.queryType!==`none`&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==`none`&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],i=r.kernelId,a=this.kernels.get(i),o=a.kernelType,s=a.kernelName,c=r.programName,l=r.inputTensorViews,u=r.outputTensorViews,d=t[e*2],f=t[e*2+1];typeof this.queryTimeBase>`u`&&(this.queryTimeBase=d);let p=Number(d-this.queryTimeBase),m=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(m))throw RangeError(`incorrect timestamp range`);if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:WL(e.dataType)})),outputsMetadata:u.map(e=>({dims:e.dims,dataType:WL(e.dataType)})),kernelId:i,kernelType:o,kernelName:s,programName:c,startTime:p,endTime:m});else{let e=``;l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${WL(t.dataType)}, `});let t=``;u.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${WL(e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${s}|${c}" ${e}${t}start time: ${p} ns, execution time: ${m-p} ns`)}MI(`GPU`,`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),FI()}run(e,t,n,r,i,a){PI(e.name);let o=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(n===0)continue;let r=this.gpuDataManager.get(n);if(!r)throw Error(`no GPU data for input: ${n}`);o.push(r)}let{outputs:s,dispatchGroup:c,programUniforms:l}=e.getRunData(t),u=n.length===0?s.map((e,t)=>t):n;if(u.length!==s.length)throw Error(`Output size ${u.length} must be equal to ${s.length}.`);let d=[],f=[];for(let e=0;e<s.length;++e){if(!Number.isInteger(u[e])||u[e]<-3||u[e]>=a)throw Error(`Invalid output index: ${u[e]}`);if(u[e]===-3)continue;let t=u[e]===-1,n=u[e]===-2,o=t||n?i(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(d.push(o),o.data===0)continue;let c=this.gpuDataManager.get(o.data);if(!c)throw Error(`no GPU data for output: ${o.data}`);if(t&&this.temporaryData.push(c),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(c)}f.push(c)}if(o.length!==t.length||f.length!==d.length){if(f.length===0)return FI(e.name),d;throw Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let p;if(l){let e=0,t=[];l.forEach(n=>{let r=typeof n.data==`number`?[n.data]:n.data;if(r.length===0)return;let i=n.type===10?2:4,a,o;n.type===10?(o=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(o=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/o)*o,t.push(e);let s=n.type===10?8:4;e+=r.length>4?Math.ceil(r.length/s)*a:r.length*i}),e=Math.ceil(e/16)*16;let n=new ArrayBuffer(e);l.forEach((e,r)=>{let i=t[r],a=typeof e.data==`number`?[e.data]:e.data;if(e.type===6)new Int32Array(n,i,a.length).set(a);else if(e.type===12)new Uint32Array(n,i,a.length).set(a);else if(e.type===10)new Uint16Array(n,i,a.length).set(a);else if(e.type===1)new Float32Array(n,i,a.length).set(a);else throw Error(`Unsupported uniform type: ${WL(e.type)}`)});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,n,0,e),this.gpuDataManager.release(r.id),p={offset:0,size:e,buffer:r.buffer}}let m=this.programManager.normalizeDispatchGroupSize(c),h=m[1]===1&&m[2]===1,g=rq(e,t,h),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),oR(`info`,()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&_.uniformVariablesInfo){if(l.length!==_.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${l.length} in program "${_.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r=typeof t.data==`number`?1:t.data.length,[i,a]=_.uniformVariablesInfo[e];if(n!==i||r!==a)throw Error(`Uniform variable ${e} mismatch: expect type ${i} with size ${a}, got type ${n} with size ${r} in program "${_.programInfo.name}".`)}}if(oR(`info`,()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!==`none`||this.sessionStatus===`capturing`){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(e),this.sessionStatus===`capturing`&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,o,f,m,p),FI(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=ZK.get(e);if(!i)throw Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,o=r.kernelEntry,s=r.attributes;if(this.currentKernelId!==null)throw Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&=(s[1]=s[0](s[1]),void 0),oR(`info`,()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(`validation`),o(t,s[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{c&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[o,n]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await BR(this,e,t);return hR(r.buffer,n)}}writeTimestamp(e){this.queryType===`inside-passes`&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType=`none`,(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>`u`?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(`chromium-experimental-timestamp-query-inside-passes`)?this.queryType=`inside-passes`:this.device.features.has(`timestamp-query`)&&(this.queryType=`at-passes`),this.queryType!==`none`&&typeof this.querySet>`u`&&(this.querySet=this.device.createQuerySet({type:`timestamp`,count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){oR(`info`,`captureBegin`),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=`capturing`}captureEnd(){oR(`info`,`captureEnd`),this.flush(),this.sessionStatus=`default`}replay(){oR(`info`,`replay`),this.sessionStatus=`replaying`;let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),i=e[r];this.writeTimestamp(this.pendingDispatchNumber*2),n.setPipeline(i.computePipeline),n.setBindGroup(0,i.bindGroup),n.dispatchWorkgroups(...i.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!==`none`&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType===`at-passes`)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=`default`}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),sq={};qF(sq,{init:()=>uq});var cq,lq,uq,dq=Z(()=>{ZL(),sR(),mR(),MR(),cq=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(this.dataType!==1)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(Q.size(t)!==Q.size(this.dims))throw Error(`Invalid new shape`);return new e(this.module,this.dataType,this.data,t)}},lq=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=r===4?`i32`:`i64`;this.opKernelContext=Number(e.getValue(r*i++,a));let o=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,`*`)),this.customDataSize=Number(e.getValue(r*i++,a));let s=[];for(let t=0;t<o;t++){let t=Number(e.getValue(r*i++,a)),n=Number(e.getValue(r*i++,`*`)),o=Number(e.getValue(r*i++,a)),c=[];for(let t=0;t<o;t++)c.push(Number(e.getValue(r*i++,a)));s.push(new cq(e,t,n,c))}this.inputs=s}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>typeof e==`number`?this.inputs[e]:e)??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,(e,t,n)=>new cq(this.module,t,this.output(e,n),n),(e,t)=>{let n=GL(e,t);if(!n)throw Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new cq(this.module,e,r,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=n===4?`i32`:`i64`,i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(i+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,i)}catch(n){throw Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},uq=async(e,t,n,r)=>{let i=t.jsepInit;if(!i)throw Error(`Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.`);if(e===`webgpu`){let e=(oq(),YF(tq)).WebGpuBackend,a=new e;await a.initialize(n,r),i(`webgpu`,[a,e=>a.alloc(Number(e)),e=>a.free(e),(e,n,r,i=!1)=>{if(i)oR(`verbose`,()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(e)}, dst=${Number(n)}, size=${Number(r)}`),a.memcpy(Number(e),Number(n));else{oR(`verbose`,()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(e)}, gpuDataId=${Number(n)}, size=${Number(r)}`);let i=t.HEAPU8.subarray(Number(e>>>0),Number(e>>>0)+Number(r));a.upload(Number(n),i)}},async(e,n,r)=>{oR(`verbose`,()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${e}, dataOffset=${n}, size=${r}`),await a.download(Number(e),()=>t.HEAPU8.subarray(Number(n)>>>0,Number(n+r)>>>0))},(e,n,r)=>a.createKernel(e,Number(n),r,t.UTF8ToString(t._JsepGetNodeName(Number(n)))),e=>a.releaseKernel(e),(e,n,r,i)=>{oR(`verbose`,()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${e}, contextDataOffset=${n}`);let o=new lq(t,a,Number(n));return a.computeKernel(Number(e),o,i)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let e=new jR(n);i(`webnn`,[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i,a)=>e.ensureTensor(t,n,r,i,a),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),fq,pq,mq,hq,gq,_q,vq,yq,bq,xq,Sq,Cq,wq,Tq=Z(()=>{qI(),FL(),HL(),ZL(),kL(),NL(),$L(),fq=(e,t)=>{OL()._OrtInit(e,t)!==0&&ML(`Can't initialize onnxruntime.`)},pq=async e=>{fq(e.wasm.numThreads,qL(e.logLevel))},mq=async(e,t)=>{OL().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);{let r=(dq(),YF(sq)).init;t===`webgpu`&&await r(`webgpu`,OL(),e,n),t===`webnn`&&await r(`webnn`,OL(),e)}},hq=new Map,gq=e=>{let t=OL(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&ML(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},_q=(e,t)=>{let n=OL(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&ML(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},vq=e=>{let t=OL(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},yq=async(e,t)=>{let n,r,i=OL();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=vq(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await VL(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(QL(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&ML(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=gq(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=_q(a,t);e===0&&ML(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:WL(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=_q(a,n+e);r===0&&ML(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:WL(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&ML(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>XL(e))}),hq.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&ML(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&ML(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ML(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},bq=e=>{let t=OL(),n=hq.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&ML(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&ML(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&ML(`Can't release session.`),hq.delete(e)},xq=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=OL(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=GL(UL(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=GL(UL(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,UL(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,AL(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=UL(l);m=GL(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(UL(l),p,m,g,u.length,XL(f));e===0&&ML(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Sq=async(e,t,n,r,i,a)=>{let o=OL(),s=o.PTR_SIZE,c=hq.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),D=o.stackAlloc(g*s);try{[_,v]=PL(a),II(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await xq(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await xq(i[t],b,x,e,d[r[t]],h+r[t],p);LI(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(T+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(E+e*s,b[e],`*`),o.setValue(D+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);II(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&ML(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&ML(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&ML(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}LI(`wasm bindInputsOutputs`),hq.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,E,_):await o._OrtRun(l,T,w,h,D,g,E,_),c!==0&&ML(`failed to call OrtRun().`);let C=[],O=[];II(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(E+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&ML(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&ML(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&ML(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=WL(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=GL(a,g);if(r===void 0||!JL(u))throw Error(`Unsupported data type: ${u}`);l=!0,C.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&ML(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(GL(a,g)===void 0||!YL(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,O.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(KL(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&ML(`Can't clear bound outputs.`),hq.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return LI(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},Cq=e=>{let t=OL(),n=hq.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&ML(`Can't get an profile file name.`),t._OrtFree(i)},wq=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Eq,Dq,Oq,kq,Aq,jq,Mq,Nq,Pq,Fq,Iq,Lq,Rq,zq,Bq,Vq,Hq,Uq,Wq=Z(()=>{qI(),Tq(),kL(),yL(),Eq=()=>!!cI.wasm.proxy&&typeof document<`u`,Oq=!1,kq=!1,Aq=!1,Nq=new Map,Pq=(e,t)=>{let n=Nq.get(e);n?n.push(t):Nq.set(e,[t])},Fq=()=>{if(Oq||!kq||Aq||!Dq)throw Error(`worker not ready`)},Iq=e=>{switch(e.data.type){case`init-wasm`:Oq=!1,e.data.err?(Aq=!0,Mq[1](e.data.err)):(kq=!0,Mq[0]()),jq&&=(URL.revokeObjectURL(jq),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Nq.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},Lq=async()=>{if(!kq){if(Oq)throw Error(`multiple calls to 'initWasm()' detected.`);if(Aq)throw Error(`previous call to 'initWasm()' failed.`);if(Oq=!0,Eq())return new Promise((e,t)=>{Dq?.terminate(),gL().then(([n,r])=>{try{Dq=r,Dq.onerror=e=>t(e),Dq.onmessage=Iq,Mq=[e,t];let i={type:`init-wasm`,in:cI};!i.in.wasm.wasmPaths&&(n||oL)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm`,``+import.meta.url).href}),Dq.postMessage(i),jq=n}catch(e){t(e)}},t)});try{await DL(cI.wasm),await pq(cI),kq=!0}catch(e){throw Aq=!0,e}finally{Oq=!1}}},Rq=async e=>{if(Eq())return Fq(),new Promise((t,n)=>{Pq(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:cI}};Dq.postMessage(r)});await mq(cI,e)},zq=async e=>Eq()?(Fq(),new Promise((t,n)=>{Pq(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Dq.postMessage(r,[e.buffer])})):vq(e),Bq=async(e,t)=>{if(Eq()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Fq(),new Promise((n,r)=>{Pq(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Dq.postMessage(i,a)})}else return yq(e,t)},Vq=async e=>{if(Eq())return Fq(),new Promise((t,n)=>{Pq(`release`,[t,n]);let r={type:`release`,in:e};Dq.postMessage(r)});bq(e)},Hq=async(e,t,n,r,i,a)=>{if(Eq()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Fq(),new Promise((i,o)=>{Pq(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Dq.postMessage(c,wq(s))})}else return Sq(e,t,n,r,i,a)},Uq=async e=>{if(Eq())return Fq(),new Promise((t,n)=>{Pq(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Dq.postMessage(r)});Cq(e)}}),Gq,Kq,qq,Jq=Z(()=>{qI(),Wq(),ZL(),JI(),$L(),Gq=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Kq=e=>{switch(e[3]){case`cpu`:return new AI(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!JL(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return AI.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!YL(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return AI.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},qq=class{async fetchModelAndCopyToWasmMemory(e){return zq(await QL(e))}async loadModel(e,t){PI();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Bq(n,t),FI()}async dispose(){return Vq(this.sessionId)}async run(e,t,n){PI();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Gq(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Gq(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Hq(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Kq(l[e]);return FI(),u}startProfiling(){}endProfiling(){Uq(this.sessionId)}}}),Yq={};qF(Yq,{OnnxruntimeWebAssemblyBackend:()=>Zq,initializeFlags:()=>Xq,wasmBackend:()=>Qq});var Xq,Zq,Qq,$q=Z(()=>{qI(),Wq(),Jq(),Xq=()=>{(typeof cI.wasm.initTimeout!=`number`||cI.wasm.initTimeout<0)&&(cI.wasm.initTimeout=0);let e=cI.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),cI.wasm.simd=!1),typeof cI.wasm.proxy!=`boolean`&&(cI.wasm.proxy=!1),typeof cI.wasm.trace!=`boolean`&&(cI.wasm.trace=!1),typeof cI.wasm.numThreads!=`number`||!Number.isInteger(cI.wasm.numThreads)||cI.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)cI.wasm.numThreads=1;else{let e=typeof navigator>`u`?KF(`node:os`).cpus().length:navigator.hardwareConcurrency;cI.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Zq=class{async init(e){Xq(),await Lq(),await Rq(e)}async createInferenceSessionHandler(e,t){let n=new qq;return await n.loadModel(e,t),n}},Qq=new Zq});qI(),qI(),qI();var eJ=`1.24.3`;{let e=($q(),YF(Yq)).wasmBackend;QF(`webgpu`,e,5),QF(`webnn`,e,5),QF(`cpu`,e,10),QF(`wasm`,e,10)}Object.defineProperty(cI.versions,"web",{value:eJ,enumerable:!0});var tJ=class{constructor(e,t){this.runner=e,this.config=t}},nJ=class extends tJ{constructor(e,t){super(e,t),this.store=new IF,this.cachedSize=null,this.graph=t.graph,this.params=t.params??{}}get size(){return this.cachedSize??this.inferSize()}reset(e){this.store.reset()}compute(e){let t=LF(this.graph,{runner:this.runner,state:e,params:this.params},this.store);if(t instanceof Float32Array)return this.cachedSize=t.length,t;if(typeof t==`number`)return this.cachedSize=1,new Float32Array([t]);if(typeof t==`boolean`)return this.cachedSize=1,new Float32Array([+!!t]);if(t instanceof Uint8Array){this.cachedSize=t.length;let e=new Float32Array(t.length);for(let n=0;n<t.length;n++)e[n]=t[n];return e}return this.cachedSize=0,new Float32Array}inferSize(){this.runner.getContext();let e={jointPos:new Float32Array(this.runner.getNumActions())};return this.compute(e),this.cachedSize??0}},rJ=class{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=e.policy_num_actions??this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(let t of Object.values(this.obsGroups))for(let n of t)n.reset&&n.reset(e);if(e){for(let[t,n]of Object.entries(this.historyConfig))if(n.steps>1){let r=this.buildFrame(this.obsGroups[t]??[],e),i=this.historyBuffers[t];for(let e=0;e<n.steps;e++)i.set(r,e*r.length)}}}update(e){this.policyModule?.update();for(let t of Object.values(this.obsGroups))for(let n of t)n.update&&n.update(e)}collectObservationsByKey(e){this.update(e);let t={};for(let[n,r]of Object.entries(this.obsGroups)){let i=this.historyConfig[n];if(i&&i.steps>1){let i=this.buildFrame(r,e),a=this.historyBuffers[n];for(let e=a.length-1;e>=i.length;e--)a[e]=a[e-i.length];a.set(i,0),t[n]=new Float32Array(a)}else t[n]=this.buildFrame(r,e)}return t}collectObservations(e){let t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];let n=Object.keys(t)[0];return n?t[n]:new Float32Array}async preloadAll(){let e=[];for(let t of Object.values(this.obsGroups))for(let n of t)typeof n.preload==`function`&&e.push(n.preload());await Promise.all(e)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];let e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(e=>({...e}));let e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(e=>({...e})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}getConfig(){return this.config}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){let t=this.options.policyModules??{},n=this.config.policy_module,r=n?t[n]:t.default;if(n&&!r)throw Error(`Unknown policy module: ${n}`);if(!r)return null;let i=new r(this.config);return await i.init(e),i}buildObservationGroups(){let e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;let n=t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new nJ(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);return new r(this,t)};for(let[r,i]of Object.entries(t)){if(Array.isArray(i)){let e=i.map(n);this.registerGroup(r,e,i);continue}if(i&&typeof i==`object`){let t=i;if(Array.isArray(t.components)){let n=t.components.map(t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new nJ(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);let i={...t,history_steps:1};return new r(this,i)}),i=Math.max(1,Math.floor(t.history_steps??1)),a=!!t.interleaved;this.registerGroup(r,n,t.components,{steps:i,interleaved:a})}}}this.obsGroups.policy?this.defaultObsKey=`policy`:this.obsGroups.observation?this.defaultObsKey=`observation`:this.obsGroups.obs_history?this.defaultObsKey=`obs_history`:this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,n,r){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((e,t)=>({name:n[t]?.name??`obs_${t}`,size:e.size}));let i=this.obsLayouts[e].reduce((e,t)=>e+t.size,0);r&&r.steps>1?(this.historyConfig[e]=r,this.historyBuffers[e]=new Float32Array(i*r.steps),this.obsSizes[e]=i*r.steps):this.obsSizes[e]=i}buildFrame(e,t){let n=e.reduce((e,t)=>e+t.size,0),r=new Float32Array(n),i=0;for(let n of e){let e=n.compute(t),a=e instanceof Float32Array?e:Float32Array.from(e);if(a.length!==n.size)throw Error(`Observation size mismatch: expected ${n.size}, got ${a.length}`);r.set(a,i),i+=a.length}return r}normalizeArray(e,t,n){let r=new Float32Array(t);for(let i=0;i<t;i++)r[i]=typeof e[i]==`number`?e[i]:n;return r}};cI.wasm.proxy=!1,cI.wasm.numThreads=1,typeof __ORT_CDN_BASE__<`u`&&(cI.wasm.wasmPaths=__ORT_CDN_BASE__);var iJ=class{constructor(e){if(!e?.path)throw Error(`OnnxModule requires a path.`);this.config=e,this.session=null;let t=e.meta?.in_keys??[`policy`],n=e.meta?.out_keys??[`action`];this.configuredInKeys=t.map(e=>Array.isArray(e)?e.join(`,`):e),this.inKeys=[...this.configuredInKeys],this.outKeys=n.map(e=>Array.isArray(e)?e.join(`,`):e),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}async init(){let e=await fetch(this.config.path);if(!e.ok)throw Error(`Failed to fetch ONNX model: ${e.status}`);let t=await e.arrayBuffer();this.session=await VI.create(t,{executionProviders:[`wasm`],graphOptimizationLevel:`all`}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}initInput(){let e={};return this.isRecurrent&&(e.is_init=new AI(`bool`,[!0],[1]),e.adapt_hx=new AI(`float32`,new Float32Array(128),[1,128])),this.inKeys.includes(`time_step`)&&(e.time_step=new AI(`float32`,new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw Error(`OnnxModule not initialized.`);let t={};for(let n=0;n<this.inKeys.length;n++){let r=this.inKeys[n],i=this.session.inputNames[n];if(!i||!e[r])throw Error(`Missing ONNX input for key: ${r}`);t[i]=e[r]}let n=await this.session.run(t),r={};for(let e=0;e<this.outKeys.length;e++){let t=this.outKeys[e],i=this.session.outputNames[e];i&&n[i]&&(r[t]=n[i])}let i={};return this.isRecurrent&&r[`next,adapt_hx`]&&(i.is_init=new AI(`bool`,[!1],[1]),i.adapt_hx=r[`next,adapt_hx`]),[r,i]}inferInputKeys(){if(!this.session)return;let e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(e=>this.configuredInKeys.includes(e)?e:e===`obs`&&this.configuredInKeys.includes(`policy`)?`policy`:e)}},aJ=class{constructor(e,t,n,r){this.mujoco=e,this.mjModel=t,this.mjData=n;let i=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(let e of r){let n=i.indexOf(e);if(n<0)throw Error(`Joint "${e}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[n]),this.qvelAdr.push(t.jnt_dofadr[n]),this.jointIndices.push(n)}this.numActions=r.length,this.ctrlAdr=this.buildCtrlAdr()}build(){let e=this.mjData.qpos,t=this.mjData.qvel,n=new Float32Array(this.numActions),r=new Float32Array(this.numActions);for(let i=0;i<this.numActions;i++)n[i]=e[this.qposAdr[i]],r[i]=t[this.qvelAdr[i]];return{jointPos:n,jointVel:r,rootPos:new Float32Array([e[0],e[1],e[2]]),rootQuat:new Float32Array([e[3],e[4],e[5],e[6]]),rootLinVel:new Float32Array([t[0],t[1],t[2]]),rootAngVel:new Float32Array([t[3],t[4],t[5]])}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;let n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[],o=[],s=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(this.ctrlAdr[e]),a.push(this.qposAdr[e]),o.push(this.qvelAdr[e]),s.push(e));return i.length===0?null:{ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s}}getCtrlMappingByActuatorNames(e){let t=this.getActuatorNames(this.mjModel),n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(e),a.push(i.length-1));return i.length>0?{ctrlAdr:i,actionIndices:a}:null}getActuatorNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.nu;i++){let a=e.name_actuatoradr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;let e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let n=0;n<this.mjModel.nu;n++){let r=this.mjModel.actuator_trntype[n];e===void 0||r===e?t.push(this.mjModel.actuator_trnid[2*n]):t.push(-1)}let n=[];for(let e of this.jointIndices){let r=t.findIndex(t=>t===e);if(r<0)return null;n.push(r)}return n}getJointNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;let s=n.decode(t.subarray(a,o));!s&&i===0&&(s=`floating_base_joint`),r.push(s)}return r}},oJ=class{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}},sJ=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},cJ=class extends oJ{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.tracking=new sJ(n)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}},lJ=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},uJ=class extends oJ{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.locomotion=new lJ(n)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}},dJ=class{constructor(e){this.config=e}};function fJ(e,t){return e+Math.random()*(t-e)}function pJ(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}function mJ(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}var hJ=class extends dJ{constructor(e){super(e),this.mutations=e.mutations??[]}onReset(e){let{mjModel:t,mjData:n}=e;if(!(!t||!n))for(let e of this.mutations)switch(e.target){case`joint_qpos`:this.applyJointOffset(t,n,e,`qpos`);break;case`joint_qvel`:this.applyJointOffset(t,n,e,`qvel`);break;case`freejoint_pos`:this.applyFreejointPos(t,n,e);break;case`freejoint_yaw`:this.applyFreejointYaw(t,n,e);break}}resolveJointIndices(e,t){let n=t.select??{};if(n.joint_ids&&n.joint_ids.length>0)return n.joint_ids.filter(t=>t>=0&&t<e.njnt);let r=pJ(e);return n.joint_names&&n.joint_names.length>0?n.joint_names.map(e=>this.findJointIndex(r,e,n.entity_name)).filter(e=>e!==null):r.map((e,t)=>({name:e,idx:t})).filter(({name:t,idx:r})=>e.jnt_type[r]===0?!1:n.entity_name?t===n.entity_name||t.startsWith(`${n.entity_name}/`):!0).map(({idx:e})=>e)}findJointIndex(e,t,n){let r=e.indexOf(t);if(r>=0)return r;if(n){let r=e.indexOf(`${n}/${t}`);if(r>=0)return r}let i=e.map((e,t)=>({name:e,idx:t})).filter(({name:e})=>e===t||e.endsWith(`/${t}`));if(i.length===1)return i[0].idx;if(n){let e=i.find(({name:e})=>e===n||e.startsWith(`${n}/`));if(e)return e.idx}return null}applyJointOffset(e,t,n,r){if(n.sample.dist!==`uniform`)return;let{low:i,high:a}=n.sample;for(let o of this.resolveJointIndices(e,n)){let s=e.jnt_type[o];if(!(s!==2&&s!==3))if(r===`qpos`){let r=e.jnt_qposadr[o];if(t.qpos[r]+=fJ(i,a),n.clip_to_limits&&e.jnt_limited[o]){let n=e.jnt_range[o*2],i=e.jnt_range[o*2+1];t.qpos[r]=Math.min(Math.max(t.qpos[r],n),i)}}else t.qvel[e.jnt_dofadr[o]]+=fJ(i,a)}}applyFreejointPos(e,t,n){if(n.sample.dist!==`uniform_xyz`)return;let r=mJ(e);if(r<0)return;let i=e.jnt_qposadr[r];t.qpos[i]+=fJ(n.sample.x[0],n.sample.x[1]),t.qpos[i+1]+=fJ(n.sample.y[0],n.sample.y[1]),t.qpos[i+2]+=fJ(n.sample.z[0],n.sample.z[1])}applyFreejointYaw(e,t,n){if(n.sample.dist!==`uniform`)return;let r=mJ(e);if(r<0)return;let i=e.jnt_qposadr[r]+3,a=fJ(n.sample.low,n.sample.high),o=Math.cos(a/2),s=Math.sin(a/2),c=t.qpos[i],l=t.qpos[i+1],u=t.qpos[i+2],d=t.qpos[i+3];t.qpos[i]=o*c-s*d,t.qpos[i+1]=o*l+s*u,t.qpos[i+2]=o*u-s*l,t.qpos[i+3]=o*d+s*c}};function gJ(e){return`kind`in e&&e.kind===`event`&&Array.isArray(e.mutations)}var _J=class{constructor(e,t){this.terms=[];for(let n of e){if(gJ(n)){this.terms.push(new hJ(n));continue}let e=t[n.name];if(!e){console.warn(`[EventManager] Unknown event type: ${n.name}`);continue}this.terms.push(new e(n))}}onReset(e){for(let t of this.terms)t.onReset(e)}get size(){return this.terms.length}},vJ={};function yJ(e){return typeof e==`object`&&!!e&&typeof e.setSelectedMotion==`function`}var bJ=class extends Error{constructor(){super(`This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory.`),this.name=`WasmMemoryLimitError`}};function xJ(e){let t=e instanceof Error?e.message:String(e);return t.includes(`MjModel loading returned null`)||t.includes(`Could not allocate memory`)||t.includes(`memory allocation failed`)||t.includes(`bad_alloc`)}var SJ=class{constructor(e,t,n={}){this.render=()=>{if(pF().updateDebugVisuals(),this.mjData&&IP(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){GD(this.camera,this.lights);for(let[e,t]of this.lastSimState.bodies){let n=this.bodies[e];n&&(n.position.copy(t.position),n.quaternion.copy(t.quaternion))}WD(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&$D({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{let{width:e,height:t}=this.getSize();this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)},this.mujoco=e,this.container=t,this.baseUrl=n.baseUrl||`/`;let r=`/working`;try{this.mujoco.FS.mkdir(r)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&console.warn(`Failed to create /working directory:`,e)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:`.`},r)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&e.code!==`EBUSY`&&console.warn(`Failed to mount MEMFS at /working:`,e)}let{width:i,height:a}=this.getSize();this.scene=new Ex,this.scene.name=`scene`,this.camera=new _x(45,i/a,.001,1e3),this.camera.name=`PerspectiveCamera`,this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new dD({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(i,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=2,this.renderer.outputColorSpace=V_,this.renderer.toneMapping=4,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported(`immersive-vr`).then(e=>{e&&(this.vrButton=FD.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new SD(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener(`resize`,this.onWindowResize),`ResizeObserver`in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:eO()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.policyCtrlDt=null,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.initialQpos=null,this.initialQvel=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=LP.getInstance(this.mujoco),this.resourceTracker=new RP,this.memoryMonitor=new zP}async loadEnvironment(e,t=null,n=null,r=null,i=null,a=null){this.terrainData=a,i&&i.length>0?(this.eventManager=new _J(i,vJ),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&=(kN(this.splatMesh,this.scene),null),this.colliderMesh&&=(jP(this.colliderMesh,this.scene),null);let o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);let t=performance.now()-o;this.memoryMonitor.logCacheOperation(`hit`,e,{elapsedMs:t})}else this.memoryMonitor.logCacheOperation(`miss`,e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await mO(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);n&&(this.splatMesh=ON(n,this.scene),n.colliderUrl&&(this.colliderMesh=await AP(this.resolveAssetUrl(n.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(r),this.running=!0,this.startLoop()}initializeCommands(){let e=pF();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){pF().initialize(e,t),console.log(`[mjswanRuntime] Commands loaded from policy config:`,Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log(`[mjswanRuntime] Simulation reset`)}async setSelectedMotion(e){let t=pF().getTerm(`motion`);if(!yJ(t))return!1;let n=await t.setSelectedMotion(e);return n&&this.resetSimulation(),n}getSelectedMotionName(){let e=pF().getTerm(`motion`);return yJ(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){let t=pF().getTerm(`motion`);!yJ(t)||typeof t.setReferenceVisible!=`function`||t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{let t=this.scene.getObjectByName(`MuJoCo Root`);t&&this.scene.remove(t);let n={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await uO(this.mujoco,e,n),!this.mjModel||!this.mjData)throw Error(`Failed to load MuJoCo model.`);this.mujocoRoot=this.scene.getObjectByName(`MuJoCo Root`),this.mujoco.mj_forward(this.mjModel,this.mjData),WD(this.mujoco,this.mjData,this.lights),GD(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001;let r=this.policyCtrlDt??.02;this.decimation=Math.max(1,Math.round(r/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new MP({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!xJ(t))throw t;console.warn(`[mjswanRuntime] OOM — clearing cache and retrying...`),this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(e){throw this.loadingScene=null,xJ(e)?new bJ:e}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&=(kN(this.splatMesh,this.scene),null),this.colliderMesh&&=(jP(this.colliderMesh,this.scene),null),e&&(this.splatMesh=ON(e,this.scene),e.colliderUrl&&(this.colliderMesh=await AP(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&DN(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;let e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){let e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build(),t=this.policyRunner.collectObservationsByKey(e);await this.runOnnxInference(t)}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){let e=this.policyStateBuilder.build();if(this.terminationManager.evaluate(e).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}pF().update(t),pF().updateDebugVisuals()}let n=(performance.now()-e)/1e3,r=Math.max(0,t-n);r>0&&await new Promise(e=>setTimeout(e,r*1e3))}this.loopPromise=null}async loadPolicyConfig(e){let t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;let n=pF();if(n.clear(),n.setResetCallback(()=>this.resetSimulation()),e){if(!this.mjModel||!this.mjData){console.warn(`Policy config loaded before MuJoCo model is ready.`);return}e!==t&&this.resetSimulationState();try{let{config:t}=await this.fetchPolicyConfig(e);if(Array.isArray(t.motions)&&(t.motions=t.motions.map(t=>({...t,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,t.path))}))),t.commands?.motion&&Array.isArray(t.motions)&&(t.commands.motion={...t.commands.motion,motions:t.motions}),this.initialQpos=Array.isArray(t.initial_qpos)?t.initial_qpos:null,this.initialQvel=Array.isArray(t.initial_qvel)?t.initial_qvel:null,this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),t.commands&&typeof t.commands==`object`){this.initializeCommandsFromConfig(t.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),pF().resetTerms();let e=pF().getTerm(`motion`);yJ(e)&&(await e.setSelectedMotion(t.motions?.find(e=>e.default)?.name??t.motions?.[0]?.name??null),e.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!t.policy_num_actions&&(!t.policy_joint_names||t.policy_joint_names.length===0))throw Error(`Policy config missing policy_joint_names.`);let n=new rJ(t,{policyModules:{tracking:cJ,locomotion:uJ},observations:BP});await n.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),await n.preloadAll(),this.policyRunner=n,this.policyStateBuilder=new aJ(this.mujoco,this.mjModel,this.mjData,n.getPolicyJointNames());let r=this.policyStateBuilder.build();this.policyRunner.reset(r),this.policyControl=this.buildPolicyControl(t,n,this.policyStateBuilder);{let e=t.observations,n=[];if(Array.isArray(e))n.push(...e);else if(e&&typeof e==`object`)for(let t of Object.values(e))Array.isArray(t)&&n.push(...t);for(let e of n)if(!(!e||this.timestep<=0)&&typeof e.fps==`number`&&e.fps>0){this.policyCtrlDt=1/e.fps;let t=Math.max(1,Math.round(this.policyCtrlDt/this.timestep));t!==this.decimation&&(console.log(`[PolicyRunner] Decimation updated: ${this.decimation} → ${t} (fps=${e.fps}, sim_dt=${this.timestep})`),this.decimation=t);break}}if(t.terminations&&Object.keys(t.terminations).length>0&&(this.terminationManager=new BF(t.terminations,VF,n),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`)),t.onnx?.path){let n=this.resolvePolicyAssetPath(e,t.onnx.path),r=this.resolveAssetUrl(n),i=new iJ({...t.onnx,path:r});await i.init(),this.onnxModule=i,this.onnxInputDict=i.initInput()}console.log(`[PolicyRunner] config loaded`,{obsSize:n.getObservationSize(),obsLayout:n.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(e){console.warn(`Failed to load policy config:`,e)}}}async fetchPolicyConfig(e){let t=this.resolveAssetUrl(e),n=await fetch(t,{cache:`no-store`});if(!n.ok)throw Error(`Failed to fetch policy config: ${n.status}`);return{config:await n.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;let t=(this.baseUrl||`/`).replace(/\/+$/,`/`),n=new URL(t,window.location.origin+`/`).toString();return new URL(e.replace(/^\/+/,``),n).toString()}resolvePolicyAssetPath(e,t){let n=e.replace(/\\/g,`/`),r=n.lastIndexOf(`/`);return r>=0?`${n.slice(0,r+1)}${t}`.replace(/\/+/g,`/`):t}buildPolicyControl(e,t,n){let r=t.getPolicyJointNames(),i=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(n,a,o,s,c,l,u,d)=>{let f=o.qposAdr.length,p=o.actionIndices.map(e=>r[e]),m=this.normalizeControlArray(s,f,1,p),h=this.normalizeControlArray(c,f,0,p),g=d?t.getDefaultJointPos():new Float32Array(r.length),_=new Float32Array(f);for(let e=0;e<f;e++)_[e]=g[o.actionIndices[e]];let v=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(r.length),y=new Float32Array(f);for(let e=0;e<f;e++)y[e]=v[o.actionIndices[e]]??0;let b=this.normalizeControlArray(l,f,0,p),x=this.normalizeControlArray(u,f,0,p),S=o.ctrlAdr.map(e=>e<0||!this.mjModel?!1:this.mjModel.actuator_biastype[e]===i),C=S.some(Boolean),w=S.some(e=>!e);return C&&w&&console.warn(`[PolicyRunner] Action term "${n}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${n}" (${a}): ${f} joint(s), mode: ${C?`position (ctrl=target_pos)`:`motor (ctrl=torque, external PD)`}`),{controlType:a,ctrlAdr:o.ctrlAdr,qposAdr:o.qposAdr,qvelAdr:o.qvelAdr,actionIndices:o.actionIndices,actionScale:m,actionOffset:h,defaultJointPos:_,encoderBias:y,positionActuator:S,kp:b,kd:x,muscleNormalize:!1}},o=e.actions;if(!o||Object.keys(o).length===0){let t=e.control_type??`joint_position`;if(t!==`joint_position`&&t!==`torque`)return console.warn(`[PolicyRunner] Unsupported control_type: ${t}`),null;let r=n.getControlMapping();return r?[a(`legacy`,t,{...r,actionIndices:Array.from({length:r.qposAdr.length},(e,t)=>t)},e.action_scale,void 0,e.stiffness,e.damping,!0)]:(console.warn(`[PolicyRunner] Failed to build control mapping.`),null)}let s=[];for(let[e,t]of Object.entries(o)){let i=t.type??`joint_position`;if(i!==`joint_position`&&i!==`torque`&&i!==`muscle_activation`){console.warn(`[PolicyRunner] Action term "${e}": unsupported type "${i}", skipping.`);continue}let o=t.actuator_names??[`.*`];if(i===`muscle_activation`){let r=n.getCtrlMappingByActuatorNames(o);if(!r){console.warn(`[PolicyRunner] Action term "${e}": no actuators matched patterns [${o.join(`, `)}], skipping.`);continue}let a=r.ctrlAdr.length,c=this.normalizeControlArray(t.scale,a,1),l=this.normalizeControlArray(t.offset,a,0),u=t.normalize??!0;console.log(`[PolicyRunner] Action term "${e}" (muscle_activation): ${a} actuator(s), normalize=${u}`),s.push({controlType:i,ctrlAdr:r.ctrlAdr,qposAdr:[],qvelAdr:[],actionIndices:r.actionIndices,actionScale:c,actionOffset:l,defaultJointPos:new Float32Array(a),encoderBias:new Float32Array(a),positionActuator:Array(a).fill(!1),kp:new Float32Array(a),kd:new Float32Array(a),muscleNormalize:u});continue}let c=o.length===1&&o[0]===`.*`,l;if(c){let t=n.getControlMapping();if(!t){console.warn(`[PolicyRunner] Action term "${e}": failed to build control mapping, skipping.`);continue}l={...t,actionIndices:Array.from({length:t.qposAdr.length},(e,t)=>t)}}else if(l=n.getControlMappingFor(o,r),!l){console.warn(`[PolicyRunner] Action term "${e}": no joints matched patterns [${o.join(`, `)}], skipping.`);continue}let u=t.use_default_offset===void 0?i===`joint_position`:t.use_default_offset;s.push(a(e,i,l,t.scale,t.offset,t.stiffness,t.damping,u))}return s.length===0?(console.warn(`[PolicyRunner] No valid action terms found in config.actions.`),null):s}normalizeControlArray(e,t,n,r){let i=new Float32Array(t);if(i.fill(n),typeof e==`number`)return i.fill(e),i;if(Array.isArray(e)){for(let r=0;r<t;r++)i[r]=typeof e[r]==`number`?e[r]:n;return i}if(typeof e==`object`&&e&&r){for(let[n,a]of Object.entries(e)){let e=r.indexOf(n);e>=0&&e<t?i[e]=a:console.warn(`[PolicyRunner] Joint name "${n}" not found in policy_joint_names; skipping.`)}return i}return i}resetSimulationState(){if(!(!this.mjModel||!this.mjData)){if(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.initialQpos){let e=this.mjData.qpos;for(let t=0;t<Math.min(this.initialQpos.length,this.mjModel.nq);t++)e[t]=this.initialQpos[t]}if(this.initialQvel){let e=this.mjData.qvel;for(let t=0;t<Math.min(this.initialQvel.length,this.mjModel.nv);t++)e[t]=this.initialQvel[t]}this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),pF().resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState()}}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;let e=this.mjData.ctrl;e.fill(0);let t=this.policyRunner?.getLastActions()??new Float32Array;for(let n of this.policyControl){let{controlType:r,ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s,actionScale:c,actionOffset:l,defaultJointPos:u,encoderBias:d,positionActuator:f,kp:p,kd:m,muscleNormalize:h}=n,g=i.length;if(r===`joint_position`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let h=t[s[n]]??0,g=u[n]+l[n]+c[n]*h-d[n];if(f[n])e[r]=g;else{let t=this.mjData.qpos[a[n]],i=this.mjData.qvel[o[n]];e[r]=p[n]*(g-t)+m[n]*(0-i)}}else if(r===`torque`)for(let n=0;n<g;n++){let r=i[n];r>=0&&(e[r]=c[n]*(t[s[n]]??0))}else if(r===`muscle_activation`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let a=(t[s[n]]??0)*c[n]+l[n];h?e[r]=1/(1+Math.exp(-5*(a-.5))):e[r]=a<0?0:a>1?1:a}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||=this.onnxModule.initInput();let t={...this.onnxInputDict};this.onnxModule.inKeys.includes(`time_step`)&&(t.time_step=new AI(`float32`,new Float32Array([this.onnxTimeStep]),[1,1]));for(let[n,r]of Object.entries(e))t[n]=new AI(`float32`,r,[1,r.length]);for(let e of this.onnxModule.inKeys)if(!t[e]){console.warn(`[PolicyRunner] Missing ONNX input:`,{key:e,available:Object.keys(t)});return}let[n,r]=await this.onnxModule.runInference(t);Object.keys(r).length>0&&(this.onnxInputDict={...this.onnxInputDict,...r}),this.onnxModule.inKeys.includes(`time_step`)&&(this.onnxTimeStep+=1);let i=this.onnxModule.outKeys[0],a=n.action??(i?n[i]:null)??n.policy??null;if(!a)return;let o=a.data,s=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&s.length!==c){console.warn(`[PolicyRunner] Action size mismatch:`,{expected:c,got:s.length});return}this.policyRunner.setLastActions(s)}catch(e){console.warn(`[PolicyRunner] ONNX inference failed:`,e)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let e=0;e<this.mjData.xfrc_applied.length;e++)this.mjData.xfrc_applied[e]=0;let e=this.dragStateManager.physicsObject;if(!e||!(`bodyID`in e)||typeof e.bodyID!=`number`||e.bodyID<=0)return;let t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let e=0;e<this.mjModel.nbody;e++)this.bodies[e]&&(fO(this.mjData.xpos,e,this.bodies[e].position),pO(this.mjData.xquat,e,this.bodies[e].quaternion),this.bodies[e].updateWorldMatrix(!0,!1));this.dragStateManager.update();let n=HD(this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale)),r=HD(this.dragStateManager.worldHit.clone()),i=new Y(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),a=new Y(r.x-i.x,r.y-i.y,r.z-i.z),o=new Y(n.x,n.y,n.z),s=new Y().crossVectors(a,o),c=t*6;this.mjData.xfrc_applied[c+0]=n.x,this.mjData.xfrc_applied[c+1]=n.y,this.mjData.xfrc_applied[c+2]=n.z,this.mjData.xfrc_applied[c+3]=s.x,this.mjData.xfrc_applied[c+4]=s.y,this.mjData.xfrc_applied[c+5]=s.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new Y,quaternion:new Pv});let e=this.lastSimState.bodies.get(t);fO(this.mjData.xpos,t,e.position),pO(this.mjData.xquat,t,e.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&QD(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=FP(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){let t=new Set;for(let n=1;n<e.nbody;n++){let r=n;for(;r>0;){if(e.body_jntnum[r]>0){t.add(n);break}r=e.body_parentid[r]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;let n=this.bodies[t];n&&(fO(this.mjData.xpos,t,n.position),pO(this.mjData.xquat,t,n.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&=(this.dragStateManager.dispose(),null),this.mjData=null,this.mjModel=null,window.removeEventListener(`resize`,this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{`geometry`in e&&e.geometry&&e.geometry.dispose(),`material`in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){let t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){let e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){let t=this.sceneCacheManager.get(e);if(!t)throw Error(`Scene ${e} not found in cache`);let n=this.scene.getObjectByName(`MuJoCo Root`);n&&this.scene.remove(n),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001;let r=this.policyCtrlDt??.02;this.decimation=Math.max(1,Math.round(r/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new MP({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){let t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn(`[SceneCache] Cannot cache scene: missing resources`);return}let n=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof xx?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:n});let r=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation(`load`,e,{memoryMB:n/1048576,totalScenes:r.totalScenes,totalMemoryMB:r.totalMemoryBytes/1048576})}},CJ=`mjswan_oom_reload_scene`,wJ=({scenePath:e,baseUrl:t,policyConfigPath:n,splatConfig:i,cameraConfig:a,eventsConfig:o,terrainData:s,selectedMotion:c,showReferenceMotion:l=!0,onStatusChange:u,onError:d,onReady:f,onRuntimeReady:p})=>{let m=(0,y.useRef)(null),h=(0,y.useRef)(null),g=(0,y.useRef)(null),_=(0,y.useRef)(i);_.current=i;let v=(0,y.useRef)(c);v.current=c;let b=(0,y.useRef)(l);return b.current=l,(0,y.useEffect)(()=>{let i=!1,c=e=>{u?.(e)};return(async()=>{if(g.current||=(c(`Loading MuJoCo…`),await(await r(()=>import(`./mujoco-C7EP5tg_.js`),__vite__mapDeps([0,1,2]))).default()),i)return;let l=m.current;if(!l)throw Error(`Failed to find viewer container.`);let u=g.current;if(!u)throw Error(`MuJoCo not loaded.`);h.current||(h.current=new SJ(u,l,{baseUrl:t}),p?.(h.current)),c(`Loading scene…`),await h.current.loadEnvironment(e,n??null,_.current??null,a??null,o??null,s??null),await h.current.setSelectedMotion(v.current??null),h.current.setReferenceVisible(b.current),!i&&(sessionStorage.removeItem(CJ),c(`Running simulation`),f?.())})().catch(t=>{if(!i){if(t instanceof bJ){if(sessionStorage.getItem(CJ)!==e){console.warn(`[MjswanViewer] OOM — reloading page to free memory...`),sessionStorage.setItem(CJ,e),window.location.reload();return}sessionStorage.removeItem(CJ)}console.error(`Failed to initialize MuJoCo viewer:`,t),d?.(t instanceof Error?t:Error(String(t))),c(`Failed to load scene`)}}),()=>{i=!0,h.current?.dispose(),h.current=null}},[e,t,n,a,o,s,u,d,f]),(0,y.useEffect)(()=>{h.current?.setReferenceVisible(l)},[l]),(0,G.jsx)(`div`,{ref:m,className:`viewer`})},TJ={outline:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},filled:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`currentColor`,stroke:`none`}},EJ=(e,t,n,r)=>{let i=(0,y.forwardRef)(({color:n=`currentColor`,size:i=24,stroke:a=2,title:o,className:s,children:c,...l},u)=>(0,y.createElement)(`svg`,{ref:u,...TJ[e],width:i,height:i,className:[`tabler-icon`,`tabler-icon-${t}`,s].join(` `),...e===`filled`?{fill:n}:{strokeWidth:a,stroke:n},...l},[o&&(0,y.createElement)(`title`,{key:`svg-title`},o),...r.map(([e,t])=>(0,y.createElement)(e,t)),...Array.isArray(c)?c:[c]]));return i.displayName=`${n}`,i},DJ=EJ(`outline`,`chevron-down`,`ChevronDown`,[[`path`,{d:`M6 9l6 6l6 -6`,key:`svg-0`}]]),OJ=EJ(`outline`,`chevron-up`,`ChevronUp`,[[`path`,{d:`M6 15l6 -6l6 6`,key:`svg-0`}]]),kJ=EJ(`outline`,`refresh`,`Refresh`,[[`path`,{d:`M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4`,key:`svg-0`}],[`path`,{d:`M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4`,key:`svg-1`}]]),AJ=EJ(`outline`,`x`,`X`,[[`path`,{d:`M18 6l-12 12`,key:`svg-0`}],[`path`,{d:`M6 6l12 12`,key:`svg-1`}]]),jJ=`0.7.0`,MJ=[{login:`ttktjmt`,html_url:`https://github.com/ttktjmt`},{login:`claude`,html_url:`https://github.com/claude`},{login:`Axellwppr`,html_url:`https://github.com/Axellwppr`},{login:`julien-blanchon`,html_url:`https://github.com/julien-blanchon`},{login:`unmoyai`,html_url:`https://github.com/unmoyai`},{login:`brentyi`,html_url:`https://github.com/brentyi`},{login:`CharlieLeee`,html_url:`https://github.com/CharlieLeee`}],NJ={move:`touchmove`,end:`touchend`},PJ={move:`mousemove`,end:`mouseup`};function FJ(e){return e.type===`touchmove`}function IJ(e){return e.type===`mousemove`}var LJ=y.createContext(null);function RJ({children:e,width:t,visible:n=!0,onVisibleChange:r,hiddenButtonTooltip:i}){let a=y.useRef(null),[o,{toggle:s}]=Ht(!0),[c,l]=y.useState(800),u=y.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),d=y.useRef({}),f=(e,t,n)=>Math.abs(e+t/2)<Math.abs(e-n+t/2)?e:e-n;function p(e,t){let n=a.current;if(n===null)return[e,t];let r=n.parentElement;if(r===null)return[e,t];let i=e,o=t;return i=Math.min(i,r.clientWidth-n.clientWidth-15),i=Math.max(i,15),o=Math.min(o,r.clientHeight-n.clientHeight-15),o=Math.max(o,15),n.style.top=`${o.toString()}px`,n.style.left=`${i.toString()}px`,[f(i,n.clientWidth,r.clientWidth),f(o,n.clientHeight,r.clientHeight)]}y.useEffect(()=>{let e=a.current;if(e===null)return;let t=e.parentElement;if(t===null)return;let n=new ResizeObserver(()=>{d.current.x===void 0&&(d.current.x=f(e.offsetLeft,e.clientWidth,t.clientWidth)),d.current.y===void 0&&(d.current.y=f(e.offsetTop,e.clientHeight,t.clientHeight));let n=t.clientHeight-30;c!==n&&l(n);let r=d.current.x,i=d.current.y;for(;r<0;)r+=t.clientWidth;for(;i<0;)i+=t.clientHeight;p(r,i)});return n.observe(e),n.observe(t),()=>{n.disconnect()}});let m=e=>{let t=u.current,n=a.current;if(!n)return;e.type==`touchstart`?(e=e,t.startClientX=e.touches[0].clientX,t.startClientY=e.touches[0].clientY):(e=e,t.startClientX=e.clientX,t.startClientY=e.clientY),t.startPosX=n.offsetLeft,t.startPosY=n.offsetTop;let r=e.type==`touchstart`?NJ:PJ;function i(e){let n=0,r=0;if(FJ(e)?(e=e,n=e.touches[0].clientX-t.startClientX,r=e.touches[0].clientY-t.startClientY):IJ(e)&&(e=e,n=e.clientX-t.startClientX,r=e.clientY-t.startClientY),Math.abs(n)<=3&&Math.abs(r)<=3)return;t.dragging=!0;let i=t.startPosX+n,a=t.startPosY+r;[d.current.x,d.current.y]=p(i,a)}window.addEventListener(r.move,i),window.addEventListener(r.end,()=>{e.type==`touchstart`&&(t.dragging=!1),window.removeEventListener(r.move,i)},{once:!0})};if(!n){let e=(0,G.jsx)(J,{component:`button`,"aria-label":i??`Show controls`,onClick:()=>r?.(!0),style:{width:`0.85rem`,height:`0.85rem`,minWidth:`0.85rem`,minHeight:`0.85rem`,display:`block`,padding:0,border:`none`,borderRadius:`9999px`,background:`rgba(255, 255, 255, 0.82)`,boxShadow:`0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)`,cursor:`pointer`}});return(0,G.jsx)(J,{style:{zIndex:10,position:`absolute`,top:`1em`,right:`1em`},children:i?(0,G.jsx)(Uh,{label:i,children:(0,G.jsx)(J,{children:e})}):e})}return(0,G.jsx)(LJ.Provider,{value:{wrapperRef:a,expanded:o,width:t,maxHeight:c,toggleExpanded:s,dragHandler:m,dragInfo:u},children:(0,G.jsx)(Jc,{radius:`xs`,shadow:`0.1em 0 1em 0 rgba(0,0,0,0.1)`,style:{boxSizing:`border-box`,width:t,zIndex:10,position:`absolute`,top:`1em`,right:`1em`,margin:0,"& .expandIcon":{transform:`rotate(0)`},overflow:`hidden`},ref:a,children:e})})}RJ.Handle=function({children:e}){let t=y.useContext(LJ);return(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(J,{style:{borderRadius:`0.2em 0.2em 0 0`,lineHeight:`1.5em`,cursor:`pointer`,position:`relative`,fontWeight:400,userSelect:`none`,display:`flex`,alignItems:`center`,padding:`0 0.75em`,height:`2.75em`},onClick:()=>{let e=t.dragInfo.current;if(e.dragging){e.dragging=!1;return}t.toggleExpanded()},onTouchStart:e=>{t.dragHandler(e)},onMouseDown:e=>{t.dragHandler(e)},children:e})})},RJ.Contents=function({children:e}){let t=y.useContext(LJ);return(0,G.jsxs)(Di,{in:t.expanded,children:[(0,G.jsx)(pp,{mx:`xs`}),(0,G.jsx)(zc.Autosize,{mah:t.maxHeight,children:(0,G.jsx)(J,{style:{width:t.width},children:e})})]})},RJ.HideWhenCollapsed=function({children:e}){return y.useContext(LJ)?.expanded??!0?e:null},RJ.HideWhenExpanded=function({children:e}){return y.useContext(LJ)?.expanded??!0?null:e};function zJ({id:e,label:t,children:n}){return(0,G.jsx)(J,{pb:`0.5em`,px:`xs`,children:(0,G.jsxs)(Hu,{align:`center`,children:[(0,G.jsx)(J,{pr:`xs`,style:{width:`7.25em`,flexShrink:0,position:`relative`},children:(0,G.jsx)(Yu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`100%`,boxSizing:`content-box`},children:(0,G.jsx)(`label`,{htmlFor:e,children:t})})}),(0,G.jsx)(J,{style:{flexGrow:1},children:n})]})})}function BJ({label:e,expandByDefault:t=!0,children:n}){let[r,{toggle:i}]=Ht(t);return(0,G.jsxs)(Jc,{withBorder:!0,style:{borderWidth:`1px`,position:`relative`,marginLeft:`var(--mantine-spacing-xs)`,marginRight:`var(--mantine-spacing-xs)`,marginTop:`var(--mantine-spacing-xs)`,marginBottom:`var(--mantine-spacing-xs)`,paddingBottom:`calc(var(--mantine-spacing-xs) - 0.5em)`},children:[(0,G.jsxs)(Jc,{onClick:i,style:{fontSize:`0.875em`,position:`absolute`,padding:`0 0.375em`,top:0,left:`0.375em`,transform:`translateY(-50%)`,userSelect:`none`,fontWeight:500,cursor:`pointer`,display:`flex`,alignItems:`center`},children:[e,(0,G.jsx)(r?OJ:DJ,{style:{width:`0.9em`,height:`0.9em`,strokeWidth:3,top:`0.1em`,position:`relative`,marginLeft:`0.25em`,marginRight:`-0.1em`,opacity:.5}})]}),(0,G.jsx)(Di,{in:r,children:(0,G.jsx)(J,{pt:`1em`,children:n})}),(0,G.jsx)(Di,{in:!r,children:(0,G.jsx)(J,{p:`xs`})})]})}var VJ={fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`4.5em`,flexShrink:0},HJ={root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}},UJ={flex:1,minWidth:0,height:`1.75em`,fontSize:`0.8em`,fontFamily:`inherit`,border:`1px solid var(--mantine-color-default-border)`,borderRadius:`var(--mantine-radius-sm)`,background:`var(--mantine-color-default)`,color:`var(--mantine-color-text)`,textAlign:`right`,padding:`0 0.4em`,outline:`none`,cursor:`ns-resize`,touchAction:`none`};function WJ({axis:e,value:t,min:n=-1/0,max:r=1/0,step:i,onChange:a}){let o=(0,y.useRef)(null),s=(0,y.useRef)(null);(0,y.useEffect)(()=>{let e=o.current;e&&document.activeElement!==e&&(e.value=t.toFixed(2))},[t]);let c=e=>Math.max(n,Math.min(r,parseFloat((Math.round(e/i)*i).toFixed(10))));return(0,G.jsxs)(J,{style:{display:`flex`,alignItems:`center`,gap:`0.25em`,flex:1},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,letterSpacing:`-0.75px`,flexShrink:0},children:e}),(0,G.jsx)(`input`,{ref:o,size:1,defaultValue:t.toFixed(2),onPointerDown:e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={startY:e.clientY,startValue:t,moved:!1}},onPointerMove:e=>{if(!s.current||!(e.buttons&1))return;let t=s.current.startY-e.clientY;if(Math.abs(t)>3&&(s.current.moved=!0),!s.current.moved)return;let n=c(s.current.startValue+t*i);a(n),o.current&&(o.current.value=n.toFixed(2))},onPointerUp:()=>{if(s.current&&!s.current.moved){let e=o.current;e&&(e.focus(),e.select())}s.current=null},onBlur:e=>{let n=parseFloat(e.target.value);isNaN(n)||a(c(n)),e.target.value=t.toFixed(2)},onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur(),e.key===`Escape`&&(o.current&&(o.current.value=t.toFixed(2)),o.current?.blur())},onFocus:e=>e.currentTarget.style.outline=`2px solid var(--mantine-color-blue-5)`,onBlurCapture:e=>e.currentTarget.style.outline=`none`,style:UJ})]})}function GJ({label:e,x:t,y:n,z:r,step:i,xLabel:a=`X`,yLabel:o=`Y`,zLabel:s=`Z`,onX:c,onY:l,onZ:u}){return(0,G.jsxs)(J,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:VJ,children:e}),(0,G.jsx)(WJ,{axis:a,value:t,step:i,onChange:c}),(0,G.jsx)(WJ,{axis:o,value:n,step:i,onChange:l}),(0,G.jsx)(WJ,{axis:s,value:r,step:i,onChange:u})]})}function KJ({scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o,onCalibrate:s}){let[c,l]=(0,y.useState)(e),[u,d]=(0,y.useState)(t),[f,p]=(0,y.useState)(n),[m,h]=(0,y.useState)(r),[g,_]=(0,y.useState)(i),[v,b]=(0,y.useState)(a),[x,S]=(0,y.useState)(o);(0,y.useEffect)(()=>{l(e)},[e]),(0,y.useEffect)(()=>{d(t)},[t]),(0,y.useEffect)(()=>{p(n)},[n]),(0,y.useEffect)(()=>{h(r)},[r]),(0,y.useEffect)(()=>{_(i)},[i]),(0,y.useEffect)(()=>{b(a)},[a]),(0,y.useEffect)(()=>{S(o)},[o]);let C=(e,t,n,r,i,a,o)=>s(e,t,n,r,i,a,o);return(0,G.jsxs)(BJ,{label:`Control`,expandByDefault:!0,children:[(0,G.jsxs)(J,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:VJ,children:`Scale`}),(0,G.jsx)(J,{style:{flex:1},children:(0,G.jsx)(ug,{value:c,onChange:e=>{l(e),C(e,u,f,m,g,v,x)},min:.1,max:5,step:.05,size:`xs`,label:e=>e.toFixed(2),styles:HJ})})]}),(0,G.jsx)(GJ,{label:`Position`,x:u,y:f,z:m,step:.05,onX:e=>{d(e),C(c,e,f,m,g,v,x)},onY:e=>{p(e),C(c,u,e,m,g,v,x)},onZ:e=>{h(e),C(c,u,f,e,g,v,x)}}),(0,G.jsx)(GJ,{label:`Rotation`,x:g,y:v,z:x,step:.5,xLabel:`R`,yLabel:`P`,zLabel:`Y`,onX:e=>{_(e),C(c,u,f,m,e,v,x)},onY:e=>{b(e),C(c,u,f,m,g,e,x)},onZ:e=>{S(e),C(c,u,f,m,g,v,e)}})]})}function qJ(e){return e instanceof HTMLElement?e.isContentEditable?!0:e.closest(`input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]`)!==null:!1}function JJ(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function YJ({command:e,value:t,onChange:n,disabled:r,enabledWhenValue:i}){let a=e.config,o=a.enabled_when!==void 0&&(i??0)<.5,s=r||o;return(0,G.jsxs)(J,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`50%`,flexShrink:0},children:a.label}),(0,G.jsx)(J,{style:{width:`50%`},children:(0,G.jsx)(ug,{value:t,onChange:t=>n(e.id,t),min:a.min,max:a.max,step:a.step,size:`xs`,disabled:s,styles:{root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}}})})]})}function XJ({command:e,value:t,onChange:n,disabled:r}){let i=e.config;return(0,G.jsx)(J,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(nf,{label:i.label,checked:t>=.5,onChange:t=>n(e.id,+!!t.currentTarget.checked),size:`xs`,disabled:r})})}function ZJ(e){let{visible:t,onVisibleChange:n,projects:r,projectValue:i,projectLabel:a,onProjectChange:o,scenes:s,sceneValue:c,onSceneChange:l,splats:u,splatSection:d=!1,splatValue:f,onSplatChange:p,splatConfig:m,onCalibrateSplat:h,onSplatUrlLoad:g,policies:_,policyValue:v,onPolicyChange:b,motions:x,motionValue:S,onMotionChange:C,showReferenceMotion:w,onShowReferenceMotionChange:T,commandsEnabled:E=!1,onReset:D}=e,[O,{open:k,close:A}]=Ht(!1),[j,M]=(0,y.useState)(``),[N,P]=(0,y.useState)(null),[F,I]=(0,y.useState)(!1),L=(0,y.useCallback)(async e=>{if(e.key!==`Enter`||!g)return;let t=j.trim();if(!u.some(e=>e.label===t||e.value===t)){if(!t.toLowerCase().endsWith(`.spz`)){P(`URL must end with .spz`);return}await g(t)?(P(null),I(!0)):P(`File not found at the specified URL`)}},[g,j,u]),[R,z]=(0,y.useState)([]),[B,V]=(0,y.useState)([]),[ee,te]=(0,y.useState)({});(0,y.useEffect)(()=>{let e=pF(),t=()=>{z(e.getCommands()),V(e.getCommandGroups()),te(e.getValues())};return t(),e.addEventListener(t),()=>{e.removeEventListener(t)}},[]);let ne=(0,y.useCallback)((e,t)=>{pF().setValue(e,t),te(n=>({...n,[e]:t}))},[]),re=(0,y.useCallback)(()=>{pF().triggerButton(`_system:reset`),D&&D()},[D]);(0,y.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.repeat||e.altKey||e.ctrlKey||e.metaKey)return;let r=e.key.toLowerCase();r!==`c`&&r!==`r`||qJ(e.target instanceof Element?e.target:document.activeElement)||(e.preventDefault(),r===`c`?n(!t):re())};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,n,re]);let ie=e=>R.filter(t=>t.groupName===e&&(t.config.type===`slider`||t.config.type===`checkbox`));return!r.length&&!s.length&&!_.length?null:(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(xm,{opened:O,onClose:A,size:`lg`,title:null,centered:!0,styles:{body:{textAlign:`center`}},children:(0,G.jsxs)(mg,{gap:`md`,align:`center`,children:[(0,G.jsx)(gp,{src:`/logo.svg`,style:{width:`8em`,height:`auto`}}),(0,G.jsx)(Yu,{size:`xl`,fw:700,children:`powered by mjswan`}),(0,G.jsxs)(Yu,{size:`sm`,c:`dimmed`,children:[`version `,jJ]}),(0,G.jsx)(Yu,{size:`sm`,c:`dimmed`,children:`MuJoco Simulation on Web Assembly with Neural netwroks`}),(0,G.jsx)(pp,{w:`100%`}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Qu,{href:`https://github.com/ttktjmt/mjswan`,target:`_blank`,style:{fontWeight:`600`},children:`GitHub`}),`\xA0\xA0•\xA0\xA0`,(0,G.jsx)(Qu,{href:`https://mjswan.readthedocs.io`,target:`_blank`,style:{fontWeight:`600`},children:`Documentation`})]}),(0,G.jsx)(pp,{w:`100%`}),(0,G.jsxs)(J,{style:{textAlign:`left`,maxHeight:`120px`,overflowY:`auto`,lineHeight:`1`,fontSize:`0.8rem`,opacity:`0.75`},px:`md`,children:[`Thanks to our contributors! `,(0,G.jsx)(`br`,{}),MJ.map((e,t)=>(0,G.jsxs)(`span`,{children:[(0,G.jsx)(Qu,{href:e.html_url,target:`_blank`,style:{textDecoration:`none`,fontSize:`0.75rem`},children:e.login}),t<MJ.length-1&&`, `]},e.login))]})]})}),(0,G.jsxs)(RJ,{width:`20em`,visible:t,onVisibleChange:n,hiddenButtonTooltip:`Show controls (C)`,children:[(0,G.jsxs)(RJ.Handle,{children:[(0,G.jsx)(Uh,{label:`mjswan ${jJ}`,children:(0,G.jsx)(J,{component:`a`,onClick:e=>{e.stopPropagation(),k()},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{position:`absolute`,cursor:`pointer`,display:`flex`,top:`0.8em`,left:`0.9em`},children:(0,G.jsx)(gp,{src:`/logo.svg`,style:{width:`1.2em`,height:`auto`}})})}),(0,G.jsx)(`div`,{style:{width:`1.1em`}}),(0,G.jsx)(RJ.HideWhenCollapsed,{children:(0,G.jsxs)(J,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`,display:`flex`,alignItems:`center`,gap:`0.5em`},pt:`0.1em`,children:[(0,G.jsx)(`span`,{style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:a}),r.length>1&&(0,G.jsxs)(im,{position:`bottom-start`,offset:5,children:[(0,G.jsx)(im.Target,{children:(0,G.jsx)(J,{onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{cursor:`pointer`,display:`flex`,alignItems:`center`,flexShrink:0},children:(0,G.jsx)(DJ,{size:16})})}),(0,G.jsx)(im.Dropdown,{onClick:e=>e.stopPropagation(),children:r.map(e=>(0,G.jsx)(im.Item,{onClick:t=>{t.stopPropagation(),o(e.value)},style:{fontWeight:e.value===i?600:400,backgroundColor:e.value===i?`rgba(34, 139, 230, 0.1)`:void 0},children:e.label},e.value))})]})]})}),(0,G.jsx)(RJ.HideWhenExpanded,{children:(0,G.jsx)(J,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`},pt:`0.1em`,children:a})}),(0,G.jsx)(Uh,{label:`Hide controls (C)`,children:(0,G.jsx)(Gl,{variant:`subtle`,color:`gray`,size:`sm`,"aria-label":`Hide controls`,onClick:e=>{e.stopPropagation(),n(!1)},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),children:(0,G.jsx)(AJ,{size:14})})})]}),(0,G.jsx)(RJ.Contents,{children:(0,G.jsxs)(J,{pt:`0.375em`,children:[s.length>0&&(0,G.jsx)(zJ,{id:`scene-select`,label:`Scene`,children:(0,G.jsx)(Gh,{id:`scene-select`,placeholder:`Select scene`,data:s,value:c,onChange:l,size:`xs`,radius:`xs`,searchable:!0,clearable:!1,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(u.length>0||d)&&(0,G.jsx)(zJ,{id:`splat-select`,label:`Splat`,children:(0,G.jsx)(Uh,{label:N??``,color:`red`,position:`bottom`,opened:N!==null,withArrow:!0,children:(0,G.jsx)(Gh,{id:`splat-select`,placeholder:g===void 0?`Select splat`:`Select splat or paste .spz URL`,data:u,value:f,onChange:e=>{p(e),P(null),I(!1)},searchable:g!==void 0,searchValue:j,onSearchChange:e=>{M(e),e&&P(null)},onKeyDown:L,size:`xs`,radius:`xs`,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})})}),(m?.control&&f!==null||F)&&h&&(0,G.jsx)(KJ,{scale:m?.scale??1,xOffset:m?.xOffset??0,yOffset:m?.yOffset??0,zOffset:m?.zOffset??0,roll:m?.roll??0,pitch:m?.pitch??0,yaw:m?.yaw??0,onCalibrate:h}),_.length>0&&(0,G.jsx)(zJ,{id:`policy-select`,label:`Policy`,children:(0,G.jsx)(Gh,{id:`policy-select`,placeholder:`Select policy`,data:_,value:v,onChange:b,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),x.length>0&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(zJ,{id:`motion-select`,label:`Motion`,children:(0,G.jsx)(Gh,{id:`motion-select`,placeholder:`Select motion`,data:x,value:S,onChange:C,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(0,G.jsx)(J,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(nf,{label:`Show reference`,checked:w,onChange:e=>T(e.currentTarget.checked),size:`xs`})})]}),B.length>0&&R.some(e=>e.config.type===`slider`||e.config.type===`checkbox`)&&(0,G.jsx)(G.Fragment,{children:B.map(e=>{let t=ie(e);return t.length===0?null:(0,G.jsx)(BJ,{label:JJ(e),expandByDefault:!0,children:t.map(e=>e.config.type===`checkbox`?(0,G.jsx)(XJ,{command:e,value:ee[e.id]??0,onChange:ne,disabled:!E},e.id):e.config.type===`slider`?(0,G.jsx)(YJ,{command:e,value:ee[e.id]??0,onChange:ne,disabled:!E,enabledWhenValue:e.config.enabled_when?ee[cF(e.groupName,e.config.enabled_when)]:void 0},e.id):null)},e)})}),(0,G.jsx)(pp,{mb:`xs`,mx:`xs`}),(0,G.jsx)(J,{px:`xs`,pb:`xs`,children:(0,G.jsx)(yf,{variant:`light`,color:`red`,size:`xs`,fullWidth:!0,leftSection:(0,G.jsx)(kJ,{size:14}),onClick:re,children:`Reset`})})]})})]})]})}function QJ(e,t,n){return Object.keys(e[t]).reduce((e,t)=>(e[t]=`var(--mantine-${n}-${t})`,e),{})}function $J(e,t){return e in t.breakpoints?t.breakpoints[e]:ze(e)}function eY(e){let t=Un(In,e),n=QJ(t,`fontSizes`,`font-size`),r=QJ(t,`lineHeights`,`line-height`),i=QJ(t,`shadows`,`shadow`),a=QJ(t,`radius`,`radius`),o=QJ(t,`spacing`,`spacing`),s=Object.keys(t.headings.sizes).reduce((e,t)=>(e[t]={fontSize:`var(--mantine-${t}-font-size)`,lineHeight:`var(--mantine-${t}-line-height)`,fontWeight:`var(--mantine-${t}-font-weight)`},e),{}),c=Object.keys(t.colors).reduce((e,t)=>(e[t]={0:`var(--mantine-color-${t}-0)`,1:`var(--mantine-color-${t}-1)`,2:`var(--mantine-color-${t}-2)`,3:`var(--mantine-color-${t}-3)`,4:`var(--mantine-color-${t}-4)`,5:`var(--mantine-color-${t}-5)`,6:`var(--mantine-color-${t}-6)`,7:`var(--mantine-color-${t}-7)`,8:`var(--mantine-color-${t}-8)`,9:`var(--mantine-color-${t}-9)`,filled:`var(--mantine-color-${t}-filled)`,filledHover:`var(--mantine-color-${t}-filled-hover)`,light:`var(--mantine-color-${t}-light)`,lightHover:`var(--mantine-color-${t}-light-hover)`,lightColor:`var(--mantine-color-${t}-light-color)`,outline:`var(--mantine-color-${t}-outline)`,outlineHover:`var(--mantine-color-${t}-outline-hover)`},e),{primary:`var(--mantine-primary-color-filled)`,primaryColors:{0:`var(--mantine-primary-color-0)`,1:`var(--mantine-primary-color-1)`,2:`var(--mantine-primary-color-2)`,3:`var(--mantine-primary-color-3)`,4:`var(--mantine-primary-color-4)`,5:`var(--mantine-primary-color-5)`,6:`var(--mantine-primary-color-6)`,7:`var(--mantine-primary-color-7)`,8:`var(--mantine-primary-color-8)`,9:`var(--mantine-primary-color-9)`,filled:`var(--mantine-primary-color-filled)`,filledHover:`var(--mantine-primary-color-filled-hover)`,light:`var(--mantine-primary-color-light)`,lightHover:`var(--mantine-primary-color-light-hover)`,lightColor:`var(--mantine-primary-color-light-color)`,outline:`var(--mantine-primary-color-outline)`,outlineHover:`var(--mantine-primary-color-outline-hover)`},white:`var(--mantine-color-white)`,black:`var(--mantine-color-black)`,text:`var(--mantine-color-text)`,body:`var(--mantine-color-body)`,error:`var(--mantine-color-error)`,placeholder:`var(--mantine-color-placeholder)`,anchor:`var(--mantine-color-anchor)`,default:`var(--mantine-color-default)`,defaultHover:`var(--mantine-color-default-hover)`,defaultColor:`var(--mantine-color-default-color)`,defaultBorder:`var(--mantine-color-default-border)`,dimmed:`var(--mantine-color-dimmed)`,disabledBody:`var(--mantine-color-disabled)`,disabledText:`var(--mantine-color-disabled-color)`,disabledBorder:`var(--mantine-color-disabled-border)`});return{scale:`var(--mantine-scale)`,cursorType:`var(--mantine-cursor-type)`,webkitFontSmoothing:`var(--mantine-webkit-font-smoothing)`,mozFontSmoothing:`var(--mantine-moz-font-smoothing)`,lineHeight:`var(--mantine-line-height)`,fontFamily:`var(--mantine-font-family)`,fontFamilyMonospace:`var(--mantine-font-family-monospace)`,fontFamilyHeadings:`var(--mantine-font-family-headings)`,headingFontWeight:`var(--mantine-heading-font-weight)`,radiusDefault:`var(--mantine-radius-default)`,breakpoints:t.breakpoints,fontSizes:n,lineHeights:r,shadows:i,radius:a,headings:s,spacing:o,colors:c,rtlSelector:`[dir="rtl"] &`,darkSelector:`[data-mantine-color-scheme="dark"] &`,lightSelector:`[data-mantine-color-scheme="light"] &`,smallerThan:e=>`(max-width: ${$J(e,t)})`,largerThan:e=>`(min-width: ${$J(e,t)})`}}var tY=jr({fontFamily:`Inter`,autoContrast:!0,components:{Checkbox:nf.extend({defaultProps:{radius:`xs`}}),ColorInput:lp.extend({defaultProps:{radius:`xs`}}),Select:Gh.extend({defaultProps:{radius:`sm`}}),Textarea:Bp.extend({defaultProps:{radius:`xs`}}),TextInput:hg.extend({defaultProps:{radius:`xs`}}),NumberInput:Th.extend({defaultProps:{radius:`xs`}}),Paper:Jc.extend({defaultProps:{radius:`xs`,shadow:`0`}}),ActionIcon:Gl.extend({defaultProps:{variant:`subtle`,color:`gray`,radius:`xs`}}),Button:yf.extend({defaultProps:{radius:`xs`,styles:{label:{fontWeight:450}}}})}});eY(tY);var nY=(0,y.createContext)(void 0),rY=()=>{let e=(0,y.useContext)(nY);if(!e)throw Error(`useLoading must be used within a LoadingProvider`);return e},iY=({children:e})=>{let[t,n]=(0,y.useState)(!1),[r,i]=(0,y.useState)(null),a=(0,y.useRef)(0),o=(0,y.useCallback)(e=>{a.current+=1,e!==void 0&&i(e),a.current>0&&n(!0)},[]),s=(0,y.useCallback)(e=>{i(e)},[]),c=(0,y.useCallback)(()=>{a.current=Math.max(0,a.current-1),a.current===0&&(n(!1),i(null))},[]);return(0,G.jsx)(nY.Provider,{value:{isLoading:t,loadingMessage:r,showLoading:o,setLoadingMessage:s,hideLoading:c},children:e})},aY=()=>{let{isLoading:e,loadingMessage:t}=rY();return e?(0,G.jsx)(`div`,{className:`loader-overlay`,children:(0,G.jsxs)(`div`,{className:`loader-content`,children:[(0,G.jsx)(Ll,{size:64,type:`bars`}),t&&(0,G.jsx)(`p`,{className:`loader-message`,children:t})]})}):null},oY=!1;function sY(){typeof window>`u`||(window.__mjswanReady=!0,oY||(oY=!0,window.dispatchEvent(new CustomEvent(`mjswan:ready`))))}function cY(){typeof window>`u`||(window.__mjswanError=!0)}function lY(e){return e.toLowerCase().replace(/ /g,`_`).replace(/-/g,`_`)}function uY(e){return e.id?e.id:`main`}function dY(e,t){if(!e.scenes.length)return null;if(!t)return e.scenes[0];let n=t.trim().toLowerCase();return e.scenes.find(e=>e.name.toLowerCase()===n)||e.scenes.find(e=>lY(e.name)===n)||e.scenes[0]}function fY(e,t){if(!e.policies.length)return null;let n=e.policies.find(e=>e.default)??e.policies[0];if(!t)return n.name;let r=t.trim().toLowerCase();return(e.policies.find(e=>e.name.toLowerCase()===r)||e.policies.find(e=>lY(e.name)===r))?.name??n.name}function pY(e,t){if(!e?.motions?.length)return null;let n=e.motions.find(e=>e.default)??e.motions[0];if(!t)return n.name;let r=t.trim().toLowerCase();return(e.motions.find(e=>e.name.toLowerCase()===r)||e.motions.find(e=>lY(e.name)===r))?.name??n.name}function mY(e,t){return`${uY(e)}/assets/${t.path?t.path:`scene/${lY(t.name)}/scene.xml`}`.replace(/\/+/g,`/`)}function hY(e,t){return`${uY(e)}/assets/${t}`.replace(/\/+/g,`/`)}var gY=`panel`,_Y=`ref`;function vY(){let e=`/`.replace(/\/+$/,`/`),t=window.location.pathname.replace(/^\/+|\/+$/g,``),n=e.replace(/^\/+|\/+$/g,``);if(n&&(t===n?t=``:t.startsWith(`${n}/`)&&(t=t.slice(n.length+1))),!t)return null;let r=t.split(`/`)[0];return r===`main`||r.includes(`.`)||r===`assets`?null:r}function yY(e,t){let n=(e||`/`).replace(/\/+$/,`/`),r=new Set,i=(e,t)=>{if(e)try{let n=new URL(e,t||window.location.href).toString();r.add(n)}catch{r.add(e.replace(/\/+/g,`/`))}},a=`${window.location.origin}/`;i(`assets/config.json`,new URL(n,a).toString());let o=window.location.pathname.split(`/`).filter(Boolean);o.length>0&&o[o.length-1]===`index.html`&&o.pop(),o.length>0&&o[o.length-1]===(t??`main`)&&o.pop();let s=`/${o.join(`/`)}${o.length?`/`:``}`;return i(`assets/config.json`,`${window.location.origin}${s}`),i(`assets/config.json`),i(`../assets/config.json`),i(`../../assets/config.json`),Array.from(r)}async function bY(e,t){let n=new URLSearchParams(window.location.search).get(`config`),r=yY(e,t);if(n)try{r.unshift(new URL(n,window.location.href).toString())}catch{r.unshift(n)}let i=null;for(let e of r)try{let t=await fetch(e,{cache:`no-store`});if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.status}`);let n=await t.text(),r=n.trim();if((t.headers.get(`content-type`)||``).includes(`text/html`)||r.startsWith(`<!doctype`)||r.startsWith(`<html`))throw Error(`Received HTML from ${e}`);try{return JSON.parse(n)}catch(t){throw Error(`Invalid JSON from ${e}: ${t instanceof Error?t.message:String(t)}`)}}catch(e){i=e instanceof Error?e:Error(String(e))}throw i??Error(`Failed to load config.json.`)}function xY(e){return new URLSearchParams(e).get(gY)!==`0`}function SY(e){return new URLSearchParams(e).get(_Y)!==`0`}function CY(e){let t=`/`.replace(/\/+$/,`/`).replace(/^\//g,``).replace(/\/+$/g,``),n=t?`/${t}/`:`/`;return e&&e!==`main`&&(n+=`${e}/`),n}function wY({projectId:e,sceneName:t,policyName:n,panelVisible:r,showReference:i}){let a=CY(e),o=new URLSearchParams(window.location.search);t?o.set(`scene`,t):o.delete(`scene`),n?o.set(`policy`,n):o.delete(`policy`),r?o.delete(gY):o.set(gY,`0`),i?o.delete(_Y):o.set(_Y,`0`);let s=o.toString(),c=a+(s?`?${s}`:``)+window.location.hash;window.history.replaceState({},``,c)}function TY(){let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(null),[o,s]=(0,y.useState)(null),[c,l]=(0,y.useState)(null),[u,d]=(0,y.useState)(()=>SY(window.location.search)),[f,p]=(0,y.useState)(null),[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(null),[v,b]=(0,y.useState)(()=>xY(window.location.search)),x=(0,y.useRef)(null),{showLoading:S,hideLoading:C,setLoadingMessage:w}=rY(),T=(0,y.useMemo)(()=>vY(),[]),E=(0,y.useMemo)(()=>new URLSearchParams(window.location.search).get(`scene`),[]),D=(0,y.useMemo)(()=>new URLSearchParams(window.location.search).get(`policy`),[]);(0,y.useEffect)(()=>{S(`Loading…`),bY(`/`,T).then(e=>{t(e);let n=e.projects.find(e=>T===null?e.id===null:e.id===T);if(!n)throw Error(`Project "${T??`(main)`}" not found in config.json.`);r(n);let i=dY(n,E);a(i);let o=i?fY(i,D):null;s(o),l(pY(i?.policies.find(e=>e.name===o)??null,null))}).catch(e=>{console.error(`Failed to load config:`,e),p(e.message||`Failed to load config.`),C()})},[T,E,D,S,C]);let O=(0,y.useMemo)(()=>!n||!i?null:mY(n,i),[n,i]),k=(0,y.useMemo)(()=>!i||!o?null:i.policies.find(e=>e.name===o)??null,[i,o]),A=(0,y.useMemo)(()=>!n||!k?.config?null:hY(n,k.config),[n,k]),j=(0,y.useMemo)(()=>k?.motions?.length?k.motions.map(e=>({value:e.name,label:e.name})):[],[k]),M=(0,y.useMemo)(()=>!n||!i?.splats?.length?[]:i.splats.map(e=>e.path?{...e,url:hY(n,e.path)}:e),[n,i?.splats]),N=(0,y.useMemo)(()=>m?M.find(e=>e.name===m)??null:g?{name:`Custom`,url:g}:null,[M,m,g]),P=(0,y.useMemo)(()=>e?e.projects.map(e=>({value:e.id??`main`,label:e.name||(e.id??`Main`)})):[],[e]),F=(0,y.useMemo)(()=>n?n.scenes.map(e=>({value:e.name,label:e.name})):[],[n]),I=(0,y.useMemo)(()=>!i||!i.policies?[]:i.policies.map(e=>({value:e.name,label:e.name})),[i]),L=n?n.id??`main`:null,R=i?.name??null,z=(0,y.useCallback)(e=>{p(e.message),C(),cY()},[C]),B=(0,y.useCallback)(()=>{C(),sY()},[C]),V=(0,y.useCallback)(e=>{e===`Running simulation`||e===`Failed to load scene`||w(e)},[w]);(0,y.useEffect)(()=>{let e=i?.splats?.[0];h(e?e.name:null),_(null)},[i]);let ee=(0,y.useCallback)(e=>{x.current=e},[]);(0,y.useEffect)(()=>{l(pY(k,null)),d(!!k?.motions?.length)},[k]);let te=(0,y.useMemo)(()=>i?.splats?.length?i.splats.map(e=>({value:e.name,label:e.name})):[],[i?.splats]),ne=(0,y.useCallback)(async e=>{h(e),_(null);let t=x.current;if(!t)return;let n=e===null?null:M.find(t=>t.name===e)??null;if(!(e!==null&&!n)){S(e===null?`Removing splat…`:`Loading splat "${e}"…`);try{await t.setSplat(n)}catch(e){console.error(`Failed to load splat:`,e)}finally{C()}}},[M,S,C]),re=(0,y.useCallback)(async e=>{try{if(!(await fetch(e,{method:`HEAD`})).ok)return!1}catch{return!1}let t=x.current;if(!t)return!1;S(`Loading splat "Custom"…`);try{return await t.setSplat({name:`Custom`,url:e}),_(e),!0}catch(e){return console.error(`Failed to load custom splat:`,e),!1}finally{C()}},[S,C]),ie=(0,y.useCallback)((e,t,n,r,i,a,o)=>{let s=N??(g?{name:`Custom`,url:g}:null);s&&x.current?.calibrateSplat({...s,scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o})},[N,g]),ae=(0,y.useCallback)(e=>{wY({projectId:e.projectId??n?.id??null,sceneName:e.sceneName??i?.name??null,policyName:e.policyName??o,panelVisible:e.panelVisible??v,showReference:e.showReference??u})},[n?.id,i?.name,o,v,u]),oe=(0,y.useCallback)(t=>{if(!e||!t)return;let n=t===`main`?null:t,i=e.projects.find(e=>(e.id??`main`)===(n??`main`));if(!i)return;let o=dY(i,null);S(o?`Loading scene "${o.name}"…`:`Loading…`),r(i),a(o);let c=o?fY(o,null):null;s(c),l(pY(o?.policies.find(e=>e.name===c)??null,null)),ae({projectId:i.id,sceneName:o?.name??null,policyName:c})},[e,S,ae]),se=(0,y.useCallback)(e=>{if(!n||!e)return;let t=n.scenes.find(t=>t.name===e);if(!t)return;S(`Loading scene "${t.name}"…`),a(t);let r=fY(t,null);s(r),l(pY(t.policies.find(e=>e.name===r)??null,null)),ae({projectId:n.id,sceneName:e,policyName:r})},[n,S,ae]),H=(0,y.useCallback)(e=>{e!==o&&S(e?`Loading policy "${e}"…`:`Loading policy…`),s(e),l(pY(i?.policies.find(t=>t.name===e)??null,null)),ae({policyName:e})},[o,S,ae]),ce=(0,y.useCallback)(e=>{b(e),ae({panelVisible:e})},[ae]),le=(0,y.useCallback)(async e=>{let t=c;l(e);let n=x.current;if(n){S(e===null?`Clearing motion…`:`Loading motion "${e}"…`);try{await n.setSelectedMotion(e)===!1&&e!==null&&l(n.getSelectedMotionName()??t)}catch(e){console.error(`Failed to load motion:`,e)}finally{C()}}},[c,S,C]),ue=(0,y.useCallback)(e=>{d(e),x.current?.setReferenceVisible(e),ae({showReference:e})},[ae]);return f?(0,G.jsx)(dr,{theme:tY,defaultColorScheme:`auto`,children:(0,G.jsx)(`div`,{className:`app`,children:(0,G.jsxs)(`div`,{className:`hud hud-error`,children:[(0,G.jsx)(`h1`,{className:`hud-title`,children:`mjswan`}),(0,G.jsx)(`p`,{className:`hud-message`,children:f})]})})}):!n||!i||!O?null:(0,G.jsx)(dr,{theme:tY,defaultColorScheme:`auto`,children:(0,G.jsxs)(`div`,{className:`app`,children:[(0,G.jsx)(aY,{}),(0,G.jsx)(ZJ,{visible:v,onVisibleChange:ce,projects:P,projectValue:L,projectLabel:n?.name??`mjswan`,onProjectChange:oe,scenes:F,sceneValue:R,onSceneChange:se,splats:te,splatSection:i?.splatSection??!1,splatValue:m,onSplatChange:ne,splatConfig:N,onCalibrateSplat:ie,onSplatUrlLoad:re,policies:I,policyValue:o,onPolicyChange:H,motions:j,motionValue:c,onMotionChange:le,showReferenceMotion:u,onShowReferenceMotionChange:ue,commandsEnabled:!!A}),(0,G.jsx)(wJ,{scenePath:O,baseUrl:`/`,policyConfigPath:A,splatConfig:N,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:c,showReferenceMotion:u,onError:z,onReady:B,onStatusChange:V,onRuntimeReady:ee})]})})}function EY(){return(0,G.jsx)(iY,{children:(0,G.jsx)(TY,{})})}var DY=document.getElementById(`root`);DY&&(0,gg.createRoot)(DY).render((0,G.jsx)(y.StrictMode,{children:(0,G.jsx)(EY,{})}));
15597
+ ${a}`,s=n.createShaderModule({code:o,label:e.name});oR(`verbose`,()=>`[WebGPU] ${e.name} shader code: ${o}`);let c=n.createComputePipeline({compute:{module:s,entryPoint:`main`},layout:`auto`,label:e.name});return FI(e.name),{programInfo:e,computePipeline:c,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e==`number`?e:e.x,n=typeof e==`number`?1:e.y||1,r=typeof e==`number`?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw Error(`Total dispatch size exceeds WebGPU maximum.`);return[o,o,o]}else return[o,o,1]}}}),tq={};qF(tq,{WebGpuBackend:()=>aq});var nq,rq,iq,aq,oq=Z(()=>{qI(),ZL(),sR(),gR(),UR(),QK(),eq(),nq=(e,t)=>{if(t.length!==e.length)throw Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r<e.length;++r){let i=e[r].dataType;switch(t[r]){case`none`:n.push(``);break;case`type`:n.push(`${i}`);break;case`rank`:{let t=e[r].dims.length;n.push(`${i};${t}`);break}case`dims`:{let t=e[r].dims.join(`,`);n.push(`${i};${t}`);break}default:throw Error(`unsupported input dependency: ${t[r]}`)}}return n.join(`|`)},rq=(e,t,n)=>{let r=e.name;return e.shaderCache?.hint&&(r+=`[`+e.shaderCache.hint+`]`),r+=`:`+n+`:${nq(t,e.shaderCache?.inputDependencies??Array(t.length).fill(`dims`))}`,r},iq=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},aq=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus=`default`,this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw Error(`currentKernelCustomData(): currentKernelId is null. (should not happen)`);let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},i=e=>t.features.has(e)&&n.push(e)&&!0;i(`chromium-experimental-timestamp-query-inside-passes`)||i(`timestamp-query`),i(`shader-f16`),i(`subgroups`),this.device=await t.requestDevice(r),this.adapterInfo=new iq(t.info||await t.requestAdapterInfo()),this.gpuDataManager=HR(this),this.programManager=new $K(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,iR(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<`u`&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||=this.device.createCommandEncoder(),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType===`at-passes`&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&=(this.computePassEncoder.end(),null)}flush(){if(!this.commandEncoder)return;PI(),this.endComputePass();let e;this.queryType!==`none`&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!==`none`&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let r=n[e],i=r.kernelId,a=this.kernels.get(i),o=a.kernelType,s=a.kernelName,c=r.programName,l=r.inputTensorViews,u=r.outputTensorViews,d=t[e*2],f=t[e*2+1];typeof this.queryTimeBase>`u`&&(this.queryTimeBase=d);let p=Number(d-this.queryTimeBase),m=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(m))throw RangeError(`incorrect timestamp range`);if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:WL(e.dataType)})),outputsMetadata:u.map(e=>({dims:e.dims,dataType:WL(e.dataType)})),kernelId:i,kernelType:o,kernelName:s,programName:c,startTime:p,endTime:m});else{let e=``;l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${WL(t.dataType)}, `});let t=``;u.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${WL(e.dataType)}, `}),console.log(`[profiling] kernel "${i}|${o}|${s}|${c}" ${e}${t}start time: ${p} ns, execution time: ${m-p} ns`)}MI(`GPU`,`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),FI()}run(e,t,n,r,i,a){PI(e.name);let o=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(n===0)continue;let r=this.gpuDataManager.get(n);if(!r)throw Error(`no GPU data for input: ${n}`);o.push(r)}let{outputs:s,dispatchGroup:c,programUniforms:l}=e.getRunData(t),u=n.length===0?s.map((e,t)=>t):n;if(u.length!==s.length)throw Error(`Output size ${u.length} must be equal to ${s.length}.`);let d=[],f=[];for(let e=0;e<s.length;++e){if(!Number.isInteger(u[e])||u[e]<-3||u[e]>=a)throw Error(`Invalid output index: ${u[e]}`);if(u[e]===-3)continue;let t=u[e]===-1,n=u[e]===-2,o=t||n?i(s[e].dataType,s[e].dims):r(u[e],s[e].dataType,s[e].dims);if(d.push(o),o.data===0)continue;let c=this.gpuDataManager.get(o.data);if(!c)throw Error(`no GPU data for output: ${o.data}`);if(t&&this.temporaryData.push(c),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(c)}f.push(c)}if(o.length!==t.length||f.length!==d.length){if(f.length===0)return FI(e.name),d;throw Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let p;if(l){let e=0,t=[];l.forEach(n=>{let r=typeof n.data==`number`?[n.data]:n.data;if(r.length===0)return;let i=n.type===10?2:4,a,o;n.type===10?(o=r.length>4?16:r.length>2?8:r.length*i,a=r.length>4?16:i*r.length):(o=r.length<=2?r.length*i:16,a=16),e=Math.ceil(e/o)*o,t.push(e);let s=n.type===10?8:4;e+=r.length>4?Math.ceil(r.length/s)*a:r.length*i}),e=Math.ceil(e/16)*16;let n=new ArrayBuffer(e);l.forEach((e,r)=>{let i=t[r],a=typeof e.data==`number`?[e.data]:e.data;if(e.type===6)new Int32Array(n,i,a.length).set(a);else if(e.type===12)new Uint32Array(n,i,a.length).set(a);else if(e.type===10)new Uint16Array(n,i,a.length).set(a);else if(e.type===1)new Float32Array(n,i,a.length).set(a);else throw Error(`Unsupported uniform type: ${WL(e.type)}`)});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,n,0,e),this.gpuDataManager.release(r.id),p={offset:0,size:e,buffer:r.buffer}}let m=this.programManager.normalizeDispatchGroupSize(c),h=m[1]===1&&m[2]===1,g=rq(e,t,h),_=this.programManager.getArtifact(g);if(_||(_=this.programManager.build(e,m),this.programManager.setArtifact(g,_),oR(`info`,()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&_.uniformVariablesInfo){if(l.length!==_.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${l.length} in program "${_.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,r=typeof t.data==`number`?1:t.data.length,[i,a]=_.uniformVariablesInfo[e];if(n!==i||r!==a)throw Error(`Uniform variable ${e} mismatch: expect type ${i} with size ${a}, got type ${n} with size ${r} in program "${_.programInfo.name}".`)}}if(oR(`info`,()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!==`none`||this.sessionStatus===`capturing`){let e={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:d};this.pendingKernels.push(e),this.sessionStatus===`capturing`&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(_,o,f,m,p),FI(e.name),d}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=ZK.get(e);if(!i)throw Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,o=r.kernelEntry,s=r.attributes;if(this.currentKernelId!==null)throw Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,s[0]&&=(s[1]=s[0](s[1]),void 0),oR(`info`,()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope(`validation`),o(t,s[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${e}`)),1}finally{c&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${i}] ${a}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(n,r,a);return i.set(t,[o,n]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await BR(this,e,t);return hR(r.buffer,n)}}writeTimestamp(e){this.queryType===`inside-passes`&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType=`none`,(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>`u`?this.env.wasm.trace:this.env.trace))&&(this.device.features.has(`chromium-experimental-timestamp-query-inside-passes`)?this.queryType=`inside-passes`:this.device.features.has(`timestamp-query`)&&(this.queryType=`at-passes`),this.queryType!==`none`&&typeof this.querySet>`u`&&(this.querySet=this.device.createQuerySet({type:`timestamp`,count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){oR(`info`,`captureBegin`),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus=`capturing`}captureEnd(){oR(`info`,`captureEnd`),this.flush(),this.sessionStatus=`default`}replay(){oR(`info`,`replay`),this.sessionStatus=`replaying`;let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let r=0;r<n;r++){let n=this.getComputePassEncoder(),i=e[r];this.writeTimestamp(this.pendingDispatchNumber*2),n.setPipeline(i.computePipeline),n.setBindGroup(0,i.bindGroup),n.dispatchWorkgroups(...i.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!==`none`&&this.pendingKernels.push(t[r]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType===`at-passes`)&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus=`default`}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),sq={};qF(sq,{init:()=>uq});var cq,lq,uq,dq=Z(()=>{ZL(),sR(),mR(),MR(),cq=class e{constructor(e,t,n,r){this.module=e,this.dataType=t,this.data=n,this.dims=r}getFloat32Array(){if(this.dataType!==1)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error(`Invalid data type`);let e=Q.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(Q.size(t)!==Q.size(this.dims))throw Error(`Invalid new shape`);return new e(this.module,this.dataType,this.data,t)}},lq=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let r=e.PTR_SIZE,i=n/e.PTR_SIZE,a=r===4?`i32`:`i64`;this.opKernelContext=Number(e.getValue(r*i++,a));let o=Number(e.getValue(r*i++,a));this.outputCount=Number(e.getValue(r*i++,a)),this.customDataOffset=Number(e.getValue(r*i++,`*`)),this.customDataSize=Number(e.getValue(r*i++,a));let s=[];for(let t=0;t<o;t++){let t=Number(e.getValue(r*i++,a)),n=Number(e.getValue(r*i++,`*`)),o=Number(e.getValue(r*i++,a)),c=[];for(let t=0;t<o;t++)c.push(Number(e.getValue(r*i++,a)));s.push(new cq(e,t,n,c))}this.inputs=s}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>typeof e==`number`?this.inputs[e]:e)??this.inputs,r=t?.outputs??[];return this.backend.run(e,n,r,(e,t,n)=>new cq(this.module,t,this.output(e,n),n),(e,t)=>{let n=GL(e,t);if(!n)throw Error(`Unsupported data type: ${e}`);let r=n>0?this.backend.gpuDataManager.create(n).id:0;return new cq(this.module,e,r,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,r=n===4?`i32`:`i64`,i=this.module.stackAlloc((1+t.length)*n);this.module.setValue(i,t.length,r);for(let e=0;e<t.length;e++)this.module.setValue(i+n*(e+1),t[e],r);return this.module._JsepOutput(this.opKernelContext,e,i)}catch(n){throw Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},uq=async(e,t,n,r)=>{let i=t.jsepInit;if(!i)throw Error(`Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.`);if(e===`webgpu`){let e=(oq(),YF(tq)).WebGpuBackend,a=new e;await a.initialize(n,r),i(`webgpu`,[a,e=>a.alloc(Number(e)),e=>a.free(e),(e,n,r,i=!1)=>{if(i)oR(`verbose`,()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(e)}, dst=${Number(n)}, size=${Number(r)}`),a.memcpy(Number(e),Number(n));else{oR(`verbose`,()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(e)}, gpuDataId=${Number(n)}, size=${Number(r)}`);let i=t.HEAPU8.subarray(Number(e>>>0),Number(e>>>0)+Number(r));a.upload(Number(n),i)}},async(e,n,r)=>{oR(`verbose`,()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${e}, dataOffset=${n}, size=${r}`),await a.download(Number(e),()=>t.HEAPU8.subarray(Number(n)>>>0,Number(n+r)>>>0))},(e,n,r)=>a.createKernel(e,Number(n),r,t.UTF8ToString(t._JsepGetNodeName(Number(n)))),e=>a.releaseKernel(e),(e,n,r,i)=>{oR(`verbose`,()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${e}, contextDataOffset=${n}`);let o=new lq(t,a,Number(n));return a.computeKernel(Number(e),o,i)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let e=new jR(n);i(`webnn`,[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,r,i,a)=>e.ensureTensor(t,n,r,i,a),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),fq,pq,mq,hq,gq,_q,vq,yq,bq,xq,Sq,Cq,wq,Tq=Z(()=>{qI(),FL(),HL(),ZL(),kL(),NL(),$L(),fq=(e,t)=>{OL()._OrtInit(e,t)!==0&&ML(`Can't initialize onnxruntime.`)},pq=async e=>{fq(e.wasm.numThreads,qL(e.logLevel))},mq=async(e,t)=>{OL().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);{let r=(dq(),YF(sq)).init;t===`webgpu`&&await r(`webgpu`,OL(),e,n),t===`webnn`&&await r(`webnn`,OL(),e)}},hq=new Map,gq=e=>{let t=OL(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&ML(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},_q=(e,t)=>{let n=OL(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&ML(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e<c;e++){let t=Number(n.getValue(i+8+e*r,`*`));l.push(t===0?Number(n.getValue(i+8+(e+c)*r,`*`)):n.UTF8ToString(t))}return[o,s,l]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},vq=e=>{let t=OL(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},yq=async(e,t)=>{let n,r,i=OL();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=vq(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await VL(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(QL(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&ML(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=gq(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;t<e;t++){let[e,n,r]=_q(a,t);e===0&&ML(`Can't get an input name.`),l.push(e);let o=i.UTF8ToString(e);p.push(o),h.push(n===0?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:WL(n),shape:r})}for(let n=0;n<d;n++){let[r,o,s]=_q(a,n+e);r===0&&ML(`Can't get an output name.`),u.push(r);let c=i.UTF8ToString(r);m.push(c),g.push(o===0?{name:c,isTensor:!1}:{name:c,isTensor:!0,type:WL(o),shape:s});{if(f&&t?.preferredOutputLocation===void 0){_.push(`gpu-buffer`);continue}let e=typeof t?.preferredOutputLocation==`string`?t.preferredOutputLocation:t?.preferredOutputLocation?.[c]??`cpu`,n=i.webnnIsGraphOutput;if(e===`cpu`&&n&&n(a,c)){_.push(`ml-tensor-cpu-output`);continue}if(e!==`cpu`&&e!==`cpu-pinned`&&e!==`gpu-buffer`&&e!==`ml-tensor`)throw Error(`Not supported preferred output location: ${e}.`);if(f&&e!==`gpu-buffer`)throw Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(e)}}let v=null;return _.some(e=>e===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&ML(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>XL(e))}),hq.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&ML(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&ML(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ML(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},bq=e=>{let t=OL(),n=hq.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&ML(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&ML(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&ML(`Can't release session.`),hq.delete(e)},xq=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=OL(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=GL(UL(l),u);{let e=s.jsepRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(r,a,t,m)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=GL(UL(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,UL(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;e<t.length;e++){if(typeof t[e]!=`string`)throw TypeError(`tensor data at index ${e} is not a string`);s.setValue(p+e*c,AL(t[e],n),`*`)}}else{let e=s.webnnIsGraphInput,a=s.webnnIsGraphOutput;if(l!==`string`&&e&&a){let o=s.UTF8ToString(i);if(e(r,o)||a(r,o)){let e=UL(l);m=GL(e,u),f=`ml-tensor`;let n=s.webnnCreateTemporaryTensor,i=s.webnnUploadTensor;if(!n||!i)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);let a=await n(r,e,u);i(a,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),p=a}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}else m=t.byteLength,p=s._malloc(m),n.push(p),s.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,m),p)}}let h=s.stackSave(),g=s.stackAlloc(4*u.length);try{u.forEach((e,t)=>s.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(UL(l),p,m,g,u.length,XL(f));e===0&&ML(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},Sq=async(e,t,n,r,i,a)=>{let o=OL(),s=o.PTR_SIZE,c=hq.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),D=o.stackAlloc(g*s);try{[_,v]=PL(a),II(`wasm prepareInputOutputTensor`);for(let r=0;r<h;r++)await xq(n[r],y,x,e,u[t[r]],t[r],p);for(let t=0;t<g;t++)await xq(i[t],b,x,e,d[r[t]],h+r[t],p);LI(`wasm prepareInputOutputTensor`);for(let e=0;e<h;e++)o.setValue(w+e*s,y[e],`*`),o.setValue(T+e*s,u[t[e]],`*`);for(let e=0;e<g;e++)o.setValue(E+e*s,b[e],`*`),o.setValue(D+e*s,d[r[e]],`*`);if(f&&!m){let{handle:n,outputPreferredLocations:a,outputPreferredLocationsEncoded:s}=f;if(u.length!==h)throw Error(`input count from feeds (${h}) is expected to be always equal to model's input count (${u.length}).`);II(`wasm bindInputsOutputs`);for(let r=0;r<h;r++){let i=t[r];await o._OrtBindInput(n,u[i],y[r])!==0&&ML(`Can't bind input[${r}] for session=${e}.`)}for(let t=0;t<g;t++){let c=r[t];i[t]?.[3]?(S.push(b[t]),o._OrtBindOutput(n,d[c],b[t],0)!==0&&ML(`Can't bind pre-allocated output[${t}] for session=${e}.`)):o._OrtBindOutput(n,d[c],0,s[c])!==0&&ML(`Can't bind output[${t}] to ${a[t]} for session=${e}.`)}LI(`wasm bindInputsOutputs`),hq.set(e,[l,u,d,f,p,!0])}o.jsepOnRunStart?.(l),o.webnnOnRunStart?.(l);let c;c=f?await o._OrtRunWithBinding(l,f.handle,g,E,_):await o._OrtRun(l,T,w,h,D,g,E,_),c!==0&&ML(`failed to call OrtRun().`);let C=[],O=[];II(`wasm ProcessOutputTensor`);for(let t=0;t<g;t++){let n=Number(o.getValue(E+t*s,`*`));if(n===b[t]||S.includes(b[t])){C.push(i[t]),n!==b[t]&&o._OrtReleaseTensor(n)!==0&&ML(`Can't release tensor.`);continue}let a=o.stackSave(),c=o.stackAlloc(4*s),l=!1,u,d=0;try{o._OrtGetTensorData(n,c,c+s,c+2*s,c+3*s)!==0&&ML(`Can't access output tensor data on index ${t}.`);let i=s===4?`i32`:`i64`,a=Number(o.getValue(c,i));d=o.getValue(c+s,`*`);let p=o.getValue(c+s*2,`*`),m=Number(o.getValue(c+s*3,i)),h=[];for(let e=0;e<m;e++)h.push(Number(o.getValue(p+e*s,i)));o._OrtFree(p)!==0&&ML(`Can't free memory for tensor dims.`);let g=h.reduce((e,t)=>e*t,1);u=WL(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t<g;t++){let n=o.getValue(d+t*s,`*`),r=o.getValue(d+(t+1)*s,`*`),i=t===g-1?void 0:r-n;e.push(o.UTF8ToString(n,i))}C.push([u,h,e,`cpu`])}else if(_===`gpu-buffer`&&g>0){let e=o.jsepGetBuffer;if(!e)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let t=e(d),r=GL(a,g);if(r===void 0||!JL(u))throw Error(`Unsupported data type: ${u}`);l=!0,C.push([u,h,{gpuBuffer:t,download:o.jsepCreateDownloader(t,r,u),dispose:()=>{o._OrtReleaseTensor(n)!==0&&ML(`Can't release tensor.`)}},`gpu-buffer`])}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(GL(a,g)===void 0||!YL(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,O.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(KL(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&ML(`Can't clear bound outputs.`),hq.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return LI(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},Cq=e=>{let t=OL(),n=hq.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&ML(`Can't get an profile file name.`),t._OrtFree(i)},wq=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),Eq,Dq,Oq,kq,Aq,jq,Mq,Nq,Pq,Fq,Iq,Lq,Rq,zq,Bq,Vq,Hq,Uq,Wq=Z(()=>{qI(),Tq(),kL(),yL(),Eq=()=>!!cI.wasm.proxy&&typeof document<`u`,Oq=!1,kq=!1,Aq=!1,Nq=new Map,Pq=(e,t)=>{let n=Nq.get(e);n?n.push(t):Nq.set(e,[t])},Fq=()=>{if(Oq||!kq||Aq||!Dq)throw Error(`worker not ready`)},Iq=e=>{switch(e.data.type){case`init-wasm`:Oq=!1,e.data.err?(Aq=!0,Mq[1](e.data.err)):(kq=!0,Mq[0]()),jq&&=(URL.revokeObjectURL(jq),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=Nq.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},Lq=async()=>{if(!kq){if(Oq)throw Error(`multiple calls to 'initWasm()' detected.`);if(Aq)throw Error(`previous call to 'initWasm()' failed.`);if(Oq=!0,Eq())return new Promise((e,t)=>{Dq?.terminate(),gL().then(([n,r])=>{try{Dq=r,Dq.onerror=e=>t(e),Dq.onmessage=Iq,Mq=[e,t];let i={type:`init-wasm`,in:cI};!i.in.wasm.wasmPaths&&(n||oL)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm`,``+import.meta.url).href}),Dq.postMessage(i),jq=n}catch(e){t(e)}},t)});try{await DL(cI.wasm),await pq(cI),kq=!0}catch(e){throw Aq=!0,e}finally{Oq=!1}}},Rq=async e=>{if(Eq())return Fq(),new Promise((t,n)=>{Pq(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:cI}};Dq.postMessage(r)});await mq(cI,e)},zq=async e=>Eq()?(Fq(),new Promise((t,n)=>{Pq(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};Dq.postMessage(r,[e.buffer])})):vq(e),Bq=async(e,t)=>{if(Eq()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return Fq(),new Promise((n,r)=>{Pq(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Dq.postMessage(i,a)})}else return yq(e,t)},Vq=async e=>{if(Eq())return Fq(),new Promise((t,n)=>{Pq(`release`,[t,n]);let r={type:`release`,in:e};Dq.postMessage(r)});bq(e)},Hq=async(e,t,n,r,i,a)=>{if(Eq()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return Fq(),new Promise((i,o)=>{Pq(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};Dq.postMessage(c,wq(s))})}else return Sq(e,t,n,r,i,a)},Uq=async e=>{if(Eq())return Fq(),new Promise((t,n)=>{Pq(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};Dq.postMessage(r)});Cq(e)}}),Gq,Kq,qq,Jq=Z(()=>{qI(),Wq(),ZL(),JI(),$L(),Gq=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},Kq=e=>{switch(e[3]){case`cpu`:return new AI(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!JL(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return AI.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!YL(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return AI.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},qq=class{async fetchModelAndCopyToWasmMemory(e){return zq(await QL(e))}async loadModel(e,t){PI();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Bq(n,t),FI()}async dispose(){return Vq(this.sessionId)}async run(e,t,n){PI();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>Gq(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?Gq(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await Hq(this.sessionId,i,s,o,c,n),u={};for(let e=0;e<l.length;e++)u[this.outputNames[o[e]]]=a[e]??Kq(l[e]);return FI(),u}startProfiling(){}endProfiling(){Uq(this.sessionId)}}}),Yq={};qF(Yq,{OnnxruntimeWebAssemblyBackend:()=>Zq,initializeFlags:()=>Xq,wasmBackend:()=>Qq});var Xq,Zq,Qq,$q=Z(()=>{qI(),Wq(),Jq(),Xq=()=>{(typeof cI.wasm.initTimeout!=`number`||cI.wasm.initTimeout<0)&&(cI.wasm.initTimeout=0);let e=cI.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),cI.wasm.simd=!1),typeof cI.wasm.proxy!=`boolean`&&(cI.wasm.proxy=!1),typeof cI.wasm.trace!=`boolean`&&(cI.wasm.trace=!1),typeof cI.wasm.numThreads!=`number`||!Number.isInteger(cI.wasm.numThreads)||cI.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)cI.wasm.numThreads=1;else{let e=typeof navigator>`u`?KF(`node:os`).cpus().length:navigator.hardwareConcurrency;cI.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Zq=class{async init(e){Xq(),await Lq(),await Rq(e)}async createInferenceSessionHandler(e,t){let n=new qq;return await n.loadModel(e,t),n}},Qq=new Zq});qI(),qI(),qI();var eJ=`1.24.3`;{let e=($q(),YF(Yq)).wasmBackend;QF(`webgpu`,e,5),QF(`webnn`,e,5),QF(`cpu`,e,10),QF(`wasm`,e,10)}Object.defineProperty(cI.versions,"web",{value:eJ,enumerable:!0});var tJ=class{constructor(e,t){this.runner=e,this.config=t}},nJ=class extends tJ{constructor(e,t){super(e,t),this.store=new IF,this.cachedSize=null,this.graph=t.graph,this.params=t.params??{}}get size(){return this.cachedSize??this.inferSize()}reset(e){this.store.reset()}compute(e){let t=LF(this.graph,{runner:this.runner,state:e,params:this.params},this.store);if(t instanceof Float32Array)return this.cachedSize=t.length,t;if(typeof t==`number`)return this.cachedSize=1,new Float32Array([t]);if(typeof t==`boolean`)return this.cachedSize=1,new Float32Array([+!!t]);if(t instanceof Uint8Array){this.cachedSize=t.length;let e=new Float32Array(t.length);for(let n=0;n<t.length;n++)e[n]=t[n];return e}return this.cachedSize=0,new Float32Array}inferSize(){this.runner.getContext();let e={jointPos:new Float32Array(this.runner.getNumActions())};return this.compute(e),this.cachedSize??0}},rJ=class{constructor(e,t={}){this.config=e,this.options=t,this.policyModule=null,this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null,this.context=null,this.policyJointNames=(e.policy_joint_names??[]).slice(),this.numActions=e.policy_num_actions??this.policyJointNames.length,this.lastActions=new Float32Array(this.numActions),this.defaultJointPos=this.normalizeArray(e.default_joint_pos??[],this.numActions,0),this.encoderBias=this.normalizeArray(e.encoder_bias??[],this.numActions,0)}async init(e){this.context=e,this.policyModule=await this.buildPolicyModule(e),this.buildObservationGroups()}reset(e){this.lastActions.fill(0),this.policyModule?.reset();for(let t of Object.values(this.obsGroups))for(let n of t)n.reset&&n.reset(e);if(e){for(let[t,n]of Object.entries(this.historyConfig))if(n.steps>1){let r=this.buildFrame(this.obsGroups[t]??[],e),i=this.historyBuffers[t];for(let e=0;e<n.steps;e++)i.set(r,e*r.length)}}}update(e){this.policyModule?.update();for(let t of Object.values(this.obsGroups))for(let n of t)n.update&&n.update(e)}collectObservationsByKey(e){this.update(e);let t={};for(let[n,r]of Object.entries(this.obsGroups)){let i=this.historyConfig[n];if(i&&i.steps>1){let i=this.buildFrame(r,e),a=this.historyBuffers[n];for(let e=a.length-1;e>=i.length;e--)a[e]=a[e-i.length];a.set(i,0),t[n]=new Float32Array(a)}else t[n]=this.buildFrame(r,e)}return t}collectObservations(e){let t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];let n=Object.keys(t)[0];return n?t[n]:new Float32Array}async preloadAll(){let e=[];for(let t of Object.values(this.obsGroups))for(let n of t)typeof n.preload==`function`&&e.push(n.preload());await Promise.all(e)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];let e=Object.keys(this.obsSizes)[0];return e?this.obsSizes[e]:0}getObservationLayout(){if(this.defaultObsKey&&this.obsLayouts[this.defaultObsKey])return this.obsLayouts[this.defaultObsKey].map(e=>({...e}));let e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(e=>({...e})):[]}getPolicyModuleContext(){return this.policyModule?.getContext()??{}}getPolicyModule(){return this.policyModule}getContext(){return this.context}getPolicyJointNames(){return this.policyJointNames.slice()}getNumActions(){return this.numActions}getDefaultJointPos(){return new Float32Array(this.defaultJointPos)}getEncoderBias(){return new Float32Array(this.encoderBias)}getLastActions(){return new Float32Array(this.lastActions)}getConfig(){return this.config}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){let t=this.options.policyModules??{},n=this.config.policy_module,r=n?t[n]:t.default;if(n&&!r)throw Error(`Unknown policy module: ${n}`);if(!r)return null;let i=new r(this.config);return await i.init(e),i}buildObservationGroups(){let e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;let n=t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new nJ(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);return new r(this,t)};for(let[r,i]of Object.entries(t)){if(Array.isArray(i)){let e=i.map(n);this.registerGroup(r,e,i);continue}if(i&&typeof i==`object`){let t=i;if(Array.isArray(t.components)){let n=t.components.map(t=>{let n=t;if(n.kind===`observation`&&Array.isArray(n.nodes))return new nJ(this,{name:`DslObservation`,graph:{kind:`observation`,nodes:n.nodes,output:n.output??``},params:n.params});let r=e[t.name];if(!r)throw Error(`Unknown observation type: ${t.name}`);let i={...t,history_steps:1};return new r(this,i)}),i=Math.max(1,Math.floor(t.history_steps??1)),a=!!t.interleaved;this.registerGroup(r,n,t.components,{steps:i,interleaved:a})}}}this.obsGroups.policy?this.defaultObsKey=`policy`:this.obsGroups.observation?this.defaultObsKey=`observation`:this.obsGroups.obs_history?this.defaultObsKey=`obs_history`:this.defaultObsKey=Object.keys(this.obsGroups)[0]??null}registerGroup(e,t,n,r){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((e,t)=>({name:n[t]?.name??`obs_${t}`,size:e.size}));let i=this.obsLayouts[e].reduce((e,t)=>e+t.size,0);r&&r.steps>1?(this.historyConfig[e]=r,this.historyBuffers[e]=new Float32Array(i*r.steps),this.obsSizes[e]=i*r.steps):this.obsSizes[e]=i}buildFrame(e,t){let n=e.reduce((e,t)=>e+t.size,0),r=new Float32Array(n),i=0;for(let n of e){let e=n.compute(t),a=e instanceof Float32Array?e:Float32Array.from(e);if(a.length!==n.size)throw Error(`Observation size mismatch: expected ${n.size}, got ${a.length}`);r.set(a,i),i+=a.length}return r}normalizeArray(e,t,n){let r=new Float32Array(t);for(let i=0;i<t;i++)r[i]=typeof e[i]==`number`?e[i]:n;return r}};cI.wasm.proxy=!1,cI.wasm.numThreads=1,typeof __ORT_CDN_BASE__<`u`&&(cI.wasm.wasmPaths=__ORT_CDN_BASE__);var iJ=class{constructor(e){if(!e?.path)throw Error(`OnnxModule requires a path.`);this.config=e,this.session=null;let t=e.meta?.in_keys??[`policy`],n=e.meta?.out_keys??[`action`];this.configuredInKeys=t.map(e=>Array.isArray(e)?e.join(`,`):e),this.inKeys=[...this.configuredInKeys],this.outKeys=n.map(e=>Array.isArray(e)?e.join(`,`):e),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}async init(){let e=await fetch(this.config.path);if(!e.ok)throw Error(`Failed to fetch ONNX model: ${e.status}`);let t=await e.arrayBuffer();this.session=await VI.create(t,{executionProviders:[`wasm`],graphOptimizationLevel:`all`}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes(`adapt_hx`)}initInput(){let e={};return this.isRecurrent&&(e.is_init=new AI(`bool`,[!0],[1]),e.adapt_hx=new AI(`float32`,new Float32Array(128),[1,128])),this.inKeys.includes(`time_step`)&&(e.time_step=new AI(`float32`,new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw Error(`OnnxModule not initialized.`);let t={};for(let n=0;n<this.inKeys.length;n++){let r=this.inKeys[n],i=this.session.inputNames[n];if(!i||!e[r])throw Error(`Missing ONNX input for key: ${r}`);t[i]=e[r]}let n=await this.session.run(t),r={};for(let e=0;e<this.outKeys.length;e++){let t=this.outKeys[e],i=this.session.outputNames[e];i&&n[i]&&(r[t]=n[i])}let i={};return this.isRecurrent&&r[`next,adapt_hx`]&&(i.is_init=new AI(`bool`,[!1],[1]),i.adapt_hx=r[`next,adapt_hx`]),[r,i]}dispose(){this.session?.release?.(),this.session=null}inferInputKeys(){if(!this.session)return;let e=this.session.inputNames;if(e.length<=1){this.inKeys=[...this.configuredInKeys];return}if(this.configuredInKeys.length===e.length){this.inKeys=[...this.configuredInKeys];return}this.inKeys=e.map(e=>this.configuredInKeys.includes(e)?e:e===`obs`&&this.configuredInKeys.includes(`policy`)?`policy`:e)}},aJ=class{constructor(e,t,n,r){this.mujoco=e,this.mjModel=t,this.mjData=n;let i=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(let e of r){let n=i.indexOf(e);if(n<0)throw Error(`Joint "${e}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[n]),this.qvelAdr.push(t.jnt_dofadr[n]),this.jointIndices.push(n)}this.numActions=r.length,this.ctrlAdr=this.buildCtrlAdr()}build(){let e=this.mjData.qpos,t=this.mjData.qvel,n=new Float32Array(this.numActions),r=new Float32Array(this.numActions);for(let i=0;i<this.numActions;i++)n[i]=e[this.qposAdr[i]],r[i]=t[this.qvelAdr[i]];return{jointPos:n,jointVel:r,rootPos:new Float32Array([e[0],e[1],e[2]]),rootQuat:new Float32Array([e[3],e[4],e[5],e[6]]),rootLinVel:new Float32Array([t[0],t[1],t[2]]),rootAngVel:new Float32Array([t[3],t[4],t[5]])}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}getControlMappingFor(e,t){if(!this.ctrlAdr)return null;let n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[],o=[],s=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(this.ctrlAdr[e]),a.push(this.qposAdr[e]),o.push(this.qvelAdr[e]),s.push(e));return i.length===0?null:{ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s}}getCtrlMappingByActuatorNames(e){let t=this.getActuatorNames(this.mjModel),n=e.map(e=>RegExp(`^(?:${e})$`)),r=e=>n.some(t=>t.test(e)),i=[],a=[];for(let e=0;e<t.length;e++)r(t[e])&&(i.push(e),a.push(i.length-1));return i.length>0?{ctrlAdr:i,actionIndices:a}:null}getActuatorNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.nu;i++){let a=e.name_actuatoradr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;let e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let n=0;n<this.mjModel.nu;n++){let r=this.mjModel.actuator_trntype[n];e===void 0||r===e?t.push(this.mjModel.actuator_trnid[2*n]):t.push(-1)}let n=[];for(let e of this.jointIndices){let r=t.findIndex(t=>t===e);if(r<0)return null;n.push(r)}return n}getJointNames(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;let s=n.decode(t.subarray(a,o));!s&&i===0&&(s=`floating_base_joint`),r.push(s)}return r}},oJ=class{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}},sJ=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},cJ=class extends oJ{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.tracking=new sJ(n)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}},lJ=class{constructor(e){this.policyJointNames=(e.policy_joint_names??[]).slice(),this.datasetJointNames=(e.dataset_joint_names??[]).slice(),this.nJoints=this.datasetJointNames.length||this.policyJointNames.length||0,this.refJointPos=[],this.refRootPos=[],this.refRootQuat=[],this.refIdx=0,this.refLen=0,this.currentName=`default`,this.currentDone=!0}reset(e){let t=e?.jointPos??new Float32Array(this.nJoints),n=e?.rootPos??new Float32Array([0,0,0]),r=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(n)],this.refRootQuat=[Float32Array.from(r)],this.refIdx=0,this.refLen=1,this.currentDone=!0,this.currentName=`default`}advance(){this.refLen<=1||this.refIdx<this.refLen-1&&(this.refIdx+=1,this.refIdx===this.refLen-1&&(this.currentDone=!0))}isReady(){return this.refLen>0}},uJ=class extends oJ{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);let t=this.config.policy_joint_names??[],n={...this.config.tracking,policy_joint_names:t};this.locomotion=new lJ(n)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}},dJ=class{constructor(e){this.config=e}};function fJ(e,t){return e+Math.random()*(t-e)}function pJ(e){let t=new Uint8Array(e.names),n=new TextDecoder,r=[];for(let i=0;i<e.njnt;i++){let a=e.name_jntadr[i],o=a;for(;o<t.length&&t[o]!==0;)o++;r.push(n.decode(t.subarray(a,o)))}return r}function mJ(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}var hJ=class extends dJ{constructor(e){super(e),this.mutations=e.mutations??[]}onReset(e){let{mjModel:t,mjData:n}=e;if(!(!t||!n))for(let e of this.mutations)switch(e.target){case`joint_qpos`:this.applyJointOffset(t,n,e,`qpos`);break;case`joint_qvel`:this.applyJointOffset(t,n,e,`qvel`);break;case`freejoint_pos`:this.applyFreejointPos(t,n,e);break;case`freejoint_yaw`:this.applyFreejointYaw(t,n,e);break}}resolveJointIndices(e,t){let n=t.select??{};if(n.joint_ids&&n.joint_ids.length>0)return n.joint_ids.filter(t=>t>=0&&t<e.njnt);let r=pJ(e);return n.joint_names&&n.joint_names.length>0?n.joint_names.map(e=>this.findJointIndex(r,e,n.entity_name)).filter(e=>e!==null):r.map((e,t)=>({name:e,idx:t})).filter(({name:t,idx:r})=>e.jnt_type[r]===0?!1:n.entity_name?t===n.entity_name||t.startsWith(`${n.entity_name}/`):!0).map(({idx:e})=>e)}findJointIndex(e,t,n){let r=e.indexOf(t);if(r>=0)return r;if(n){let r=e.indexOf(`${n}/${t}`);if(r>=0)return r}let i=e.map((e,t)=>({name:e,idx:t})).filter(({name:e})=>e===t||e.endsWith(`/${t}`));if(i.length===1)return i[0].idx;if(n){let e=i.find(({name:e})=>e===n||e.startsWith(`${n}/`));if(e)return e.idx}return null}applyJointOffset(e,t,n,r){if(n.sample.dist!==`uniform`)return;let{low:i,high:a}=n.sample;for(let o of this.resolveJointIndices(e,n)){let s=e.jnt_type[o];if(!(s!==2&&s!==3))if(r===`qpos`){let r=e.jnt_qposadr[o];if(t.qpos[r]+=fJ(i,a),n.clip_to_limits&&e.jnt_limited[o]){let n=e.jnt_range[o*2],i=e.jnt_range[o*2+1];t.qpos[r]=Math.min(Math.max(t.qpos[r],n),i)}}else t.qvel[e.jnt_dofadr[o]]+=fJ(i,a)}}applyFreejointPos(e,t,n){if(n.sample.dist!==`uniform_xyz`)return;let r=mJ(e);if(r<0)return;let i=e.jnt_qposadr[r];t.qpos[i]+=fJ(n.sample.x[0],n.sample.x[1]),t.qpos[i+1]+=fJ(n.sample.y[0],n.sample.y[1]),t.qpos[i+2]+=fJ(n.sample.z[0],n.sample.z[1])}applyFreejointYaw(e,t,n){if(n.sample.dist!==`uniform`)return;let r=mJ(e);if(r<0)return;let i=e.jnt_qposadr[r]+3,a=fJ(n.sample.low,n.sample.high),o=Math.cos(a/2),s=Math.sin(a/2),c=t.qpos[i],l=t.qpos[i+1],u=t.qpos[i+2],d=t.qpos[i+3];t.qpos[i]=o*c-s*d,t.qpos[i+1]=o*l+s*u,t.qpos[i+2]=o*u-s*l,t.qpos[i+3]=o*d+s*c}};function gJ(e){return`kind`in e&&e.kind===`event`&&Array.isArray(e.mutations)}var _J=class{constructor(e,t){this.terms=[];for(let n of e){if(gJ(n)){this.terms.push(new hJ(n));continue}let e=t[n.name];if(!e){console.warn(`[EventManager] Unknown event type: ${n.name}`);continue}this.terms.push(new e(n))}}onReset(e){for(let t of this.terms)t.onReset(e)}get size(){return this.terms.length}},vJ={};function yJ(e){return typeof e==`object`&&!!e&&typeof e.setSelectedMotion==`function`}var bJ=class extends Error{constructor(){super(`This scene cannot be loaded because it exceeds the browser's WebAssembly 2 GB memory limit. Try closing other browser tabs or reloading the page to free memory.`),this.name=`WasmMemoryLimitError`}};function xJ(e){let t=e instanceof Error?e.message:String(e);return t.includes(`MjModel loading returned null`)||t.includes(`Could not allocate memory`)||t.includes(`memory allocation failed`)||t.includes(`bad_alloc`)}var SJ=class{constructor(e,t,n={}){this.render=()=>{if(pF().updateDebugVisuals(),this.mjData&&IP(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){GD(this.camera,this.lights);for(let[e,t]of this.lastSimState.bodies){let n=this.bodies[e];n&&(n.position.copy(t.position),n.quaternion.copy(t.quaternion))}WD(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&$D({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{let{width:e,height:t}=this.getSize();this.camera.aspect=e/t,this.camera.updateProjectionMatrix(),this.renderer.setSize(e,t)},this.mujoco=e,this.container=t,this.baseUrl=n.baseUrl||`/`;let r=`/working`;try{this.mujoco.FS.mkdir(r)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&console.warn(`Failed to create /working directory:`,e)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:`.`},r)}catch(e){e&&typeof e==`object`&&`code`in e&&e.code!==`EEXIST`&&e.code!==`EBUSY`&&console.warn(`Failed to mount MEMFS at /working:`,e)}let{width:i,height:a}=this.getSize();this.scene=new Ex,this.scene.name=`scene`,this.camera=new _x(45,i/a,.001,1e3),this.camera.name=`PerspectiveCamera`,this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new dD({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(i,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=2,this.renderer.outputColorSpace=V_,this.renderer.toneMapping=4,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported(`immersive-vr`).then(e=>{e&&(this.vrButton=FD.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new SD(this.camera,this.renderer.domElement),this.controls.target.set(0,.2,0),this.controls.panSpeed=2,this.controls.zoomSpeed=1,this.controls.enableDamping=!0,this.controls.dampingFactor=.1,this.controls.screenSpacePanning=!0,this.controls.update(),this.renderer.setAnimationLoop(this.render),window.addEventListener(`resize`,this.onWindowResize),`ResizeObserver`in window?(this.resizeObserver=new ResizeObserver(()=>this.onWindowResize()),this.resizeObserver.observe(this.container)):this.resizeObserver=null,this.lastSimState={bodies:new Map,tendons:eO()},this.dynamicBodyIds=null,this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.loopPromise=null,this.running=!1,this.timestep=.001,this.decimation=1,this.policyCtrlDt=null,this.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.initialQpos=null,this.initialQvel=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null,this.eventManager=null,this.terrainData=null,this.splatMesh=null,this.colliderMesh=null,this.cameraState={trackBodyId:null,prevBodyPos:null},this.sceneCacheManager=LP.getInstance(this.mujoco),this.resourceTracker=new RP,this.memoryMonitor=new zP}async loadEnvironment(e,t=null,n=null,r=null,i=null,a=null){this.terrainData=a,i&&i.length>0?(this.eventManager=new _J(i,vJ),console.log(`[EventManager] ${this.eventManager.size} reset event(s) loaded`)):this.eventManager=null,await this.stop(),this.splatMesh&&=(kN(this.splatMesh,this.scene),null),this.colliderMesh&&=(jP(this.colliderMesh,this.scene),null);let o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);let t=performance.now()-o;this.memoryMonitor.logCacheOperation(`hit`,e,{elapsedMs:t})}else this.memoryMonitor.logCacheOperation(`miss`,e),await this.sceneCacheManager.prepareForNewScene(),this.mjModel=null,this.mjData=null,this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.resourceTracker.startTracking(this.mujoco),await mO(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);n&&(this.splatMesh=ON(n,this.scene),n.colliderUrl&&(this.colliderMesh=await AP(this.resolveAssetUrl(n.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(r),this.running=!0,this.startLoop()}initializeCommands(){let e=pF();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){pF().initialize(e,t),console.log(`[mjswanRuntime] Commands loaded from policy config:`,Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log(`[mjswanRuntime] Simulation reset`)}async setSelectedMotion(e){let t=pF().getTerm(`motion`);if(!yJ(t))return!1;let n=await t.setSelectedMotion(e);return n&&this.resetSimulation(),n}getSelectedMotionName(){let e=pF().getTerm(`motion`);return yJ(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){let t=pF().getTerm(`motion`);!yJ(t)||typeof t.setReferenceVisible!=`function`||t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{let t=this.scene.getObjectByName(`MuJoCo Root`);t&&this.scene.remove(t);let n={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await uO(this.mujoco,e,n),!this.mjModel||!this.mjData)throw Error(`Failed to load MuJoCo model.`);this.mujocoRoot=this.scene.getObjectByName(`MuJoCo Root`),this.mujoco.mj_forward(this.mjModel,this.mjData),WD(this.mujoco,this.mjData,this.lights),GD(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001;let r=this.policyCtrlDt??.02;this.decimation=Math.max(1,Math.round(r/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new MP({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds}),this.loadingScene=null})(),await this.loadingScene}async loadSceneWithOomRetry(e){try{await this.loadScene(e)}catch(t){if(!xJ(t))throw t;console.warn(`[mjswanRuntime] OOM — clearing cache and retrying...`),this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(e){throw this.loadingScene=null,xJ(e)?new bJ:e}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&=(kN(this.splatMesh,this.scene),null),this.colliderMesh&&=(jP(this.colliderMesh,this.scene),null),e&&(this.splatMesh=ON(e,this.scene),e.colliderUrl&&(this.colliderMesh=await AP(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&DN(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;let e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){let e=performance.now(),t=this.timestep*this.decimation;if(this.mjModel&&this.mjData){if(this.mujoco.mj_forward(this.mjModel,this.mjData),this.policyRunner&&this.policyStateBuilder){let e=this.policyStateBuilder.build(),t=this.policyRunner.collectObservationsByKey(e);await this.runOnnxInference(t)}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){let e=this.policyStateBuilder.build();if(this.terminationManager.evaluate(e).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){let e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}pF().update(t),pF().updateDebugVisuals()}let n=(performance.now()-e)/1e3,r=Math.max(0,t-n);r>0&&await new Promise(e=>setTimeout(e,r*1e3))}this.loopPromise=null}async loadPolicyConfig(e){let t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;let n=pF();if(n.clear(),n.setResetCallback(()=>this.resetSimulation()),e){if(!this.mjModel||!this.mjData){console.warn(`Policy config loaded before MuJoCo model is ready.`);return}e!==t&&this.resetSimulationState();try{let{config:t}=await this.fetchPolicyConfig(e);if(Array.isArray(t.motions)&&(t.motions=t.motions.map(t=>({...t,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,t.path))}))),t.commands?.motion&&Array.isArray(t.motions)&&(t.commands.motion={...t.commands.motion,motions:t.motions}),this.initialQpos=Array.isArray(t.initial_qpos)?t.initial_qpos:null,this.initialQvel=Array.isArray(t.initial_qvel)?t.initial_qvel:null,this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),t.commands&&typeof t.commands==`object`){this.initializeCommandsFromConfig(t.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),pF().resetTerms();let e=pF().getTerm(`motion`);yJ(e)&&(await e.setSelectedMotion(t.motions?.find(e=>e.default)?.name??t.motions?.[0]?.name??null),e.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!t.policy_num_actions&&(!t.policy_joint_names||t.policy_joint_names.length===0))throw Error(`Policy config missing policy_joint_names.`);let n=new rJ(t,{policyModules:{tracking:cJ,locomotion:uJ},observations:BP});await n.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),await n.preloadAll(),this.policyRunner=n,this.policyStateBuilder=new aJ(this.mujoco,this.mjModel,this.mjData,n.getPolicyJointNames());let r=this.policyStateBuilder.build();this.policyRunner.reset(r),this.policyControl=this.buildPolicyControl(t,n,this.policyStateBuilder);{let e=t.observations,n=[];if(Array.isArray(e))n.push(...e);else if(e&&typeof e==`object`)for(let t of Object.values(e))Array.isArray(t)&&n.push(...t);for(let e of n)if(!(!e||this.timestep<=0)&&typeof e.fps==`number`&&e.fps>0){this.policyCtrlDt=1/e.fps;let t=Math.max(1,Math.round(this.policyCtrlDt/this.timestep));t!==this.decimation&&(console.log(`[PolicyRunner] Decimation updated: ${this.decimation} → ${t} (fps=${e.fps}, sim_dt=${this.timestep})`),this.decimation=t);break}}if(t.terminations&&Object.keys(t.terminations).length>0&&(this.terminationManager=new BF(t.terminations,VF,n),console.log(`[TerminationManager] ${this.terminationManager.size} termination term(s) loaded`)),t.onnx?.path){let n=this.resolvePolicyAssetPath(e,t.onnx.path),r=this.resolveAssetUrl(n),i=new iJ({...t.onnx,path:r});await i.init(),this.onnxModule=i,this.onnxInputDict=i.initInput()}console.log(`[PolicyRunner] config loaded`,{obsSize:n.getObservationSize(),obsLayout:n.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(e){console.warn(`Failed to load policy config:`,e)}}}async fetchPolicyConfig(e){let t=this.resolveAssetUrl(e),n=await fetch(t,{cache:`no-store`});if(!n.ok)throw Error(`Failed to fetch policy config: ${n.status}`);return{config:await n.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;let t=(this.baseUrl||`/`).replace(/\/+$/,`/`),n=new URL(t,window.location.origin+`/`).toString();return new URL(e.replace(/^\/+/,``),n).toString()}resolvePolicyAssetPath(e,t){let n=e.replace(/\\/g,`/`),r=n.lastIndexOf(`/`);return r>=0?`${n.slice(0,r+1)}${t}`.replace(/\/+/g,`/`):t}buildPolicyControl(e,t,n){let r=t.getPolicyJointNames(),i=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(n,a,o,s,c,l,u,d)=>{let f=o.qposAdr.length,p=o.actionIndices.map(e=>r[e]),m=this.normalizeControlArray(s,f,1,p),h=this.normalizeControlArray(c,f,0,p),g=d?t.getDefaultJointPos():new Float32Array(r.length),_=new Float32Array(f);for(let e=0;e<f;e++)_[e]=g[o.actionIndices[e]];let v=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(r.length),y=new Float32Array(f);for(let e=0;e<f;e++)y[e]=v[o.actionIndices[e]]??0;let b=this.normalizeControlArray(l,f,0,p),x=this.normalizeControlArray(u,f,0,p),S=o.ctrlAdr.map(e=>e<0||!this.mjModel?!1:this.mjModel.actuator_biastype[e]===i),C=S.some(Boolean),w=S.some(e=>!e);return C&&w&&console.warn(`[PolicyRunner] Action term "${n}": mixed actuator types detected.`),console.log(`[PolicyRunner] Action term "${n}" (${a}): ${f} joint(s), mode: ${C?`position (ctrl=target_pos)`:`motor (ctrl=torque, external PD)`}`),{controlType:a,ctrlAdr:o.ctrlAdr,qposAdr:o.qposAdr,qvelAdr:o.qvelAdr,actionIndices:o.actionIndices,actionScale:m,actionOffset:h,defaultJointPos:_,encoderBias:y,positionActuator:S,kp:b,kd:x,muscleNormalize:!1}},o=e.actions;if(!o||Object.keys(o).length===0){let t=e.control_type??`joint_position`;if(t!==`joint_position`&&t!==`torque`)return console.warn(`[PolicyRunner] Unsupported control_type: ${t}`),null;let r=n.getControlMapping();return r?[a(`legacy`,t,{...r,actionIndices:Array.from({length:r.qposAdr.length},(e,t)=>t)},e.action_scale,void 0,e.stiffness,e.damping,!0)]:(console.warn(`[PolicyRunner] Failed to build control mapping.`),null)}let s=[];for(let[e,t]of Object.entries(o)){let i=t.type??`joint_position`;if(i!==`joint_position`&&i!==`torque`&&i!==`muscle_activation`){console.warn(`[PolicyRunner] Action term "${e}": unsupported type "${i}", skipping.`);continue}let o=t.actuator_names??[`.*`];if(i===`muscle_activation`){let r=n.getCtrlMappingByActuatorNames(o);if(!r){console.warn(`[PolicyRunner] Action term "${e}": no actuators matched patterns [${o.join(`, `)}], skipping.`);continue}let a=r.ctrlAdr.length,c=this.normalizeControlArray(t.scale,a,1),l=this.normalizeControlArray(t.offset,a,0),u=t.normalize??!0;console.log(`[PolicyRunner] Action term "${e}" (muscle_activation): ${a} actuator(s), normalize=${u}`),s.push({controlType:i,ctrlAdr:r.ctrlAdr,qposAdr:[],qvelAdr:[],actionIndices:r.actionIndices,actionScale:c,actionOffset:l,defaultJointPos:new Float32Array(a),encoderBias:new Float32Array(a),positionActuator:Array(a).fill(!1),kp:new Float32Array(a),kd:new Float32Array(a),muscleNormalize:u});continue}let c=o.length===1&&o[0]===`.*`,l;if(c){let t=n.getControlMapping();if(!t){console.warn(`[PolicyRunner] Action term "${e}": failed to build control mapping, skipping.`);continue}l={...t,actionIndices:Array.from({length:t.qposAdr.length},(e,t)=>t)}}else if(l=n.getControlMappingFor(o,r),!l){console.warn(`[PolicyRunner] Action term "${e}": no joints matched patterns [${o.join(`, `)}], skipping.`);continue}let u=t.use_default_offset===void 0?i===`joint_position`:t.use_default_offset;s.push(a(e,i,l,t.scale,t.offset,t.stiffness,t.damping,u))}return s.length===0?(console.warn(`[PolicyRunner] No valid action terms found in config.actions.`),null):s}normalizeControlArray(e,t,n,r){let i=new Float32Array(t);if(i.fill(n),typeof e==`number`)return i.fill(e),i;if(Array.isArray(e)){for(let r=0;r<t;r++)i[r]=typeof e[r]==`number`?e[r]:n;return i}if(typeof e==`object`&&e&&r){for(let[n,a]of Object.entries(e)){let e=r.indexOf(n);e>=0&&e<t?i[e]=a:console.warn(`[PolicyRunner] Joint name "${n}" not found in policy_joint_names; skipping.`)}return i}return i}resetSimulationState(){if(!(!this.mjModel||!this.mjData)){if(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.initialQpos){let e=this.mjData.qpos;for(let t=0;t<Math.min(this.initialQpos.length,this.mjModel.nq);t++)e[t]=this.initialQpos[t]}if(this.initialQvel){let e=this.mjData.qvel;for(let t=0;t<Math.min(this.initialQvel.length,this.mjModel.nv);t++)e[t]=this.initialQvel[t]}this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),pF().resetTerms(),this.onnxModule&&(this.onnxInputDict=this.onnxModule.initInput()),this.onnxTimeStep=0,this.mujoco.mj_forward(this.mjModel,this.mjData),this.lastSimState.bodies.clear(),this.updateCachedState()}}executeSimulationSteps(){if(!(!this.mjModel||!this.mjData)){this.applyDragForces();for(let e=0;e<this.decimation;e++)this.applyPolicyControl(),this.mujoco.mj_step(this.mjModel,this.mjData)}}applyPolicyControl(){if(!this.policyControl||!this.mjData)return;let e=this.mjData.ctrl;e.fill(0);let t=this.policyRunner?.getLastActions()??new Float32Array;for(let n of this.policyControl){let{controlType:r,ctrlAdr:i,qposAdr:a,qvelAdr:o,actionIndices:s,actionScale:c,actionOffset:l,defaultJointPos:u,encoderBias:d,positionActuator:f,kp:p,kd:m,muscleNormalize:h}=n,g=i.length;if(r===`joint_position`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let h=t[s[n]]??0,g=u[n]+l[n]+c[n]*h-d[n];if(f[n])e[r]=g;else{let t=this.mjData.qpos[a[n]],i=this.mjData.qvel[o[n]];e[r]=p[n]*(g-t)+m[n]*(0-i)}}else if(r===`torque`)for(let n=0;n<g;n++){let r=i[n];r>=0&&(e[r]=c[n]*(t[s[n]]??0))}else if(r===`muscle_activation`)for(let n=0;n<g;n++){let r=i[n];if(r<0)continue;let a=(t[s[n]]??0)*c[n]+l[n];h?e[r]=1/(1+Math.exp(-5*(a-.5))):e[r]=a<0?0:a>1?1:a}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||=this.onnxModule.initInput();let t={...this.onnxInputDict};this.onnxModule.inKeys.includes(`time_step`)&&(t.time_step=new AI(`float32`,new Float32Array([this.onnxTimeStep]),[1,1]));for(let[n,r]of Object.entries(e))t[n]=new AI(`float32`,r,[1,r.length]);for(let e of this.onnxModule.inKeys)if(!t[e]){console.warn(`[PolicyRunner] Missing ONNX input:`,{key:e,available:Object.keys(t)});return}let[n,r]=await this.onnxModule.runInference(t);Object.keys(r).length>0&&(this.onnxInputDict={...this.onnxInputDict,...r}),this.onnxModule.inKeys.includes(`time_step`)&&(this.onnxTimeStep+=1);let i=this.onnxModule.outKeys[0],a=n.action??(i?n[i]:null)??n.policy??null;if(!a)return;let o=a.data,s=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&s.length!==c){console.warn(`[PolicyRunner] Action size mismatch:`,{expected:c,got:s.length});return}this.policyRunner.setLastActions(s)}catch(e){console.warn(`[PolicyRunner] ONNX inference failed:`,e)}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let e=0;e<this.mjData.xfrc_applied.length;e++)this.mjData.xfrc_applied[e]=0;let e=this.dragStateManager.physicsObject;if(!e||!(`bodyID`in e)||typeof e.bodyID!=`number`||e.bodyID<=0)return;let t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let e=0;e<this.mjModel.nbody;e++)this.bodies[e]&&(fO(this.mjData.xpos,e,this.bodies[e].position),pO(this.mjData.xquat,e,this.bodies[e].quaternion),this.bodies[e].updateWorldMatrix(!0,!1));this.dragStateManager.update();let n=HD(this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale)),r=HD(this.dragStateManager.worldHit.clone()),i=new Y(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),a=new Y(r.x-i.x,r.y-i.y,r.z-i.z),o=new Y(n.x,n.y,n.z),s=new Y().crossVectors(a,o),c=t*6;this.mjData.xfrc_applied[c+0]=n.x,this.mjData.xfrc_applied[c+1]=n.y,this.mjData.xfrc_applied[c+2]=n.z,this.mjData.xfrc_applied[c+3]=s.x,this.mjData.xfrc_applied[c+4]=s.y,this.mjData.xfrc_applied[c+5]=s.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++)if(!(e&&!e.has(t))&&this.bodies[t]){this.lastSimState.bodies.has(t)||this.lastSimState.bodies.set(t,{position:new Y,quaternion:new Pv});let e=this.lastSimState.bodies.get(t);fO(this.mjData.xpos,t,e.position),pO(this.mjData.xquat,t,e.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&QD(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=FP(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){let t=new Set;for(let n=1;n<e.nbody;n++){let r=n;for(;r>0;){if(e.body_jntnum[r]>0){t.add(n);break}r=e.body_parentid[r]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;let e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;let n=this.bodies[t];n&&(fO(this.mjData.xpos,t,n.position),pO(this.mjData.xquat,t,n.quaternion))}}async captureThumbnail(e={}){let{maxDim:t=1280,quality:n=.85}=e,r=this.renderer.domElement;this.renderer.render(this.scene,this.camera);let i=r.width,a=r.height;if(!i||!a)throw Error(`mjswan: canvas has zero size; nothing to capture.`);let o=Math.min(1,t/Math.max(i,a)),s=Math.max(1,Math.round(i*o)),c=Math.max(1,Math.round(a*o)),l=document.createElement(`canvas`);l.width=s,l.height=c;let u=l.getContext(`2d`);if(!u)throw Error(`mjswan: failed to get a 2D context for thumbnail capture.`);return u.drawImage(r,0,0,s,c),await new Promise((e,t)=>{l.toBlob(n=>n?e(n):t(Error(`mjswan: toBlob returned null.`)),`image/jpeg`,n)})}async dispose(){await this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.onnxModule&&=(this.onnxModule.dispose(),null),this.onnxInputDict=null,this.onnxInferencing=!1,this.splatMesh&&=(kN(this.splatMesh,this.scene),null),this.colliderMesh&&=(jP(this.colliderMesh,this.scene),null),this.dragStateManager&&=(this.dragStateManager.dispose(),null),this.mjData=null,this.mjModel=null,window.removeEventListener(`resize`,this.onWindowResize),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.controls.dispose(),this.renderer.setAnimationLoop(null),this.renderer.dispose(),this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.vrButton?.parentElement&&(this.vrButton.parentElement.removeChild(this.vrButton),this.vrButton=null),this.bodies=null,this.lights=[],this.mujocoRoot=null,this.dynamicBodyIds=null,this.lastSimState.bodies.clear()}disposeThreeJSResources(){if(this.scene)for(this.scene.traverse(e=>{`geometry`in e&&e.geometry&&e.geometry.dispose(),`material`in e&&e.material&&(Array.isArray(e.material)?e.material.forEach(e=>this.disposeMaterial(e)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){let t=e;t.map&&t.map.dispose(),t.aoMap&&t.aoMap.dispose(),t.emissiveMap&&t.emissiveMap.dispose(),t.metalnessMap&&t.metalnessMap.dispose(),t.normalMap&&t.normalMap.dispose(),t.roughnessMap&&t.roughnessMap.dispose(),e.dispose()}getSize(){let e=this.container.clientWidth||window.innerWidth,t=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,t)}}async restoreFromCache(e){let t=this.sceneCacheManager.get(e);if(!t)throw Error(`Scene ${e} not found in cache`);let n=this.scene.getObjectByName(`MuJoCo Root`);n&&this.scene.remove(n),this.mjModel=t.mjModel,this.mjData=t.mjData,this.bodies=t.bodies,this.lights=t.lights,this.mujocoRoot=t.mujocoRoot,this.scene.add(this.mujocoRoot),this.scene.background=t.skybox,this.mujoco.mj_forward(this.mjModel,this.mjData),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001;let r=this.policyCtrlDt??.02;this.decimation=Math.max(1,Math.round(r/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new MP({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){let t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn(`[SceneCache] Cannot cache scene: missing resources`);return}let n=this.resourceTracker.estimateSceneMemory({mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,meshes:{},mujocoRoot:this.mujocoRoot});await this.sceneCacheManager.set(e,{scenePath:e,lastAccessed:Date.now(),loadedAt:Date.now(),mjModel:this.mjModel,mjData:this.mjData,bodies:this.bodies,lights:this.lights,meshes:{},mujocoRoot:this.mujocoRoot,skybox:this.scene.background instanceof xx?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:n});let r=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation(`load`,e,{memoryMB:n/1048576,totalScenes:r.totalScenes,totalMemoryMB:r.totalMemoryBytes/1048576})}},CJ=`mjswan_oom_reload_scene`,wJ=({scenePath:e,baseUrl:t,policyConfigPath:n,splatConfig:i,cameraConfig:a,eventsConfig:o,terrainData:s,selectedMotion:c,showReferenceMotion:l=!0,onStatusChange:u,onError:d,onReady:f,onRuntimeReady:p})=>{let m=(0,y.useRef)(null),h=(0,y.useRef)(null),g=(0,y.useRef)(null),_=(0,y.useRef)(i);_.current=i;let v=(0,y.useRef)(c);v.current=c;let b=(0,y.useRef)(l);return b.current=l,(0,y.useEffect)(()=>{let i=!1,c=e=>{u?.(e)};return(async()=>{if(g.current||=(c(`Loading MuJoCo…`),await(await r(()=>import(`./mujoco-C7EP5tg_.js`),__vite__mapDeps([0,1,2]))).default()),i)return;let l=m.current;if(!l)throw Error(`Failed to find viewer container.`);let u=g.current;if(!u)throw Error(`MuJoCo not loaded.`);h.current||(h.current=new SJ(u,l,{baseUrl:t}),p?.(h.current)),c(`Loading scene…`),await h.current.loadEnvironment(e,n??null,_.current??null,a??null,o??null,s??null),await h.current.setSelectedMotion(v.current??null),h.current.setReferenceVisible(b.current),!i&&(sessionStorage.removeItem(CJ),c(`Running simulation`),f?.())})().catch(t=>{if(!i){if(t instanceof bJ){if(sessionStorage.getItem(CJ)!==e){console.warn(`[MjswanViewer] OOM — reloading page to free memory...`),sessionStorage.setItem(CJ,e),window.location.reload();return}sessionStorage.removeItem(CJ)}console.error(`Failed to initialize MuJoCo viewer:`,t),d?.(t instanceof Error?t:Error(String(t))),c(`Failed to load scene`)}}),()=>{i=!0,h.current?.dispose(),h.current=null}},[e,t,n,a,o,s,u,d,f]),(0,y.useEffect)(()=>{h.current?.setReferenceVisible(l)},[l]),(0,G.jsx)(`div`,{ref:m,className:`viewer`})},TJ={outline:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},filled:{xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`currentColor`,stroke:`none`}},EJ=(e,t,n,r)=>{let i=(0,y.forwardRef)(({color:n=`currentColor`,size:i=24,stroke:a=2,title:o,className:s,children:c,...l},u)=>(0,y.createElement)(`svg`,{ref:u,...TJ[e],width:i,height:i,className:[`tabler-icon`,`tabler-icon-${t}`,s].join(` `),...e===`filled`?{fill:n}:{strokeWidth:a,stroke:n},...l},[o&&(0,y.createElement)(`title`,{key:`svg-title`},o),...r.map(([e,t])=>(0,y.createElement)(e,t)),...Array.isArray(c)?c:[c]]));return i.displayName=`${n}`,i},DJ=EJ(`outline`,`chevron-down`,`ChevronDown`,[[`path`,{d:`M6 9l6 6l6 -6`,key:`svg-0`}]]),OJ=EJ(`outline`,`chevron-up`,`ChevronUp`,[[`path`,{d:`M6 15l6 -6l6 6`,key:`svg-0`}]]),kJ=EJ(`outline`,`refresh`,`Refresh`,[[`path`,{d:`M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4`,key:`svg-0`}],[`path`,{d:`M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4`,key:`svg-1`}]]),AJ=EJ(`outline`,`x`,`X`,[[`path`,{d:`M18 6l-12 12`,key:`svg-0`}],[`path`,{d:`M6 6l12 12`,key:`svg-1`}]]),jJ=`0.7.1-beta.1`,MJ=[{login:`ttktjmt`,html_url:`https://github.com/ttktjmt`},{login:`claude`,html_url:`https://github.com/claude`},{login:`Axellwppr`,html_url:`https://github.com/Axellwppr`},{login:`julien-blanchon`,html_url:`https://github.com/julien-blanchon`},{login:`unmoyai`,html_url:`https://github.com/unmoyai`},{login:`brentyi`,html_url:`https://github.com/brentyi`},{login:`CharlieLeee`,html_url:`https://github.com/CharlieLeee`}],NJ={move:`touchmove`,end:`touchend`},PJ={move:`mousemove`,end:`mouseup`};function FJ(e){return e.type===`touchmove`}function IJ(e){return e.type===`mousemove`}var LJ=y.createContext(null);function RJ({children:e,width:t,visible:n=!0,onVisibleChange:r,hiddenButtonTooltip:i}){let a=y.useRef(null),[o,{toggle:s}]=Ht(!0),[c,l]=y.useState(800),u=y.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),d=y.useRef({}),f=(e,t,n)=>Math.abs(e+t/2)<Math.abs(e-n+t/2)?e:e-n;function p(e,t){let n=a.current;if(n===null)return[e,t];let r=n.parentElement;if(r===null)return[e,t];let i=e,o=t;return i=Math.min(i,r.clientWidth-n.clientWidth-15),i=Math.max(i,15),o=Math.min(o,r.clientHeight-n.clientHeight-15),o=Math.max(o,15),n.style.top=`${o.toString()}px`,n.style.left=`${i.toString()}px`,[f(i,n.clientWidth,r.clientWidth),f(o,n.clientHeight,r.clientHeight)]}y.useEffect(()=>{let e=a.current;if(e===null)return;let t=e.parentElement;if(t===null)return;let n=new ResizeObserver(()=>{d.current.x===void 0&&(d.current.x=f(e.offsetLeft,e.clientWidth,t.clientWidth)),d.current.y===void 0&&(d.current.y=f(e.offsetTop,e.clientHeight,t.clientHeight));let n=t.clientHeight-30;c!==n&&l(n);let r=d.current.x,i=d.current.y;for(;r<0;)r+=t.clientWidth;for(;i<0;)i+=t.clientHeight;p(r,i)});return n.observe(e),n.observe(t),()=>{n.disconnect()}});let m=e=>{let t=u.current,n=a.current;if(!n)return;e.type==`touchstart`?(e=e,t.startClientX=e.touches[0].clientX,t.startClientY=e.touches[0].clientY):(e=e,t.startClientX=e.clientX,t.startClientY=e.clientY),t.startPosX=n.offsetLeft,t.startPosY=n.offsetTop;let r=e.type==`touchstart`?NJ:PJ;function i(e){let n=0,r=0;if(FJ(e)?(e=e,n=e.touches[0].clientX-t.startClientX,r=e.touches[0].clientY-t.startClientY):IJ(e)&&(e=e,n=e.clientX-t.startClientX,r=e.clientY-t.startClientY),Math.abs(n)<=3&&Math.abs(r)<=3)return;t.dragging=!0;let i=t.startPosX+n,a=t.startPosY+r;[d.current.x,d.current.y]=p(i,a)}window.addEventListener(r.move,i),window.addEventListener(r.end,()=>{e.type==`touchstart`&&(t.dragging=!1),window.removeEventListener(r.move,i)},{once:!0})};if(!n){let e=(0,G.jsx)(J,{component:`button`,"aria-label":i??`Show controls`,onClick:()=>r?.(!0),style:{width:`0.85rem`,height:`0.85rem`,minWidth:`0.85rem`,minHeight:`0.85rem`,display:`block`,padding:0,border:`none`,borderRadius:`9999px`,background:`rgba(255, 255, 255, 0.82)`,boxShadow:`0 0 0 1px rgba(0, 0, 0, 0.14), 0 2px 8px rgba(0, 0, 0, 0.18)`,cursor:`pointer`}});return(0,G.jsx)(J,{style:{zIndex:10,position:`absolute`,top:`1em`,right:`1em`},children:i?(0,G.jsx)(Uh,{label:i,children:(0,G.jsx)(J,{children:e})}):e})}return(0,G.jsx)(LJ.Provider,{value:{wrapperRef:a,expanded:o,width:t,maxHeight:c,toggleExpanded:s,dragHandler:m,dragInfo:u},children:(0,G.jsx)(Jc,{radius:`xs`,shadow:`0.1em 0 1em 0 rgba(0,0,0,0.1)`,style:{boxSizing:`border-box`,width:t,zIndex:10,position:`absolute`,top:`1em`,right:`1em`,margin:0,"& .expandIcon":{transform:`rotate(0)`},overflow:`hidden`},ref:a,children:e})})}RJ.Handle=function({children:e}){let t=y.useContext(LJ);return(0,G.jsx)(G.Fragment,{children:(0,G.jsx)(J,{style:{borderRadius:`0.2em 0.2em 0 0`,lineHeight:`1.5em`,cursor:`pointer`,position:`relative`,fontWeight:400,userSelect:`none`,display:`flex`,alignItems:`center`,padding:`0 0.75em`,height:`2.75em`},onClick:()=>{let e=t.dragInfo.current;if(e.dragging){e.dragging=!1;return}t.toggleExpanded()},onTouchStart:e=>{t.dragHandler(e)},onMouseDown:e=>{t.dragHandler(e)},children:e})})},RJ.Contents=function({children:e}){let t=y.useContext(LJ);return(0,G.jsxs)(Di,{in:t.expanded,children:[(0,G.jsx)(pp,{mx:`xs`}),(0,G.jsx)(zc.Autosize,{mah:t.maxHeight,children:(0,G.jsx)(J,{style:{width:t.width},children:e})})]})},RJ.HideWhenCollapsed=function({children:e}){return y.useContext(LJ)?.expanded??!0?e:null},RJ.HideWhenExpanded=function({children:e}){return y.useContext(LJ)?.expanded??!0?null:e};function zJ({id:e,label:t,children:n}){return(0,G.jsx)(J,{pb:`0.5em`,px:`xs`,children:(0,G.jsxs)(Hu,{align:`center`,children:[(0,G.jsx)(J,{pr:`xs`,style:{width:`7.25em`,flexShrink:0,position:`relative`},children:(0,G.jsx)(Yu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`100%`,boxSizing:`content-box`},children:(0,G.jsx)(`label`,{htmlFor:e,children:t})})}),(0,G.jsx)(J,{style:{flexGrow:1},children:n})]})})}function BJ({label:e,expandByDefault:t=!0,children:n}){let[r,{toggle:i}]=Ht(t);return(0,G.jsxs)(Jc,{withBorder:!0,style:{borderWidth:`1px`,position:`relative`,marginLeft:`var(--mantine-spacing-xs)`,marginRight:`var(--mantine-spacing-xs)`,marginTop:`var(--mantine-spacing-xs)`,marginBottom:`var(--mantine-spacing-xs)`,paddingBottom:`calc(var(--mantine-spacing-xs) - 0.5em)`},children:[(0,G.jsxs)(Jc,{onClick:i,style:{fontSize:`0.875em`,position:`absolute`,padding:`0 0.375em`,top:0,left:`0.375em`,transform:`translateY(-50%)`,userSelect:`none`,fontWeight:500,cursor:`pointer`,display:`flex`,alignItems:`center`},children:[e,(0,G.jsx)(r?OJ:DJ,{style:{width:`0.9em`,height:`0.9em`,strokeWidth:3,top:`0.1em`,position:`relative`,marginLeft:`0.25em`,marginRight:`-0.1em`,opacity:.5}})]}),(0,G.jsx)(Di,{in:r,children:(0,G.jsx)(J,{pt:`1em`,children:n})}),(0,G.jsx)(Di,{in:!r,children:(0,G.jsx)(J,{p:`xs`})})]})}var VJ={fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`4.5em`,flexShrink:0},HJ={root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}},UJ={flex:1,minWidth:0,height:`1.75em`,fontSize:`0.8em`,fontFamily:`inherit`,border:`1px solid var(--mantine-color-default-border)`,borderRadius:`var(--mantine-radius-sm)`,background:`var(--mantine-color-default)`,color:`var(--mantine-color-text)`,textAlign:`right`,padding:`0 0.4em`,outline:`none`,cursor:`ns-resize`,touchAction:`none`};function WJ({axis:e,value:t,min:n=-1/0,max:r=1/0,step:i,onChange:a}){let o=(0,y.useRef)(null),s=(0,y.useRef)(null);(0,y.useEffect)(()=>{let e=o.current;e&&document.activeElement!==e&&(e.value=t.toFixed(2))},[t]);let c=e=>Math.max(n,Math.min(r,parseFloat((Math.round(e/i)*i).toFixed(10))));return(0,G.jsxs)(J,{style:{display:`flex`,alignItems:`center`,gap:`0.25em`,flex:1},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,letterSpacing:`-0.75px`,flexShrink:0},children:e}),(0,G.jsx)(`input`,{ref:o,size:1,defaultValue:t.toFixed(2),onPointerDown:e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={startY:e.clientY,startValue:t,moved:!1}},onPointerMove:e=>{if(!s.current||!(e.buttons&1))return;let t=s.current.startY-e.clientY;if(Math.abs(t)>3&&(s.current.moved=!0),!s.current.moved)return;let n=c(s.current.startValue+t*i);a(n),o.current&&(o.current.value=n.toFixed(2))},onPointerUp:()=>{if(s.current&&!s.current.moved){let e=o.current;e&&(e.focus(),e.select())}s.current=null},onBlur:e=>{let n=parseFloat(e.target.value);isNaN(n)||a(c(n)),e.target.value=t.toFixed(2)},onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur(),e.key===`Escape`&&(o.current&&(o.current.value=t.toFixed(2)),o.current?.blur())},onFocus:e=>e.currentTarget.style.outline=`2px solid var(--mantine-color-blue-5)`,onBlurCapture:e=>e.currentTarget.style.outline=`none`,style:UJ})]})}function GJ({label:e,x:t,y:n,z:r,step:i,xLabel:a=`X`,yLabel:o=`Y`,zLabel:s=`Z`,onX:c,onY:l,onZ:u}){return(0,G.jsxs)(J,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:VJ,children:e}),(0,G.jsx)(WJ,{axis:a,value:t,step:i,onChange:c}),(0,G.jsx)(WJ,{axis:o,value:n,step:i,onChange:l}),(0,G.jsx)(WJ,{axis:s,value:r,step:i,onChange:u})]})}function KJ({scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o,onCalibrate:s}){let[c,l]=(0,y.useState)(e),[u,d]=(0,y.useState)(t),[f,p]=(0,y.useState)(n),[m,h]=(0,y.useState)(r),[g,_]=(0,y.useState)(i),[v,b]=(0,y.useState)(a),[x,S]=(0,y.useState)(o);(0,y.useEffect)(()=>{l(e)},[e]),(0,y.useEffect)(()=>{d(t)},[t]),(0,y.useEffect)(()=>{p(n)},[n]),(0,y.useEffect)(()=>{h(r)},[r]),(0,y.useEffect)(()=>{_(i)},[i]),(0,y.useEffect)(()=>{b(a)},[a]),(0,y.useEffect)(()=>{S(o)},[o]);let C=(e,t,n,r,i,a,o)=>s(e,t,n,r,i,a,o);return(0,G.jsxs)(BJ,{label:`Control`,expandByDefault:!0,children:[(0,G.jsxs)(J,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`,gap:`0.5em`},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:VJ,children:`Scale`}),(0,G.jsx)(J,{style:{flex:1},children:(0,G.jsx)(ug,{value:c,onChange:e=>{l(e),C(e,u,f,m,g,v,x)},min:.1,max:5,step:.05,size:`xs`,label:e=>e.toFixed(2),styles:HJ})})]}),(0,G.jsx)(GJ,{label:`Position`,x:u,y:f,z:m,step:.05,onX:e=>{d(e),C(c,e,f,m,g,v,x)},onY:e=>{p(e),C(c,u,e,m,g,v,x)},onZ:e=>{h(e),C(c,u,f,e,g,v,x)}}),(0,G.jsx)(GJ,{label:`Rotation`,x:g,y:v,z:x,step:.5,xLabel:`R`,yLabel:`P`,zLabel:`Y`,onX:e=>{_(e),C(c,u,f,m,e,v,x)},onY:e=>{b(e),C(c,u,f,m,g,e,x)},onZ:e=>{S(e),C(c,u,f,m,g,v,e)}})]})}function qJ(e){return e instanceof HTMLElement?e.isContentEditable?!0:e.closest(`input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]`)!==null:!1}function JJ(e){return e.split(`_`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function YJ({command:e,value:t,onChange:n,disabled:r,enabledWhenValue:i}){let a=e.config,o=a.enabled_when!==void 0&&(i??0)<.5,s=r||o;return(0,G.jsxs)(J,{pb:`0.5em`,px:`xs`,style:{display:`flex`,alignItems:`center`},children:[(0,G.jsx)(Yu,{c:`dimmed`,style:{fontSize:`0.875em`,fontWeight:450,lineHeight:`1.375em`,letterSpacing:`-0.75px`,width:`50%`,flexShrink:0},children:a.label}),(0,G.jsx)(J,{style:{width:`50%`},children:(0,G.jsx)(ug,{value:t,onChange:t=>n(e.id,t),min:a.min,max:a.max,step:a.step,size:`xs`,disabled:s,styles:{root:{padding:`0`},track:{height:4},thumb:{width:12,height:12}}})})]})}function XJ({command:e,value:t,onChange:n,disabled:r}){let i=e.config;return(0,G.jsx)(J,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(nf,{label:i.label,checked:t>=.5,onChange:t=>n(e.id,+!!t.currentTarget.checked),size:`xs`,disabled:r})})}function ZJ(e){let{visible:t,onVisibleChange:n,projects:r,projectValue:i,projectLabel:a,onProjectChange:o,scenes:s,sceneValue:c,onSceneChange:l,splats:u,splatSection:d=!1,splatValue:f,onSplatChange:p,splatConfig:m,onCalibrateSplat:h,onSplatUrlLoad:g,policies:_,policyValue:v,onPolicyChange:b,motions:x,motionValue:S,onMotionChange:C,showReferenceMotion:w,onShowReferenceMotionChange:T,commandsEnabled:E=!1,onReset:D}=e,[O,{open:k,close:A}]=Ht(!1),[j,M]=(0,y.useState)(``),[N,P]=(0,y.useState)(null),[F,I]=(0,y.useState)(!1),L=(0,y.useCallback)(async e=>{if(e.key!==`Enter`||!g)return;let t=j.trim();if(!u.some(e=>e.label===t||e.value===t)){if(!t.toLowerCase().endsWith(`.spz`)){P(`URL must end with .spz`);return}await g(t)?(P(null),I(!0)):P(`File not found at the specified URL`)}},[g,j,u]),[R,z]=(0,y.useState)([]),[B,V]=(0,y.useState)([]),[ee,te]=(0,y.useState)({});(0,y.useEffect)(()=>{let e=pF(),t=()=>{z(e.getCommands()),V(e.getCommandGroups()),te(e.getValues())};return t(),e.addEventListener(t),()=>{e.removeEventListener(t)}},[]);let ne=(0,y.useCallback)((e,t)=>{pF().setValue(e,t),te(n=>({...n,[e]:t}))},[]),re=(0,y.useCallback)(()=>{pF().triggerButton(`_system:reset`),D&&D()},[D]);(0,y.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.repeat||e.altKey||e.ctrlKey||e.metaKey)return;let r=e.key.toLowerCase();r!==`c`&&r!==`r`||qJ(e.target instanceof Element?e.target:document.activeElement)||(e.preventDefault(),r===`c`?n(!t):re())};return window.addEventListener(`keydown`,e),()=>{window.removeEventListener(`keydown`,e)}},[t,n,re]);let ie=e=>R.filter(t=>t.groupName===e&&(t.config.type===`slider`||t.config.type===`checkbox`));return!r.length&&!s.length&&!_.length?null:(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(xm,{opened:O,onClose:A,size:`lg`,title:null,centered:!0,styles:{body:{textAlign:`center`}},children:(0,G.jsxs)(mg,{gap:`md`,align:`center`,children:[(0,G.jsx)(gp,{src:`/logo.svg`,style:{width:`8em`,height:`auto`}}),(0,G.jsx)(Yu,{size:`xl`,fw:700,children:`powered by mjswan`}),(0,G.jsxs)(Yu,{size:`sm`,c:`dimmed`,children:[`version `,jJ]}),(0,G.jsx)(Yu,{size:`sm`,c:`dimmed`,children:`MuJoco Simulation on Web Assembly with Neural netwroks`}),(0,G.jsx)(pp,{w:`100%`}),(0,G.jsxs)(J,{children:[(0,G.jsx)(Qu,{href:`https://github.com/ttktjmt/mjswan`,target:`_blank`,style:{fontWeight:`600`},children:`GitHub`}),`\xA0\xA0•\xA0\xA0`,(0,G.jsx)(Qu,{href:`https://mjswan.readthedocs.io`,target:`_blank`,style:{fontWeight:`600`},children:`Documentation`})]}),(0,G.jsx)(pp,{w:`100%`}),(0,G.jsxs)(J,{style:{textAlign:`left`,maxHeight:`120px`,overflowY:`auto`,lineHeight:`1`,fontSize:`0.8rem`,opacity:`0.75`},px:`md`,children:[`Thanks to our contributors! `,(0,G.jsx)(`br`,{}),MJ.map((e,t)=>(0,G.jsxs)(`span`,{children:[(0,G.jsx)(Qu,{href:e.html_url,target:`_blank`,style:{textDecoration:`none`,fontSize:`0.75rem`},children:e.login}),t<MJ.length-1&&`, `]},e.login))]})]})}),(0,G.jsxs)(RJ,{width:`20em`,visible:t,onVisibleChange:n,hiddenButtonTooltip:`Show controls (C)`,children:[(0,G.jsxs)(RJ.Handle,{children:[(0,G.jsx)(Uh,{label:`mjswan ${jJ}`,children:(0,G.jsx)(J,{component:`a`,onClick:e=>{e.stopPropagation(),k()},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{position:`absolute`,cursor:`pointer`,display:`flex`,top:`0.8em`,left:`0.9em`},children:(0,G.jsx)(gp,{src:`/logo.svg`,style:{width:`1.2em`,height:`auto`}})})}),(0,G.jsx)(`div`,{style:{width:`1.1em`}}),(0,G.jsx)(RJ.HideWhenCollapsed,{children:(0,G.jsxs)(J,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`,display:`flex`,alignItems:`center`,gap:`0.5em`},pt:`0.1em`,children:[(0,G.jsx)(`span`,{style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:a}),r.length>1&&(0,G.jsxs)(im,{position:`bottom-start`,offset:5,children:[(0,G.jsx)(im.Target,{children:(0,G.jsx)(J,{onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),style:{cursor:`pointer`,display:`flex`,alignItems:`center`,flexShrink:0},children:(0,G.jsx)(DJ,{size:16})})}),(0,G.jsx)(im.Dropdown,{onClick:e=>e.stopPropagation(),children:r.map(e=>(0,G.jsx)(im.Item,{onClick:t=>{t.stopPropagation(),o(e.value)},style:{fontWeight:e.value===i?600:400,backgroundColor:e.value===i?`rgba(34, 139, 230, 0.1)`:void 0},children:e.label},e.value))})]})]})}),(0,G.jsx)(RJ.HideWhenExpanded,{children:(0,G.jsx)(J,{px:`xs`,style:{flexGrow:1,letterSpacing:`-0.5px`},pt:`0.1em`,children:a})}),(0,G.jsx)(Uh,{label:`Hide controls (C)`,children:(0,G.jsx)(Gl,{variant:`subtle`,color:`gray`,size:`sm`,"aria-label":`Hide controls`,onClick:e=>{e.stopPropagation(),n(!1)},onMouseDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),children:(0,G.jsx)(AJ,{size:14})})})]}),(0,G.jsx)(RJ.Contents,{children:(0,G.jsxs)(J,{pt:`0.375em`,children:[s.length>0&&(0,G.jsx)(zJ,{id:`scene-select`,label:`Scene`,children:(0,G.jsx)(Gh,{id:`scene-select`,placeholder:`Select scene`,data:s,value:c,onChange:l,size:`xs`,radius:`xs`,searchable:!0,clearable:!1,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(u.length>0||d)&&(0,G.jsx)(zJ,{id:`splat-select`,label:`Splat`,children:(0,G.jsx)(Uh,{label:N??``,color:`red`,position:`bottom`,opened:N!==null,withArrow:!0,children:(0,G.jsx)(Gh,{id:`splat-select`,placeholder:g===void 0?`Select splat`:`Select splat or paste .spz URL`,data:u,value:f,onChange:e=>{p(e),P(null),I(!1)},searchable:g!==void 0,searchValue:j,onSearchChange:e=>{M(e),e&&P(null)},onKeyDown:L,size:`xs`,radius:`xs`,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})})}),(m?.control&&f!==null||F)&&h&&(0,G.jsx)(KJ,{scale:m?.scale??1,xOffset:m?.xOffset??0,yOffset:m?.yOffset??0,zOffset:m?.zOffset??0,roll:m?.roll??0,pitch:m?.pitch??0,yaw:m?.yaw??0,onCalibrate:h}),_.length>0&&(0,G.jsx)(zJ,{id:`policy-select`,label:`Policy`,children:(0,G.jsx)(Gh,{id:`policy-select`,placeholder:`Select policy`,data:_,value:v,onChange:b,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),x.length>0&&(0,G.jsxs)(G.Fragment,{children:[(0,G.jsx)(zJ,{id:`motion-select`,label:`Motion`,children:(0,G.jsx)(Gh,{id:`motion-select`,placeholder:`Select motion`,data:x,value:S,onChange:C,size:`xs`,radius:`xs`,searchable:!0,clearable:!0,styles:{input:{minHeight:`1.625rem`,height:`1.625rem`,padding:`0.5em`}},comboboxProps:{zIndex:1e3}})}),(0,G.jsx)(J,{pb:`0.5em`,px:`xs`,children:(0,G.jsx)(nf,{label:`Show reference`,checked:w,onChange:e=>T(e.currentTarget.checked),size:`xs`})})]}),B.length>0&&R.some(e=>e.config.type===`slider`||e.config.type===`checkbox`)&&(0,G.jsx)(G.Fragment,{children:B.map(e=>{let t=ie(e);return t.length===0?null:(0,G.jsx)(BJ,{label:JJ(e),expandByDefault:!0,children:t.map(e=>e.config.type===`checkbox`?(0,G.jsx)(XJ,{command:e,value:ee[e.id]??0,onChange:ne,disabled:!E},e.id):e.config.type===`slider`?(0,G.jsx)(YJ,{command:e,value:ee[e.id]??0,onChange:ne,disabled:!E,enabledWhenValue:e.config.enabled_when?ee[cF(e.groupName,e.config.enabled_when)]:void 0},e.id):null)},e)})}),(0,G.jsx)(pp,{mb:`xs`,mx:`xs`}),(0,G.jsx)(J,{px:`xs`,pb:`xs`,children:(0,G.jsx)(yf,{variant:`light`,color:`red`,size:`xs`,fullWidth:!0,leftSection:(0,G.jsx)(kJ,{size:14}),onClick:re,children:`Reset`})})]})})]})]})}function QJ(e,t,n){return Object.keys(e[t]).reduce((e,t)=>(e[t]=`var(--mantine-${n}-${t})`,e),{})}function $J(e,t){return e in t.breakpoints?t.breakpoints[e]:ze(e)}function eY(e){let t=Un(In,e),n=QJ(t,`fontSizes`,`font-size`),r=QJ(t,`lineHeights`,`line-height`),i=QJ(t,`shadows`,`shadow`),a=QJ(t,`radius`,`radius`),o=QJ(t,`spacing`,`spacing`),s=Object.keys(t.headings.sizes).reduce((e,t)=>(e[t]={fontSize:`var(--mantine-${t}-font-size)`,lineHeight:`var(--mantine-${t}-line-height)`,fontWeight:`var(--mantine-${t}-font-weight)`},e),{}),c=Object.keys(t.colors).reduce((e,t)=>(e[t]={0:`var(--mantine-color-${t}-0)`,1:`var(--mantine-color-${t}-1)`,2:`var(--mantine-color-${t}-2)`,3:`var(--mantine-color-${t}-3)`,4:`var(--mantine-color-${t}-4)`,5:`var(--mantine-color-${t}-5)`,6:`var(--mantine-color-${t}-6)`,7:`var(--mantine-color-${t}-7)`,8:`var(--mantine-color-${t}-8)`,9:`var(--mantine-color-${t}-9)`,filled:`var(--mantine-color-${t}-filled)`,filledHover:`var(--mantine-color-${t}-filled-hover)`,light:`var(--mantine-color-${t}-light)`,lightHover:`var(--mantine-color-${t}-light-hover)`,lightColor:`var(--mantine-color-${t}-light-color)`,outline:`var(--mantine-color-${t}-outline)`,outlineHover:`var(--mantine-color-${t}-outline-hover)`},e),{primary:`var(--mantine-primary-color-filled)`,primaryColors:{0:`var(--mantine-primary-color-0)`,1:`var(--mantine-primary-color-1)`,2:`var(--mantine-primary-color-2)`,3:`var(--mantine-primary-color-3)`,4:`var(--mantine-primary-color-4)`,5:`var(--mantine-primary-color-5)`,6:`var(--mantine-primary-color-6)`,7:`var(--mantine-primary-color-7)`,8:`var(--mantine-primary-color-8)`,9:`var(--mantine-primary-color-9)`,filled:`var(--mantine-primary-color-filled)`,filledHover:`var(--mantine-primary-color-filled-hover)`,light:`var(--mantine-primary-color-light)`,lightHover:`var(--mantine-primary-color-light-hover)`,lightColor:`var(--mantine-primary-color-light-color)`,outline:`var(--mantine-primary-color-outline)`,outlineHover:`var(--mantine-primary-color-outline-hover)`},white:`var(--mantine-color-white)`,black:`var(--mantine-color-black)`,text:`var(--mantine-color-text)`,body:`var(--mantine-color-body)`,error:`var(--mantine-color-error)`,placeholder:`var(--mantine-color-placeholder)`,anchor:`var(--mantine-color-anchor)`,default:`var(--mantine-color-default)`,defaultHover:`var(--mantine-color-default-hover)`,defaultColor:`var(--mantine-color-default-color)`,defaultBorder:`var(--mantine-color-default-border)`,dimmed:`var(--mantine-color-dimmed)`,disabledBody:`var(--mantine-color-disabled)`,disabledText:`var(--mantine-color-disabled-color)`,disabledBorder:`var(--mantine-color-disabled-border)`});return{scale:`var(--mantine-scale)`,cursorType:`var(--mantine-cursor-type)`,webkitFontSmoothing:`var(--mantine-webkit-font-smoothing)`,mozFontSmoothing:`var(--mantine-moz-font-smoothing)`,lineHeight:`var(--mantine-line-height)`,fontFamily:`var(--mantine-font-family)`,fontFamilyMonospace:`var(--mantine-font-family-monospace)`,fontFamilyHeadings:`var(--mantine-font-family-headings)`,headingFontWeight:`var(--mantine-heading-font-weight)`,radiusDefault:`var(--mantine-radius-default)`,breakpoints:t.breakpoints,fontSizes:n,lineHeights:r,shadows:i,radius:a,headings:s,spacing:o,colors:c,rtlSelector:`[dir="rtl"] &`,darkSelector:`[data-mantine-color-scheme="dark"] &`,lightSelector:`[data-mantine-color-scheme="light"] &`,smallerThan:e=>`(max-width: ${$J(e,t)})`,largerThan:e=>`(min-width: ${$J(e,t)})`}}var tY=jr({fontFamily:`Inter`,autoContrast:!0,components:{Checkbox:nf.extend({defaultProps:{radius:`xs`}}),ColorInput:lp.extend({defaultProps:{radius:`xs`}}),Select:Gh.extend({defaultProps:{radius:`sm`}}),Textarea:Bp.extend({defaultProps:{radius:`xs`}}),TextInput:hg.extend({defaultProps:{radius:`xs`}}),NumberInput:Th.extend({defaultProps:{radius:`xs`}}),Paper:Jc.extend({defaultProps:{radius:`xs`,shadow:`0`}}),ActionIcon:Gl.extend({defaultProps:{variant:`subtle`,color:`gray`,radius:`xs`}}),Button:yf.extend({defaultProps:{radius:`xs`,styles:{label:{fontWeight:450}}}})}});eY(tY);var nY=(0,y.createContext)(void 0),rY=()=>{let e=(0,y.useContext)(nY);if(!e)throw Error(`useLoading must be used within a LoadingProvider`);return e},iY=({children:e})=>{let[t,n]=(0,y.useState)(!1),[r,i]=(0,y.useState)(null),a=(0,y.useRef)(0),o=(0,y.useCallback)(e=>{a.current+=1,e!==void 0&&i(e),a.current>0&&n(!0)},[]),s=(0,y.useCallback)(e=>{i(e)},[]),c=(0,y.useCallback)(()=>{a.current=Math.max(0,a.current-1),a.current===0&&(n(!1),i(null))},[]);return(0,G.jsx)(nY.Provider,{value:{isLoading:t,loadingMessage:r,showLoading:o,setLoadingMessage:s,hideLoading:c},children:e})},aY=()=>{let{isLoading:e,loadingMessage:t}=rY();return e?(0,G.jsx)(`div`,{className:`loader-overlay`,children:(0,G.jsxs)(`div`,{className:`loader-content`,children:[(0,G.jsx)(Ll,{size:64,type:`bars`}),t&&(0,G.jsx)(`p`,{className:`loader-message`,children:t})]})}):null},oY=!1;function sY(){typeof window>`u`||(window.__mjswanReady=!0,oY||(oY=!0,window.dispatchEvent(new CustomEvent(`mjswan:ready`))))}function cY(){typeof window>`u`||(window.__mjswanError=!0)}function lY(e){return e.toLowerCase().replace(/ /g,`_`).replace(/-/g,`_`)}function uY(e){return e.id?e.id:`main`}function dY(e,t){if(!e.scenes.length)return null;if(!t)return e.scenes[0];let n=t.trim().toLowerCase();return e.scenes.find(e=>e.name.toLowerCase()===n)||e.scenes.find(e=>lY(e.name)===n)||e.scenes[0]}function fY(e,t){if(!e.policies.length)return null;let n=e.policies.find(e=>e.default)??e.policies[0];if(!t)return n.name;let r=t.trim().toLowerCase();return(e.policies.find(e=>e.name.toLowerCase()===r)||e.policies.find(e=>lY(e.name)===r))?.name??n.name}function pY(e,t){if(!e?.motions?.length)return null;let n=e.motions.find(e=>e.default)??e.motions[0];if(!t)return n.name;let r=t.trim().toLowerCase();return(e.motions.find(e=>e.name.toLowerCase()===r)||e.motions.find(e=>lY(e.name)===r))?.name??n.name}function mY(e,t){return`${uY(e)}/assets/${t.path?t.path:`scene/${lY(t.name)}/scene.xml`}`.replace(/\/+/g,`/`)}function hY(e,t){return`${uY(e)}/assets/${t}`.replace(/\/+/g,`/`)}var gY=`panel`,_Y=`ref`;function vY(){let e=`/`.replace(/\/+$/,`/`),t=window.location.pathname.replace(/^\/+|\/+$/g,``),n=e.replace(/^\/+|\/+$/g,``);if(n&&(t===n?t=``:t.startsWith(`${n}/`)&&(t=t.slice(n.length+1))),!t)return null;let r=t.split(`/`)[0];return r===`main`||r.includes(`.`)||r===`assets`?null:r}function yY(e,t){let n=(e||`/`).replace(/\/+$/,`/`),r=new Set,i=(e,t)=>{if(e)try{let n=new URL(e,t||window.location.href).toString();r.add(n)}catch{r.add(e.replace(/\/+/g,`/`))}},a=`${window.location.origin}/`;i(`assets/config.json`,new URL(n,a).toString());let o=window.location.pathname.split(`/`).filter(Boolean);o.length>0&&o[o.length-1]===`index.html`&&o.pop(),o.length>0&&o[o.length-1]===(t??`main`)&&o.pop();let s=`/${o.join(`/`)}${o.length?`/`:``}`;return i(`assets/config.json`,`${window.location.origin}${s}`),i(`assets/config.json`),i(`../assets/config.json`),i(`../../assets/config.json`),Array.from(r)}async function bY(e,t){let n=new URLSearchParams(window.location.search).get(`config`),r=yY(e,t);if(n)try{r.unshift(new URL(n,window.location.href).toString())}catch{r.unshift(n)}let i=null;for(let e of r)try{let t=await fetch(e,{cache:`no-store`});if(!t.ok)throw Error(`Failed to fetch ${e}: ${t.status}`);let n=await t.text(),r=n.trim();if((t.headers.get(`content-type`)||``).includes(`text/html`)||r.startsWith(`<!doctype`)||r.startsWith(`<html`))throw Error(`Received HTML from ${e}`);try{return JSON.parse(n)}catch(t){throw Error(`Invalid JSON from ${e}: ${t instanceof Error?t.message:String(t)}`)}}catch(e){i=e instanceof Error?e:Error(String(e))}throw i??Error(`Failed to load config.json.`)}function xY(e){return new URLSearchParams(e).get(gY)!==`0`}function SY(e){return new URLSearchParams(e).get(_Y)!==`0`}function CY(e){let t=`/`.replace(/\/+$/,`/`).replace(/^\//g,``).replace(/\/+$/g,``),n=t?`/${t}/`:`/`;return e&&e!==`main`&&(n+=`${e}/`),n}function wY({projectId:e,sceneName:t,policyName:n,panelVisible:r,showReference:i}){let a=CY(e),o=new URLSearchParams(window.location.search);t?o.set(`scene`,t):o.delete(`scene`),n?o.set(`policy`,n):o.delete(`policy`),r?o.delete(gY):o.set(gY,`0`),i?o.delete(_Y):o.set(_Y,`0`);let s=o.toString(),c=a+(s?`?${s}`:``)+window.location.hash;window.history.replaceState({},``,c)}function TY(){let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(null),[o,s]=(0,y.useState)(null),[c,l]=(0,y.useState)(null),[u,d]=(0,y.useState)(()=>SY(window.location.search)),[f,p]=(0,y.useState)(null),[m,h]=(0,y.useState)(null),[g,_]=(0,y.useState)(null),[v,b]=(0,y.useState)(()=>xY(window.location.search)),x=(0,y.useRef)(null),{showLoading:S,hideLoading:C,setLoadingMessage:w}=rY(),T=(0,y.useMemo)(()=>vY(),[]),E=(0,y.useMemo)(()=>new URLSearchParams(window.location.search).get(`scene`),[]),D=(0,y.useMemo)(()=>new URLSearchParams(window.location.search).get(`policy`),[]);(0,y.useEffect)(()=>{S(`Loading…`),bY(`/`,T).then(e=>{t(e);let n=e.projects.find(e=>T===null?e.id===null:e.id===T);if(!n)throw Error(`Project "${T??`(main)`}" not found in config.json.`);r(n);let i=dY(n,E);a(i);let o=i?fY(i,D):null;s(o),l(pY(i?.policies.find(e=>e.name===o)??null,null))}).catch(e=>{console.error(`Failed to load config:`,e),p(e.message||`Failed to load config.`),C()})},[T,E,D,S,C]);let O=(0,y.useMemo)(()=>!n||!i?null:mY(n,i),[n,i]),k=(0,y.useMemo)(()=>!i||!o?null:i.policies.find(e=>e.name===o)??null,[i,o]),A=(0,y.useMemo)(()=>!n||!k?.config?null:hY(n,k.config),[n,k]),j=(0,y.useMemo)(()=>k?.motions?.length?k.motions.map(e=>({value:e.name,label:e.name})):[],[k]),M=(0,y.useMemo)(()=>!n||!i?.splats?.length?[]:i.splats.map(e=>e.path?{...e,url:hY(n,e.path)}:e),[n,i?.splats]),N=(0,y.useMemo)(()=>m?M.find(e=>e.name===m)??null:g?{name:`Custom`,url:g}:null,[M,m,g]),P=(0,y.useMemo)(()=>e?e.projects.map(e=>({value:e.id??`main`,label:e.name||(e.id??`Main`)})):[],[e]),F=(0,y.useMemo)(()=>n?n.scenes.map(e=>({value:e.name,label:e.name})):[],[n]),I=(0,y.useMemo)(()=>!i||!i.policies?[]:i.policies.map(e=>({value:e.name,label:e.name})),[i]),L=n?n.id??`main`:null,R=i?.name??null,z=(0,y.useCallback)(e=>{p(e.message),C(),cY()},[C]),B=(0,y.useCallback)(()=>{C(),sY()},[C]),V=(0,y.useCallback)(e=>{e===`Running simulation`||e===`Failed to load scene`||w(e)},[w]);(0,y.useEffect)(()=>{let e=i?.splats?.[0];h(e?e.name:null),_(null)},[i]);let ee=(0,y.useCallback)(e=>{x.current=e},[]);(0,y.useEffect)(()=>{l(pY(k,null)),d(!!k?.motions?.length)},[k]);let te=(0,y.useMemo)(()=>i?.splats?.length?i.splats.map(e=>({value:e.name,label:e.name})):[],[i?.splats]),ne=(0,y.useCallback)(async e=>{h(e),_(null);let t=x.current;if(!t)return;let n=e===null?null:M.find(t=>t.name===e)??null;if(!(e!==null&&!n)){S(e===null?`Removing splat…`:`Loading splat "${e}"…`);try{await t.setSplat(n)}catch(e){console.error(`Failed to load splat:`,e)}finally{C()}}},[M,S,C]),re=(0,y.useCallback)(async e=>{try{if(!(await fetch(e,{method:`HEAD`})).ok)return!1}catch{return!1}let t=x.current;if(!t)return!1;S(`Loading splat "Custom"…`);try{return await t.setSplat({name:`Custom`,url:e}),_(e),!0}catch(e){return console.error(`Failed to load custom splat:`,e),!1}finally{C()}},[S,C]),ie=(0,y.useCallback)((e,t,n,r,i,a,o)=>{let s=N??(g?{name:`Custom`,url:g}:null);s&&x.current?.calibrateSplat({...s,scale:e,xOffset:t,yOffset:n,zOffset:r,roll:i,pitch:a,yaw:o})},[N,g]),ae=(0,y.useCallback)(e=>{wY({projectId:e.projectId??n?.id??null,sceneName:e.sceneName??i?.name??null,policyName:e.policyName??o,panelVisible:e.panelVisible??v,showReference:e.showReference??u})},[n?.id,i?.name,o,v,u]),oe=(0,y.useCallback)(t=>{if(!e||!t)return;let n=t===`main`?null:t,i=e.projects.find(e=>(e.id??`main`)===(n??`main`));if(!i)return;let o=dY(i,null);S(o?`Loading scene "${o.name}"…`:`Loading…`),r(i),a(o);let c=o?fY(o,null):null;s(c),l(pY(o?.policies.find(e=>e.name===c)??null,null)),ae({projectId:i.id,sceneName:o?.name??null,policyName:c})},[e,S,ae]),se=(0,y.useCallback)(e=>{if(!n||!e)return;let t=n.scenes.find(t=>t.name===e);if(!t)return;S(`Loading scene "${t.name}"…`),a(t);let r=fY(t,null);s(r),l(pY(t.policies.find(e=>e.name===r)??null,null)),ae({projectId:n.id,sceneName:e,policyName:r})},[n,S,ae]),H=(0,y.useCallback)(e=>{e!==o&&S(e?`Loading policy "${e}"…`:`Loading policy…`),s(e),l(pY(i?.policies.find(t=>t.name===e)??null,null)),ae({policyName:e})},[o,S,ae]),ce=(0,y.useCallback)(e=>{b(e),ae({panelVisible:e})},[ae]),le=(0,y.useCallback)(async e=>{let t=c;l(e);let n=x.current;if(n){S(e===null?`Clearing motion…`:`Loading motion "${e}"…`);try{await n.setSelectedMotion(e)===!1&&e!==null&&l(n.getSelectedMotionName()??t)}catch(e){console.error(`Failed to load motion:`,e)}finally{C()}}},[c,S,C]),ue=(0,y.useCallback)(e=>{d(e),x.current?.setReferenceVisible(e),ae({showReference:e})},[ae]);return f?(0,G.jsx)(dr,{theme:tY,defaultColorScheme:`auto`,children:(0,G.jsx)(`div`,{className:`app`,children:(0,G.jsxs)(`div`,{className:`hud hud-error`,children:[(0,G.jsx)(`h1`,{className:`hud-title`,children:`mjswan`}),(0,G.jsx)(`p`,{className:`hud-message`,children:f})]})})}):!n||!i||!O?null:(0,G.jsx)(dr,{theme:tY,defaultColorScheme:`auto`,children:(0,G.jsxs)(`div`,{className:`app`,children:[(0,G.jsx)(aY,{}),(0,G.jsx)(ZJ,{visible:v,onVisibleChange:ce,projects:P,projectValue:L,projectLabel:n?.name??`mjswan`,onProjectChange:oe,scenes:F,sceneValue:R,onSceneChange:se,splats:te,splatSection:i?.splatSection??!1,splatValue:m,onSplatChange:ne,splatConfig:N,onCalibrateSplat:ie,onSplatUrlLoad:re,policies:I,policyValue:o,onPolicyChange:H,motions:j,motionValue:c,onMotionChange:le,showReferenceMotion:u,onShowReferenceMotionChange:ue,commandsEnabled:!!A}),(0,G.jsx)(wJ,{scenePath:O,baseUrl:`/`,policyConfigPath:A,splatConfig:N,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:c,showReferenceMotion:u,onError:z,onReady:B,onStatusChange:V,onRuntimeReady:ee})]})})}function EY(){return(0,G.jsx)(iY,{children:(0,G.jsx)(TY,{})})}var DY=document.getElementById(`root`);DY&&(0,gg.createRoot)(DY).render((0,G.jsx)(y.StrictMode,{children:(0,G.jsx)(EY,{})}));
package/dist/index.html CHANGED
@@ -11,7 +11,7 @@
11
11
  />
12
12
  <link rel="manifest" href="manifest.json" />
13
13
  <title>mjswan</title>
14
- <script type="module" crossorigin src="/assets/index-BaczEYWT.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-CYGC4_3w.js"></script>
15
15
  <link rel="modulepreload" crossorigin href="/assets/chunk-BHe-jwch.js">
16
16
  <link rel="modulepreload" crossorigin href="/assets/preload-helper-zJ_50EbN.js">
17
17
  <link rel="stylesheet" crossorigin href="/assets/index-CrgUmStW.css">