mjswan 0.5.4 → 0.5.5

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.
@@ -15606,4 +15606,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
15606
15606
  }`},FR=n=>{let e=n[1].dims,t=n[2].dims,r=n[0].dims,i=n[1].dataType,s=!(Le.areEqual(e,t)&&Le.areEqual(t,r)),a=e,o=Le.size(e);if(s){let c=Zd.calcShape(Zd.calcShape(e,t,!1),r,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,o=Le.size(a)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>LR(c,n,a,s,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:l},...Ct(r,e,t,a)]})}},T4=n=>{n.compute(FR(n.inputs))}}),R4,Jte=et(()=>{dte(),oI(),hte(),fte(),pte(),Ate(),mte(),_te(),wte(),Ete(),Cte(),Ite(),Ste(),Bte(),Mte(),Tte(),Rte(),Dte(),kte(),Nte(),Qte(),Pte(),Lte(),Fte(),zte(),XF(),Ute(),Ote(),$te(),Gte(),Vte(),aI(),Hte(),t4(),jte(),Wte(),qte(),ZF(),Yte(),jl(),lI(),Xte(),R4=new Map([["Abs",[EL]],["Acos",[CL]],["Acosh",[IL]],["Add",[aF]],["ArgMax",[vL,Rw]],["ArgMin",[xL,Rw]],["Asin",[SL]],["Asinh",[BL]],["Atan",[ML]],["Atanh",[TL]],["Attention",[_L]],["AveragePool",[u4,c4]],["BatchNormalization",[bL]],["BiasAdd",[wL]],["BiasSplitGelu",[sF]],["Cast",[DL,RL]],["Ceil",[NL]],["Clip",[kL]],["Concat",[mF,gF]],["Conv",[Lw,Pw]],["ConvTranspose",[SF,IF]],["Cos",[QL]],["Cosh",[PL]],["CumSum",[BF,MF]],["DepthToSpace",[TF,RF]],["DequantizeLinear",[g4,y4]],["Div",[oF]],["Einsum",[DF,kF]],["Elu",[LL,op]],["Equal",[lF]],["Erf",[FL]],["Exp",[zL]],["Expand",[NF]],["FastGelu",[QF]],["Floor",[UL]],["FusedConv",[Lw,Pw]],["Gather",[LF,PF]],["GatherElements",[GF,$F]],["GatherBlockQuantized",[UF,OF]],["GatherND",[FF,zF]],["Gelu",[OL]],["Gemm",[HF,VF]],["GlobalAveragePool",[h4,d4]],["GlobalMaxPool",[m4,A4]],["Greater",[hF]],["GreaterOrEqual",[pF]],["GridSample",[jF,WF]],["GroupQueryAttention",[n4]],["HardSigmoid",[YL,qL]],["InstanceNormalization",[r4]],["LayerNormalization",[i4]],["LeakyRelu",[$L,op]],["Less",[fF]],["LessOrEqual",[AF]],["Log",[rF]],["MatMul",[s4]],["MatMulNBits",[a4,o4]],["MaxPool",[f4,p4]],["Mul",[cF]],["MultiHeadAttention",[YF,qF]],["Neg",[VL]],["Not",[GL]],["Pad",[l4]],["Pow",[uF]],["QuickGelu",[iF,op]],["Range",[x4]],["Reciprocal",[HL]],["ReduceMin",[pL]],["ReduceMean",[cL]],["ReduceMax",[fL]],["ReduceSum",[mL]],["ReduceProd",[AL]],["ReduceL1",[uL]],["ReduceL2",[dL]],["ReduceLogSum",[yL]],["ReduceLogSumExp",[hL]],["ReduceSumSquare",[gL]],["Relu",[jL]],["Resize",[b4,w4]],["RotaryEmbedding",[e4]],["ScatterND",[_4,v4]],["Sigmoid",[WL]],["Sin",[XL]],["Sinh",[JL]],["Slice",[C4,I4]],["SkipLayerNormalization",[E4]],["Split",[JF,KF]],["Sqrt",[KL]],["Softmax",[S4,B4]],["Sub",[dF]],["Tan",[ZL]],["Tanh",[eF]],["ThresholdedRelu",[nF,op]],["Tile",[M4]],["Transpose",[JP,KP]],["Where",[T4]]])}),D4,Kte=et(()=>{xs(),No(),Wt(),D4=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,e){this.repo.set(n,e)}run(n,e,t,r,i){Fa(n.programInfo.name);let s=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let o=[];for(let c of e)o.push({binding:o.length,resource:{buffer:c.buffer}});for(let c of t)o.push({binding:o.length,resource:{buffer:c.buffer}});i&&o.push({binding:o.length,resource:i});let l=s.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:o,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:l,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}a.setPipeline(n.computePipeline),a.setBindGroup(0,l),a.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(),Zs(n.programInfo.name)}dispose(){}build(n,e){Fa(n.name);let t=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&r.push(`enable ${c.extension};`)});let i=XP(e,this.backend.device.limits),s=n.getShaderSource(i),a=`${r.join(`
15607
15607
  `)}
15608
15608
  ${i.additionalImplementations}
15609
- ${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Zs(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),k4={};vh(k4,{WebGpuBackend:()=>N4});var zR,UR,OR,N4,Zte=et(()=>{xs(),Lt(),No(),HP(),cte(),Jte(),Kte(),zR=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r<n.length;++r){let i=n[r].dataType;switch(e[r]){case"none":{t.push("");break}case"type":{t.push(`${i}`);break}case"rank":{let s=n[r].dims.length;t.push(`${i};${s}`);break}case"dims":{let s=n[r].dims.join(",");t.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return t.join("|")},UR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${zR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},OR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},N4=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 new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=s=>e.features.has(s)&&t.push(s)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await e.requestDevice(r),this.adapterInfo=new OR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=qP(this),this.programManager=new D4(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nI(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Fa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let y=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:po(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:po(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:y,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${po(_.dataType)}, `});let g="";h.forEach((_,b)=>{g+=`output[${b}]: [${_.dims}] | ${po(_.dataType)}, `})}qg("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Zs()}run(n,e,t,r,i,s){Fa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Zs(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,$;M.type===10?($=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):($=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/$)*$,b.push(_);let Q=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/Q)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${po(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let y=this.programManager.normalizeDispatchGroupSize(l),m=y[1]===1&&y[2]===1,x=UR(n,e,m),g=this.programManager.getArtifact(x);if(g||(g=this.programManager.build(n,y),this.programManager.setArtifact(x,g),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=g.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${g.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(g,a,p,y,A),Zs(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=R4.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Bw(this,n,e);return rI(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}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(){un("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(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[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(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Q4={};vh(Q4,{init:()=>P4});var ng,$R,P4,ene=et(()=>{Lt(),No(),jt(),lte(),ng=class L4{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Le.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 new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Le.size(e)!==Le.size(this.dims))throw new Error("Invalid new shape");return new L4(this.module,this.dataType,this.data,e)}},$R=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.PTR_SIZE,i=t/n.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(n.getValue(r*i++,s));let a=Number(n.getValue(r*i++,s));this.outputCount=Number(n.getValue(r*i++,s)),this.customDataOffset=Number(n.getValue(r*i++,"*")),this.customDataSize=Number(n.getValue(r*i++,s));let o=[];for(let l=0;l<a;l++){let c=Number(n.getValue(r*i++,s)),d=Number(n.getValue(r*i++,"*")),h=Number(n.getValue(r*i++,s)),p=[];for(let A=0;A<h;A++)p.push(Number(n.getValue(r*i++,s)));o.push(new ng(n,c,d,p))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(n,e){let t=e?.inputs?.map(a=>typeof a=="number"?this.inputs[a]:a)??this.inputs,r=e?.outputs??[],i=(a,o,l)=>new ng(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Pc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ng(this.module,a,c,o)};return this.backend.run(n,t,r,i,s,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.PTR_SIZE,i=r===4?"i32":"i64",s=this.module.stackAlloc((1+e.length)*r);this.module.setValue(s,e.length,i);for(let a=0;a<e.length;a++)this.module.setValue(s+r*(a+1),e[a],i);return this.module._JsepOutput(this.opKernelContext,n,s)}catch(r){throw new Error(`Failed to generate kernel's output[${n}] with dims [${e}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(t)}}},P4=async(n,e,t,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let s=(Zte(),Pp(k4)).WebGpuBackend,a=new s;await a.initialize(t,r),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,l,c,d=!1)=>{if(d)un("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(o),Number(l));else{un("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let h=e.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(c));a.upload(Number(l),h)}},async(o,l,c)=>{un("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${l}, size=${c}`),await a.download(Number(o),()=>e.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(o,l,c)=>a.createKernel(o,Number(l),c,e.UTF8ToString(e._JsepGetNodeName(Number(l)))),o=>a.releaseKernel(o),(o,l,c,d)=>{un("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${o}, contextDataOffset=${l}`);let h=new $R(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new WP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),GR,pI,AI,Il,VR,G_,t0,mI,gI,V_,yI,xI,vI,F4=et(()=>{xs(),ite(),ste(),Lt(),cu(),KC(),OP(),GR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},pI=async n=>{GR(n.wasm.numThreads,Xg(n.logLevel))},AI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(ene(),Pp(Q4)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},Il=new Map,VR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},G_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},t0=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},mI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=t0(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await UP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(tI(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=VR(s),A=!!e?.enableGraphCapture,y=[],m=[],x=[],g=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=G_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);y.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=G_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),g.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>Iw(w))}),Il.set(s,[s,c,d,b,A,!1]),[s,y,m,x,g]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},gI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),Il.delete(n)},V_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,y;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let g=n[2].gpuBuffer;y=Pc(Qc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,g,y)}}else if(h==="ml-tensor"){let g=n[2].mlTensor;y=Pc(Qc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,g,Qc(c),d)}else{let g=n[2];if(Array.isArray(g)){y=l*g.length,A=o._malloc(y),t.push(A);for(let _=0;_<g.length;_++){if(typeof g[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Gs(g[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Qc(c);y=Pc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),A=T}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let g=o._OrtCreateTensor(Qc(c),A,y,x,d.length,Iw(p));g===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},yI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=Il.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],y=l[5],m=e.length,x=r.length,g=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),$=a.stackAlloc(x*o);try{[g,_]=zP(s),Wc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)await V_(t[W],b,C,n,d[e[W]],e[W],A);for(let W=0;W<x;W++)await V_(i[W],w,C,n,h[r[W]],m+r[W],A);qc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)a.setValue(T+W*o,b[W],"*"),a.setValue(R+W*o,d[e[W]],"*");for(let W=0;W<x;W++)a.setValue(k+W*o,w[W],"*"),a.setValue($+W*o,h[r[W]],"*");if(p&&!y){let{handle:W,outputPreferredLocations:K,outputPreferredLocationsEncoded:Y}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);Wc("wasm bindInputsOutputs");for(let G=0;G<m;G++){let X=e[G];await a._OrtBindInput(W,d[X],b[G])!==0&&wn(`Can't bind input[${G}] for session=${n}.`)}for(let G=0;G<x;G++){let X=r[G];i[G]?.[3]?(S.push(w[G]),a._OrtBindOutput(W,h[X],w[G],0)!==0&&wn(`Can't bind pre-allocated output[${G}] for session=${n}.`)):a._OrtBindOutput(W,h[X],0,Y[X])!==0&&wn(`Can't bind output[${G}] to ${K[G]} for session=${n}.`)}qc("wasm bindInputsOutputs"),Il.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let Q;p?Q=await a._OrtRunWithBinding(c,p.handle,x,k,g):Q=await a._OrtRun(c,R,T,m,$,x,k,g),Q!==0&&wn("failed to call OrtRun().");let H=[],B=[];Wc("wasm ProcessOutputTensor");for(let W=0;W<x;W++){let K=Number(a.getValue(k+W*o,"*"));if(K===w[W]||S.includes(w[W])){H.push(i[W]),K!==w[W]&&a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.");continue}let Y=a.stackSave(),G=a.stackAlloc(4*o),X=!1,re,L=0;try{a._OrtGetTensorData(K,G,G+o,G+2*o,G+3*o)!==0&&wn(`Can't access output tensor data on index ${W}.`);let V=o===4?"i32":"i64",oe=Number(a.getValue(G,V));L=a.getValue(G+o,"*");let Ae=a.getValue(G+o*2,"*"),ye=Number(a.getValue(G+o*3,V)),he=[];for(let Re=0;Re<ye;Re++)he.push(Number(a.getValue(Ae+Re*o,V)));a._OrtFree(Ae)!==0&&wn("Can't free memory for tensor dims.");let fe=he.reduce((Re,ve)=>Re*ve,1);re=po(oe);let Ee=p?.outputPreferredLocations[r[W]];if(re==="string"){if(Ee==="gpu-buffer"||Ee==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Re=[];for(let ve=0;ve<fe;ve++){let Ne=a.getValue(L+ve*o,"*"),rt=a.getValue(L+(ve+1)*o,"*"),Ge=ve===fe-1?void 0:rt-Ne;Re.push(a.UTF8ToString(Ne,Ge))}H.push([re,he,Re,"cpu"])}else if(Ee==="gpu-buffer"&&fe>0){let Re=a.jsepGetBuffer;if(!Re)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Re(L),Ne=Pc(oe,fe);if(Ne===void 0||!ZC(re))throw new Error(`Unsupported data type: ${re}`);X=!0,H.push([re,he,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,Ne,re),dispose:()=>{a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(Ee==="ml-tensor"&&fe>0){let Re=a.webnnEnsureTensor,ve=a.webnnIsGraphInputOutputTypeSupported;if(!Re||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Pc(oe,fe)===void 0||!eI(re))throw new Error(`Unsupported data type: ${re}`);if(!ve(n,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let Ne=await Re(n,L,oe,he,!1);X=!0,H.push([re,he,{mlTensor:Ne,download:a.webnnCreateMLTensorDownloader(L,re),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K)}},"ml-tensor"])}else if(Ee==="ml-tensor-cpu-output"&&fe>0){let Re=a.webnnCreateMLTensorDownloader(L,re)(),ve=H.length;X=!0,B.push((async()=>{let Ne=[ve,await Re];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K),Ne})()),H.push([re,he,[],"cpu"])}else{let Re=Z0(re),ve=new Re(fe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(L,L+ve.byteLength)),H.push([re,he,ve,"cpu"])}}finally{a.stackRestore(Y),re==="string"&&L&&a._free(L),X||a._OrtReleaseTensor(K)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),Il.set(n,[c,d,h,p,A,!1]));for(let[W,K]of await Promise.all(B))H[W][2]=K;return qc("wasm ProcessOutputTensor"),H}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(Q=>a._OrtReleaseTensor(Q)),w.forEach(Q=>a._OrtReleaseTensor(Q)),C.forEach(Q=>a._free(Q)),g!==0&&a._OrtReleaseRunOptions(g),_.forEach(Q=>a._free(Q))}},xI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},vI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Sl,ts,Ed,qf,Yf,rg,H_,ig,Ic,Sc,HR,z4,U4,O4,$4,G4,V4,H4,j4=et(()=>{xs(),F4(),cu(),XC(),Sl=()=>!!Dn.wasm.proxy&&typeof document<"u",Ed=!1,qf=!1,Yf=!1,ig=new Map,Ic=(n,e)=>{let t=ig.get(n);t?t.push(e):ig.set(n,[e])},Sc=()=>{if(Ed||!qf||Yf||!ts)throw new Error("worker not ready")},HR=n=>{switch(n.data.type){case"init-wasm":Ed=!1,n.data.err?(Yf=!0,H_[1](n.data.err)):(qf=!0,H_[0]()),rg&&(URL.revokeObjectURL(rg),rg=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ig.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},z4=async()=>{if(!qf){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Yf)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sl())return new Promise((n,e)=>{ts?.terminate(),LP().then(([t,r])=>{try{ts=r,ts.onerror=s=>e(s),ts.onmessage=HR,H_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||Cw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),ts.postMessage(i),rg=t}catch(i){e(i)}},e)});try{await JC(Dn.wasm),await pI(Dn),qf=!0}catch(n){throw Yf=!0,n}finally{Ed=!1}}},U4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};ts.postMessage(r)});await AI(Dn,n)},O4=async n=>Sl()?(Sc(),new Promise((e,t)=>{Ic("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};ts.postMessage(r,[n.buffer])})):t0(n),$4=async(n,e)=>{if(Sl()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sc(),new Promise((t,r)=>{Ic("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),ts.postMessage(i,s)})}else return mI(n,e)},G4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("release",[e,t]);let r={type:"release",in:n};ts.postMessage(r)});gI(n)},V4=async(n,e,t,r,i,s)=>{if(Sl()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sc(),new Promise((a,o)=>{Ic("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};ts.postMessage(c,vI(l))})}else return yI(n,e,t,r,i,s)},H4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("end-profiling",[e,t]);let r={type:"end-profiling",in:n};ts.postMessage(r)});xI(n)}}),j_,jR,W4,tne=et(()=>{xs(),j4(),Lt(),YC(),OP(),j_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},jR=n=>{switch(n[3]){case"cpu":return new ti(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!ZC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return ti.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!eI(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return ti.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},W4=class{async fetchModelAndCopyToWasmMemory(n){return O4(await tI(n))}async loadModel(n,e){Fa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await $4(t,e),Zs()}async dispose(){return G4(this.sessionId)}async run(n,e,t){Fa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],y=this.inputNames.indexOf(p);if(y===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(y)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],y=this.outputNames.indexOf(p);if(y===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(y)});let o=r.map((h,p)=>j_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?j_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await V4(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??jR(c[h]);return Zs(),d}startProfiling(){}endProfiling(){H4(this.sessionId)}}}),q4={};vh(q4,{OnnxruntimeWebAssemblyBackend:()=>Uw,initializeFlags:()=>zw,wasmBackend:()=>Y4});var zw,Uw,Y4,nne=et(()=>{xs(),j4(),tne(),zw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?Uee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Uw=class{async init(n){zw(),await z4(),await U4(n)}async createInferenceSessionHandler(n,e){let t=new W4;return await t.loadModel(n,e),t}},Y4=new Uw});xs();xs();xs();var rne="1.24.3";{let n=(nne(),Pp(q4)).wasmBackend;Bd("webgpu",n,5),Bd("webnn",n,5),Bd("cpu",n,10),Bd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:rne,enumerable:!0});class ine{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=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(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const 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(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}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)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}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,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class sne{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.configuredInKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await qC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes("adapt_hx")}initInput(){const e={};return this.isRecurrent&&(e.is_init=new ti("bool",[!0],[1]),e.adapt_hx=new ti("float32",new Float32Array(128),[1,128])),this.inKeys.includes("time_step")&&(e.time_step=new ti("float32",new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new ti("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}inferInputKeys(){if(!this.session)return;const 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(t=>this.configuredInKeys.includes(t)?t:t==="obs"&&this.configuredInKeys.includes("policy")?"policy":t)}}class ane{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}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;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class X4{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class one{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){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],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}}class lne extends X4{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.tracking=new one(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class cne{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){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],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}}class une extends X4{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.locomotion=new cne(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class dne{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];i&&this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class J4{constructor(e){this.config=e}}const hne={};class K4 extends J4{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class fne extends J4{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new K4(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const pne={ResetRootStateUniform:K4,ResetRootStateFromFlatPatches:fne},Ane={...pne,...hne};function sg(n){return typeof n=="object"&&n!==null&&typeof n.setSelectedMotion=="function"}class Z4 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 WR(n){const e=n instanceof Error?n.message:String(n);return e.includes("MjModel loading returned null")||e.includes("Could not allocate memory")||e.includes("memory allocation failed")||e.includes("bad_alloc")}class mne{constructor(e,t,r={}){this.render=()=>{if(Kn().updateDebugVisuals(),this.mjData&&$Z(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}L3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&hX({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:o,height:l}=this.getSize();this.camera.aspect=o/l,this.camera.updateProjectionMatrix(),this.renderer.setSize(o,l)},this.mujoco=e,this.container=t,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code}const{width:s,height:a}=this.getSize();this.scene=new s9,this.scene.name="scene",this.camera=new zr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new z7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=NN,this.renderer.outputColorSpace=ii,this.renderer.toneMapping=QN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=RC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new O7(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:fX()},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.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,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=ww.getInstance(this.mujoco),this.resourceTracker=new GZ,this.memoryMonitor=new VZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?this.eventManager=new dne(s,Ane):this.eventManager=null,await this.stop(),this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}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 bX(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=tB(r,this.scene),r.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=Kn();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){Kn().initialize(e,t)}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}async setSelectedMotion(e){const t=Kn().getTerm("motion");if(!sg(t))return!1;const r=await t.setSelectedMotion(e);return r&&this.resetSimulation(),r}getSelectedMotionName(){const e=Kn().getTerm("motion");return sg(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){const t=Kn().getTerm("motion");!sg(t)||typeof t.setReferenceVisible!="function"||t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await vX(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),L3(this.mujoco,this.mjData,this.lights),F3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({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(!WR(t))throw t;this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,WR(r)?new Z4:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=tB(e,this.scene),e.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&aP(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const 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){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null;l&&Array.from(l.slice(0,8))}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}Kn().update(t),Kn().updateDebugVisuals()}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;const r=Kn();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e&&!(!this.mjModel||!this.mjData)){e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(Array.isArray(i.motions)&&(i.motions=i.motions.map(o=>({...o,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,o.path))}))),i.commands?.motion&&Array.isArray(i.motions)&&(i.commands.motion={...i.commands.motion,motions:i.motions}),this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"){this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),Kn().resetTerms();const o=Kn().getTerm("motion");sg(o)&&(await o.setSelectedMotion(i.motions?.find(l=>l.default)?.name??i.motions?.[0]?.name??null),o.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new ine(i,{policyModules:{tracking:lne,locomotion:une},observations:Mee});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new ane(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new Tee(i.terminations,Pee)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new sne(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}}catch{}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,y,m,x)=>{const g=h.qposAdr.length,_=h.actionIndices.map(Q=>i[Q]),b=this.normalizeControlArray(p,g,1,_),w=this.normalizeControlArray(A,g,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(g);for(let Q=0;Q<g;Q++)S[Q]=C[h.actionIndices[Q]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(g);for(let Q=0;Q<g;Q++)T[Q]=M[h.actionIndices[Q]]??0;const R=this.normalizeControlArray(y,g,0,_),k=this.normalizeControlArray(m,g,0,_),$=h.ctrlAdr.map(Q=>Q<0||!this.mjModel?!1:this.mjModel.actuator_biastype[Q]===s);return $.some(Boolean),$.some(Q=>!Q),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:$,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return null;const d=r.getControlMapping();if(!d)return null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque")continue;const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let y;if(A){const x=r.getControlMapping();if(!x)continue;y={...x,actionIndices:Array.from({length:x.qposAdr.length},(g,_)=>_)}}else if(y=r.getControlMappingFor(p,i),!y)continue;const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,y,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?null:l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t&&(s[l]=o)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),Kn().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;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:y,kd:m}=r,x=s.length;if(i==="joint_position")for(let g=0;g<x;g++){const _=s[g];if(_<0)continue;const b=t[l[g]]??0,w=h[g]+d[g]+c[g]*b-p[g];if(A[g])e[_]=w;else{const C=this.mjData.qpos[a[g]],S=this.mjData.qvel[o[g]];e[_]=y[g]*(w-C)+m[g]*(0-S)}}else if(i==="torque")for(let g=0;g<x;g++){const _=s[g];_>=0&&(e[_]=c[g]*(t[l[g]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};this.onnxModule.inKeys.includes("time_step")&&(t.time_step=new ti("float32",new Float32Array([this.onnxTimeStep]),[1,1]));for(const[d,h]of Object.entries(e))t[d]=new ti("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d])return;const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i}),this.onnxModule.inKeys.includes("time_step")&&(this.onnxTimeStep+=1);const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c)return;this.policyRunner.setLastActions(l)}catch{}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(jc(this.mjData.xpos,p,this.bodies[p].position),pp(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=P3(r),s=this.dragStateManager.worldHit.clone(),a=P3(s),o=new ue(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new ue(a.x-o.x,a.y-o.y,a.z-o.z),c=new ue(i.x,i.y,i.z),d=new ue().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const 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 ue,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&dX(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=OZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=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(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const 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(){const 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){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),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,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot)return;const r=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 ph?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const ag="mjswan_oom_reload_scene",gne=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,selectedMotion:o,showReferenceMotion:l=!0,onStatusChange:c,onError:d,onReady:h,onRuntimeReady:p})=>{const A=U.useRef(null),y=U.useRef(null),m=U.useRef(null),x=U.useRef(r);x.current=r;const g=U.useRef(o);g.current=o;const _=U.useRef(l);return _.current=l,U.useEffect(()=>{let b=!1;const w=S=>{c?.(S)};return(async()=>{if(w("Loading MuJoCo..."),!m.current){const T=await RV(()=>import("./mujoco-DesrhgLU.js"),[]);m.current=await T.default()}if(b)return;const S=A.current;if(!S)throw new Error("Failed to find viewer container.");const M=m.current;if(!M)throw new Error("MuJoCo not loaded.");y.current||(y.current=new mne(M,S,{baseUrl:e}),p?.(y.current)),w("Loading scene assets..."),await y.current.loadEnvironment(n,t??null,x.current??null,i??null,s??null,a??null),await y.current.setSelectedMotion(g.current??null),y.current.setReferenceVisible(_.current),!b&&(sessionStorage.removeItem(ag),w("Running simulation"),h?.())})().catch(S=>{if(!b){if(S instanceof Z4){if(sessionStorage.getItem(ag)!==n){sessionStorage.setItem(ag,n),window.location.reload();return}sessionStorage.removeItem(ag)}d?.(S instanceof Error?S:new Error(String(S))),w("Failed to load scene")}}),()=>{b=!0,y.current?.dispose(),y.current=null}},[n,e,t,i,s,a,c,d,h]),U.useEffect(()=>{y.current&&y.current.setSelectedMotion(o??null)},[o]),U.useEffect(()=>{y.current?.setReferenceVisible(l)},[l]),j.jsx("div",{ref:A,className:"viewer"})};var yne={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"}};const ey=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...yne[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,y])=>U.createElement(A,y)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const xne=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],ez=ey("outline","chevron-down","ChevronDown",xne);const vne=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],_ne=ey("outline","chevron-up","ChevronUp",vne);const bne=[["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"}]],wne=ey("outline","refresh","Refresh",bne);const Ene=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Cne=ey("outline","x","X",Ene),qR="0.5.4",YR=[{login:"ttktjmt",html_url:"https://github.com/ttktjmt"},{login:"claude",html_url:"https://github.com/claude"},{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:"Axellwppr",html_url:"https://github.com/Axellwppr"},{login:"CharlieLeee",html_url:"https://github.com/CharlieLeee"}],Ine={move:"touchmove",end:"touchend"},Sne={move:"mousemove",end:"mouseup"};function Bne(n){return n.type==="touchmove"}function Mne(n){return n.type==="mousemove"}const jp=On.createContext(null);function Ao({children:n,width:e,visible:t=!0,onVisibleChange:r,hiddenButtonTooltip:i}){const s=On.useRef(null),[a,{toggle:o}]=s0(!0),[l,c]=On.useState(800),d=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),h=On.useRef({}),p=(x,g,_)=>Math.abs(x+g/2)<Math.abs(x-_+g/2)?x:x-_,A=15;function y(x,g){const _=s.current;if(_===null)return[x,g];const b=_.parentElement;if(b===null)return[x,g];let w=x,C=g;return w=Math.min(w,b.clientWidth-_.clientWidth-A),w=Math.max(w,A),C=Math.min(C,b.clientHeight-_.clientHeight-A),C=Math.max(C,A),_.style.top=`${C.toString()}px`,_.style.left=`${w.toString()}px`,[p(w,_.clientWidth,b.clientWidth),p(C,_.clientHeight,b.clientHeight)]}On.useEffect(()=>{const x=s.current;if(x===null)return;const g=x.parentElement;if(g===null)return;const _=new ResizeObserver(()=>{h.current.x===void 0&&(h.current.x=p(x.offsetLeft,x.clientWidth,g.clientWidth)),h.current.y===void 0&&(h.current.y=p(x.offsetTop,x.clientHeight,g.clientHeight));const b=g.clientHeight-A*2;l!==b&&c(b);let w=h.current.x,C=h.current.y;for(;w<0;)w+=g.clientWidth;for(;C<0;)C+=g.clientHeight;y(w,C)});return _.observe(x),_.observe(g),()=>{_.disconnect()}});const m=x=>{const g=d.current,_=s.current;if(!_)return;x.type=="touchstart"?(x=x,g.startClientX=x.touches[0].clientX,g.startClientY=x.touches[0].clientY):(x=x,g.startClientX=x.clientX,g.startClientY=x.clientY),g.startPosX=_.offsetLeft,g.startPosY=_.offsetTop;const b=x.type=="touchstart"?Ine:Sne;function w(C){let S=0,M=0;if(Bne(C)?(C=C,S=C.touches[0].clientX-g.startClientX,M=C.touches[0].clientY-g.startClientY):Mne(C)&&(C=C,S=C.clientX-g.startClientX,M=C.clientY-g.startClientY),Math.abs(S)<=3&&Math.abs(M)<=3)return;g.dragging=!0;const T=g.startPosX+S,R=g.startPosY+M;[h.current.x,h.current.y]=y(T,R)}window.addEventListener(b.move,w),window.addEventListener(b.end,()=>{x.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(b.move,w)},{once:!0})};if(!t){const x=j.jsx(Je,{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 j.jsx(Je,{style:{zIndex:10,position:"absolute",top:"1em",right:"1em"},children:i?j.jsx(Pl,{label:i,children:j.jsx(Je,{children:x})}):x})}return j.jsx(jp.Provider,{value:{wrapperRef:s,expanded:a,width:e,maxHeight:l,toggleExpanded:o,dragHandler:m,dragInfo:d},children:j.jsx(Xc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:s,children:n})})}Ao.Handle=function({children:e}){const t=On.useContext(jp);return j.jsx(j.Fragment,{children:j.jsx(Je,{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:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};Ao.Contents=function({children:e}){const t=On.useContext(jp);return j.jsxs(Mg,{in:t.expanded,children:[j.jsx(Dd,{mx:"xs"}),j.jsx(su.Autosize,{mah:t.maxHeight,children:j.jsx(Je,{style:{width:t.width},children:e})})]})};Ao.HideWhenCollapsed=function({children:e}){return On.useContext(jp)?.expanded??!0?e:null};Ao.HideWhenExpanded=function({children:e}){return On.useContext(jp)?.expanded??!0?null:e};function og({id:n,label:e,children:t}){return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsxs(EE,{align:"center",children:[j.jsx(Je,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:j.jsx("label",{htmlFor:n,children:e})})}),j.jsx(Je,{style:{flexGrow:1},children:t})]})})}function tz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=s0(e),s=r?_ne:ez;return j.jsxs(Xc,{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:[j.jsxs(Xc,{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:[n,j.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),j.jsx(Mg,{in:r,children:j.jsx(Je,{pt:"1em",children:t})}),j.jsx(Mg,{in:!r,children:j.jsx(Je,{p:"xs"})})]})}const nz={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Tne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Rne={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 W_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const y=a.current;y&&document.activeElement!==y&&(y.value=e.toFixed(2))},[e]);const l=y=>Math.max(t,Math.min(r,parseFloat((Math.round(y/i)*i).toFixed(10)))),c=y=>{y.preventDefault(),y.currentTarget.setPointerCapture(y.pointerId),o.current={startY:y.clientY,startValue:e,moved:!1}},d=y=>{if(!o.current||!(y.buttons&1))return;const m=o.current.startY-y.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const y=a.current;y&&(y.focus(),y.select())}o.current=null},p=y=>{const m=parseFloat(y.target.value);isNaN(m)||s(l(m)),y.target.value=e.toFixed(2)},A=y=>{y.key==="Enter"&&y.currentTarget.blur(),y.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return j.jsxs(Je,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),j.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:y=>y.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:y=>y.currentTarget.style.outline="none",style:Rne})]})}function XR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:n}),j.jsx(W_,{axis:s,value:e,step:i,onChange:l}),j.jsx(W_,{axis:a,value:t,step:i,onChange:c}),j.jsx(W_,{axis:o,value:r,step:i,onChange:d})]})}function Dne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[y,m]=U.useState(r),[x,g]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{g(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,$,Q,H)=>o(M,T,R,k,$,Q,H);return j.jsxs(tz,{label:"Control",expandByDefault:!0,children:[j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:"Scale"}),j.jsx(Je,{style:{flex:1},children:j.jsx(P0,{value:l,onChange:M=>{c(M),S(M,d,p,y,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Tne})})]}),j.jsx(XR,{label:"Position",x:d,y:p,z:y,step:.05,onX:M=>{h(M),S(l,M,p,y,x,_,w)},onY:M=>{A(M),S(l,d,M,y,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),j.jsx(XR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{g(M),S(l,d,p,y,M,_,w)},onY:M=>{b(M),S(l,d,p,y,x,M,w)},onZ:M=>{C(M),S(l,d,p,y,x,_,M)}})]})}function kne(n){return n instanceof HTMLElement?n.isContentEditable?!0:n.closest('input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]')!==null:!1}function Nne(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Qne({command:n,value:e,onChange:t,disabled:r,enabledWhenValue:i}){const s=n.config,a=s.enabled_when!==void 0&&(i??0)<.5,o=r||a;return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:s.label}),j.jsx(Je,{style:{width:"50%"},children:j.jsx(P0,{value:e,onChange:l=>t(n.id,l),min:s.min,max:s.max,step:s.step,size:"xs",disabled:o,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function Pne({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:i.label,checked:e>=.5,onChange:s=>t(n.id,s.currentTarget.checked?1:0),size:"xs",disabled:r})})}function Lne(n){const{visible:e,onVisibleChange:t,projects:r,projectValue:i,projectLabel:s,onProjectChange:a,scenes:o,sceneValue:l,onSceneChange:c,splats:d,splatSection:h=!1,splatValue:p,onSplatChange:A,splatConfig:y,onCalibrateSplat:m,onSplatUrlLoad:x,policies:g,policyValue:_,onPolicyChange:b,motions:w,motionValue:C,onMotionChange:S,showReferenceMotion:M,onShowReferenceMotionChange:T,commandsEnabled:R=!1,onReset:k}=n,[$,{open:Q,close:H}]=s0(!1),[B,W]=U.useState(""),[K,Y]=U.useState(null),[G,X]=U.useState(!1),re=U.useCallback(async ve=>{if(ve.key!=="Enter"||!x)return;const Ne=B.trim();if(d.some(Ge=>Ge.label===Ne||Ge.value===Ne))return;if(!Ne.toLowerCase().endsWith(".spz")){Y("URL must end with .spz");return}await x(Ne)?(Y(null),X(!0)):Y("File not found at the specified URL")},[x,B,d]),[L,V]=U.useState([]),[oe,Ae]=U.useState([]),[ye,he]=U.useState({});U.useEffect(()=>{const ve=Kn(),Ne=()=>{V(ve.getCommands()),Ae(ve.getCommandGroups()),he(ve.getValues())};return Ne(),ve.addEventListener(Ne),()=>{ve.removeEventListener(Ne)}},[]),U.useEffect(()=>{const ve=Ne=>{if(Ne.defaultPrevented||Ne.repeat||Ne.altKey||Ne.ctrlKey||Ne.metaKey||Ne.key.toLowerCase()!=="c")return;const rt=Ne.target instanceof Element?Ne.target:document.activeElement;kne(rt)||(Ne.preventDefault(),t(!e))};return window.addEventListener("keydown",ve),()=>{window.removeEventListener("keydown",ve)}},[e,t]);const fe=U.useCallback((ve,Ne)=>{Kn().setValue(ve,Ne),he(Ge=>({...Ge,[ve]:Ne}))},[]),Ee=U.useCallback(()=>{Kn().triggerButton("_system:reset"),k&&k()},[k]),Re=ve=>L.filter(Ne=>Ne.groupName===ve&&(Ne.config.type==="slider"||Ne.config.type==="checkbox"));return!r.length&&!o.length&&!g.length?null:j.jsxs(j.Fragment,{children:[j.jsx(aa,{opened:$,onClose:H,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:j.jsxs(sC,{gap:"md",align:"center",children:[j.jsx(Pg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),j.jsx(Xs,{size:"xl",fw:700,children:"powered by mjswan"}),j.jsxs(Xs,{size:"sm",c:"dimmed",children:["version ",qR]}),j.jsx(Xs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{children:[j.jsx(up,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",j.jsx(up,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",j.jsx("br",{}),YR.map((ve,Ne)=>j.jsxs("span",{children:[j.jsx(up,{href:ve.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:ve.login}),Ne<YR.length-1&&", "]},ve.login))]})]})}),j.jsxs(Ao,{width:"20em",visible:e,onVisibleChange:t,hiddenButtonTooltip:"Show controls (C)",children:[j.jsxs(Ao.Handle,{children:[j.jsx(Pl,{label:`mjswan ${qR}`,children:j.jsx(Je,{component:"a",onClick:ve=>{ve.stopPropagation(),Q()},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:j.jsx(Pg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),j.jsx("div",{style:{width:"1.1em"}}),j.jsx(Ao.HideWhenCollapsed,{children:j.jsxs(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[j.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),r.length>1&&j.jsxs(pi,{position:"bottom-start",offset:5,children:[j.jsx(pi.Target,{children:j.jsx(Je,{onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center",flexShrink:0},children:j.jsx(ez,{size:16})})}),j.jsx(pi.Dropdown,{onClick:ve=>ve.stopPropagation(),children:r.map(ve=>j.jsx(pi.Item,{onClick:Ne=>{Ne.stopPropagation(),a(ve.value)},style:{fontWeight:ve.value===i?600:400,backgroundColor:ve.value===i?"rgba(34, 139, 230, 0.1)":void 0},children:ve.label},ve.value))})]})]})}),j.jsx(Ao.HideWhenExpanded,{children:j.jsx(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:s})}),j.jsx(Pl,{label:"Hide controls (C)",children:j.jsx(au,{variant:"subtle",color:"gray",size:"sm","aria-label":"Hide controls",onClick:ve=>{ve.stopPropagation(),t(!1)},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),children:j.jsx(Cne,{size:14})})})]}),j.jsx(Ao.Contents,{children:j.jsxs(Je,{pt:"0.375em",children:[o.length>0&&j.jsx(og,{id:"scene-select",label:"Scene",children:j.jsx(zc,{id:"scene-select",placeholder:"Select scene",data:o,value:l,onChange:c,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(d.length>0||h)&&j.jsx(og,{id:"splat-select",label:"Splat",children:j.jsx(Pl,{label:K??"",color:"red",position:"bottom",opened:K!==null,withArrow:!0,children:j.jsx(zc,{id:"splat-select",placeholder:x!==void 0?"Select splat or paste .spz URL":"Select splat",data:d,value:p,onChange:ve=>{A(ve),Y(null),X(!1)},searchable:x!==void 0,searchValue:B,onSearchChange:ve=>{W(ve),ve&&Y(null)},onKeyDown:re,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(y?.control&&p!==null||G)&&m&&j.jsx(Dne,{scale:y?.scale??1,xOffset:y?.xOffset??0,yOffset:y?.yOffset??0,zOffset:y?.zOffset??0,roll:y?.roll??0,pitch:y?.pitch??0,yaw:y?.yaw??0,onCalibrate:m}),g.length>0&&j.jsx(og,{id:"policy-select",label:"Policy",children:j.jsx(zc,{id:"policy-select",placeholder:"Select policy",data:g,value:_,onChange:b,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),w.length>0&&j.jsxs(j.Fragment,{children:[j.jsx(og,{id:"motion-select",label:"Motion",children:j.jsx(zc,{id:"motion-select",placeholder:"Select motion",data:w,value:C,onChange:S,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:"Show reference",checked:M,onChange:ve=>T(ve.currentTarget.checked),size:"xs"})})]}),oe.length>0&&L.some(ve=>ve.config.type==="slider"||ve.config.type==="checkbox")&&j.jsx(j.Fragment,{children:oe.map(ve=>{const Ne=Re(ve);return Ne.length===0?null:j.jsx(tz,{label:Nne(ve),expandByDefault:!0,children:Ne.map(rt=>rt.config.type==="checkbox"?j.jsx(Pne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R},rt.id):rt.config.type!=="slider"?null:j.jsx(Qne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R,enabledWhenValue:rt.config.enabled_when?ye[Ew(rt.groupName,rt.config.enabled_when)]:void 0},rt.id))},ve)})}),j.jsx(Dd,{mb:"xs",mx:"xs"}),j.jsx(Je,{px:"xs",pb:"xs",children:j.jsx(lh,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:j.jsx(wne,{size:14}),onClick:Ee,children:"Reset"})})]})})]})]})}function Xf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function JR(n,e){return n in e.breakpoints?e.breakpoints[n]:X_(n)}function Fne(n){const e=bD(c0,n),t=Xf(e,"fontSizes","font-size"),r=Xf(e,"lineHeights","line-height"),i=Xf(e,"shadows","shadow"),s=Xf(e,"radius","radius"),a=Xf(e,"spacing","spacing"),o=Object.keys(e.headings.sizes).reduce((c,d)=>(c[d]={fontSize:`var(--mantine-${d}-font-size)`,lineHeight:`var(--mantine-${d}-line-height)`,fontWeight:`var(--mantine-${d}-font-weight)`},c),{}),l=Object.keys(e.colors).reduce((c,d)=>(c[d]={0:`var(--mantine-color-${d}-0)`,1:`var(--mantine-color-${d}-1)`,2:`var(--mantine-color-${d}-2)`,3:`var(--mantine-color-${d}-3)`,4:`var(--mantine-color-${d}-4)`,5:`var(--mantine-color-${d}-5)`,6:`var(--mantine-color-${d}-6)`,7:`var(--mantine-color-${d}-7)`,8:`var(--mantine-color-${d}-8)`,9:`var(--mantine-color-${d}-9)`,filled:`var(--mantine-color-${d}-filled)`,filledHover:`var(--mantine-color-${d}-filled-hover)`,light:`var(--mantine-color-${d}-light)`,lightHover:`var(--mantine-color-${d}-light-hover)`,lightColor:`var(--mantine-color-${d}-light-color)`,outline:`var(--mantine-color-${d}-outline)`,outlineHover:`var(--mantine-color-${d}-outline-hover)`},c),{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:e.breakpoints,fontSizes:t,lineHeights:r,shadows:i,radius:s,headings:o,spacing:a,colors:l,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:c=>`(max-width: ${JR(c,e)})`,largerThan:c=>`(min-width: ${JR(c,e)})`}}const Ow={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Gl.extend({defaultProps:{radius:"xs"}}),ColorInput:jE.extend({defaultProps:{radius:"xs"}}),Select:zc.extend({defaultProps:{radius:"sm"}}),Textarea:qE.extend({defaultProps:{radius:"xs"}}),TextInput:aC.extend({defaultProps:{radius:"xs"}}),NumberInput:nC.extend({defaultProps:{radius:"xs"}}),Paper:Xc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:au.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:lh.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Fne(Ow);const rz=U.createContext(void 0),iz=()=>{const n=U.useContext(rz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},zne=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return j.jsx(rz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Une=()=>{const{isLoading:n}=iz();return n?j.jsx("div",{className:"loader-overlay",children:j.jsx("div",{className:"loader-content",children:j.jsx(sh,{size:64,type:"bars"})})}):null},$w="panel",Gw="ref";function One(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function _I(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function $ne(n,e){const t=n.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const A=new URL(h,p||window.location.href).toString();r.add(A)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,a=new URL(t,s).toString();i("assets/config.json",a);const l=window.location.pathname.split("/").filter(Boolean);l.length>0&&l[l.length-1]==="index.html"&&l.pop(),l.length>0&&l[l.length-1]===(e??"main")&&l.pop();const c=`/${l.join("/")}${l.length?"/":""}`,d=`${window.location.origin}${c}`;return i("assets/config.json",d),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function Gne(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=$ne(n,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const a of i)try{const o=await fetch(a,{cache:"no-store"});if(!o.ok)throw new Error(`Failed to fetch ${a}: ${o.status}`);const l=await o.text(),c=l.trim();if((o.headers.get("content-type")||"").includes("text/html")||c.startsWith("<!doctype")||c.startsWith("<html"))throw new Error(`Received HTML from ${a}`);try{return JSON.parse(l)}catch(h){throw new Error(`Invalid JSON from ${a}: ${h instanceof Error?h.message:String(h)}`)}}catch(o){s=o instanceof Error?o:new Error(String(o))}throw s??new Error("Failed to load config.json.")}function KR(n,e){if(!n.scenes.length)return null;if(!e)return n.scenes[0];const t=e.trim().toLowerCase();return n.scenes.find(r=>r.name.toLowerCase()===t)||n.scenes.find(r=>_I(r.name)===t)||n.scenes[0]}function q_(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>_I(s.name)===r))?.name??t.name}function Jf(n,e){return n?.motions?.length?(n.motions.find(r=>r.default)??n.motions[0]).name:null}function Vne(n){return new URLSearchParams(n).get($w)!=="0"}function Hne(n){return new URLSearchParams(n).get(Gw)!=="0"}function jne(n){const t="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let r=t?`/${t}/`:"/";return n&&n!=="main"&&(r+=`${n}/`),r}function Wne({projectId:n,sceneName:e,policyName:t,panelVisible:r,showReference:i}){const s=jne(n),a=new URLSearchParams(window.location.search);e?a.set("scene",e):a.delete("scene"),t?a.set("policy",t):a.delete("policy"),r?a.delete($w):a.set($w,"0"),i?a.delete(Gw):a.set(Gw,"0");const o=a.toString(),l=s+(o?`?${o}`:"")+window.location.hash;window.history.replaceState({},"",l)}function qne(){const[n,e]=U.useState(null),[t,r]=U.useState(null),[i,s]=U.useState(null),[a,o]=U.useState(null),[l,c]=U.useState(null),[d,h]=U.useState(()=>Hne(window.location.search)),[p,A]=U.useState(null),[y,m]=U.useState(null),[x,g]=U.useState(null),[_,b]=U.useState(()=>Vne(window.location.search)),w=U.useRef(null),{showLoading:C,hideLoading:S}=iz(),M=U.useMemo(()=>One(),[]),T=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),R=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{C(),Gne("/",M).then(J=>{e(J);const ge=J.projects.find(Ce=>M===null?Ce.id===null:Ce.id===M);if(!ge)throw new Error(`Project "${M??"(main)"}" not found in config.json.`);r(ge);const te=KR(ge,T);s(te);const ee=te?q_(te,R):null;o(ee);const ie=te?.policies.find(Ce=>Ce.name===ee)??null;c(Jf(ie))}).catch(J=>{A(J.message||"Failed to load config."),S()})},[M,T,R,C,S]);const k=U.useMemo(()=>{if(!t||!i)return null;const J=t.id?t.id:"main",ge=i.path?i.path:`scene/${_I(i.name)}/scene.xml`;return`${J}/assets/${ge}`.replace(/\/+/g,"/")},[t,i]),$=U.useMemo(()=>!i||!a?null:i.policies.find(J=>J.name===a)??null,[i,a]),Q=U.useMemo(()=>!t||!$?.config?null:`${t.id?t.id:"main"}/assets/${$.config}`.replace(/\/+/g,"/"),[t,$]),H=U.useMemo(()=>$?.motions?.length?$.motions.map(J=>({value:J.name,label:J.name})):[],[$]),B=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const J=t.id?t.id:"main";return i.splats.map(ge=>{if(ge.path){const te=`${J}/assets/${ge.path}`.replace(/\/+/g,"/");return{...ge,url:te}}return ge})},[t,i?.splats]),W=U.useMemo(()=>y?B.find(J=>J.name===y)??null:x?{name:"Custom",url:x}:null,[B,y,x]),K=U.useMemo(()=>n?n.projects.map(J=>({value:J.id??"main",label:J.name||(J.id??"Main")})):[],[n]),Y=U.useMemo(()=>t?t.scenes.map(J=>({value:J.name,label:J.name})):[],[t]),G=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(J=>({value:J.name,label:J.name})),[i]),X=t?t.id??"main":null,re=i?.name??null,L=U.useCallback(J=>{A(J.message),S()},[S]),V=U.useCallback(()=>{S()},[S]);U.useEffect(()=>{const J=i?.splats?.[0];m(J?J.name:null),g(null)},[i]);const oe=U.useCallback(J=>{w.current=J},[]);U.useEffect(()=>{c(Jf($)),h(!!$?.motions?.length)},[$]);const Ae=U.useMemo(()=>i?.splats?.length?i.splats.map(J=>({value:J.name,label:J.name})):[],[i?.splats]),ye=U.useCallback(J=>{if(J===null)w.current?.setSplat(null);else{const ge=B.find(te=>te.name===J);ge&&w.current?.setSplat(ge)}m(J),g(null)},[B]),he=U.useCallback(async J=>{try{if(!(await fetch(J,{method:"HEAD"})).ok)return!1}catch{return!1}return w.current?.setSplat({name:"Custom",url:J}),g(J),!0},[]),fe=U.useCallback((J,ge,te,ee,ie,Ce,be)=>{const de=W??(x?{name:"Custom",url:x}:null);de&&w.current?.calibrateSplat({...de,scale:J,xOffset:ge,yOffset:te,zOffset:ee,roll:ie,pitch:Ce,yaw:be})},[W,x]),Ee=U.useCallback(J=>{Wne({projectId:J.projectId??t?.id??null,sceneName:J.sceneName??i?.name??null,policyName:J.policyName??a,panelVisible:J.panelVisible??_,showReference:J.showReference??d})},[t?.id,i?.name,a,_,d]),Re=U.useCallback(J=>{if(!n||!J)return;const ge=J==="main"?null:J,te=n.projects.find(be=>(be.id??"main")===(ge??"main"));if(!te)return;C(),r(te);const ee=KR(te,null);s(ee);const ie=ee?q_(ee,null):null;o(ie);const Ce=ee?.policies.find(be=>be.name===ie)??null;c(Jf(Ce)),Ee({projectId:te.id,sceneName:ee?.name??null,policyName:ie})},[n,C,Ee]),ve=U.useCallback(J=>{if(!t||!J)return;const ge=t.scenes.find(ie=>ie.name===J);if(!ge)return;C(),s(ge);const te=q_(ge,null);o(te);const ee=ge.policies.find(ie=>ie.name===te)??null;c(Jf(ee)),Ee({projectId:t.id,sceneName:J,policyName:te})},[t,C,Ee]),Ne=U.useCallback(J=>{J!==a&&C(),o(J);const ge=i?.policies.find(te=>te.name===J)??null;c(Jf(ge)),Ee({policyName:J})},[a,C,Ee]),rt=U.useCallback(J=>{b(J),Ee({panelVisible:J})},[Ee]),Ge=U.useCallback(J=>{const ge=l;c(J),w.current?.setSelectedMotion(J)?.then(ee=>{ee===!1&&J!==null&&c(w.current?.getSelectedMotionName()??ge)})},[l]),F=U.useCallback(J=>{h(J),w.current?.setReferenceVisible(J),Ee({showReference:J})},[Ee]);return p?j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsx("div",{className:"app",children:j.jsxs("div",{className:"hud hud-error",children:[j.jsx("h1",{className:"hud-title",children:"mjswan"}),j.jsx("p",{className:"hud-message",children:p})]})})}):!t||!i||!k?null:j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsxs("div",{className:"app",children:[j.jsx(Une,{}),j.jsx(Lne,{visible:_,onVisibleChange:rt,projects:K,projectValue:X,projectLabel:t?.name??"mjswan",onProjectChange:Re,scenes:Y,sceneValue:re,onSceneChange:ve,splats:Ae,splatSection:i?.splatSection??!1,splatValue:y,onSplatChange:ye,splatConfig:W,onCalibrateSplat:fe,onSplatUrlLoad:he,policies:G,policyValue:a,onPolicyChange:Ne,motions:H,motionValue:l,onMotionChange:Ge,showReferenceMotion:d,onShowReferenceMotionChange:F,commandsEnabled:!!Q}),j.jsx(gne,{scenePath:k,baseUrl:"/",policyConfigPath:Q,splatConfig:W,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:l,showReferenceMotion:d,onError:L,onReady:V,onRuntimeReady:oe})]})})}function Yne(){return j.jsx(zne,{children:j.jsx(qne,{})})}const ZR=document.getElementById("root");ZR&&Wz.createRoot(ZR).render(j.jsx(On.StrictMode,{children:j.jsx(Yne,{})}));export{RV as _};
15609
+ ${s}`,o=t.createShaderModule({code:a,label:n.name});un("verbose",()=>`[WebGPU] ${n.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:n.name});return Zs(n.name),{programInfo:n,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,r=typeof n=="number"?1:n.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&t<=i&&r<=i)return[e,t,r];let s=e*t*r,a=Math.ceil(Math.sqrt(s));if(a>i){if(a=Math.ceil(Math.cbrt(s)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),k4={};vh(k4,{WebGpuBackend:()=>N4});var zR,UR,OR,N4,Zte=et(()=>{xs(),Lt(),No(),HP(),cte(),Jte(),Kte(),zR=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let r=0;r<n.length;++r){let i=n[r].dataType;switch(e[r]){case"none":{t.push("");break}case"type":{t.push(`${i}`);break}case"rank":{let s=n[r].dims.length;t.push(`${i};${s}`);break}case"dims":{let s=n[r].dims.join(",");t.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return t.join("|")},UR=(n,e,t)=>{let r=n.name;return n.shaderCache?.hint&&(r+="["+n.shaderCache.hint+"]"),r+=":"+t+`:${zR(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},OR=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},N4=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 new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=s=>e.features.has(s)&&t.push(s)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await e.requestDevice(r),this.adapterInfo=new OR(e.info||await e.requestAdapterInfo()),this.gpuDataManager=qP(this),this.programManager=new D4(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,nI(n.logLevel,!!n.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Fa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let r=0;r<e.length/2;r++){let i=t[r],s=i.kernelId,a=this.kernels.get(s),o=a.kernelType,l=a.kernelName,c=i.programName,d=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],A=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let y=Number(p-this.queryTimeBase),m=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(m))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(x=>({dims:x.dims,dataType:po(x.dataType)})),outputsMetadata:h.map(x=>({dims:x.dims,dataType:po(x.dataType)})),kernelId:s,kernelType:o,kernelName:l,programName:c,startTime:y,endTime:m});else{let x="";d.forEach((_,b)=>{x+=`input[${b}]: [${_.dims}] | ${po(_.dataType)}, `});let g="";h.forEach((_,b)=>{g+=`output[${b}]: [${_.dims}] | ${po(_.dataType)}, `})}qg("GPU",`${c}::${p}::${A}`)}n.unmap(),this.pendingQueries.delete(n)}),Zs()}run(n,e,t,r,i,s){Fa(n.name);let a=[];for(let _=0;_<e.length;++_){let b=e[_].data;if(b===0)continue;let w=this.gpuDataManager.get(b);if(!w)throw new Error(`no GPU data for input: ${b}`);a.push(w)}let{outputs:o,dispatchGroup:l,programUniforms:c}=n.getRunData(e),d=t.length===0?o.map((_,b)=>b):t;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h=[],p=[];for(let _=0;_<o.length;++_){if(!Number.isInteger(d[_])||d[_]<-3||d[_]>=s)throw new Error(`Invalid output index: ${d[_]}`);if(d[_]===-3)continue;let b=d[_]===-1,w=d[_]===-2,C=b||w?i(o[_].dataType,o[_].dims):r(d[_],o[_].dataType,o[_].dims);if(h.push(C),C.data===0)continue;let S=this.gpuDataManager.get(C.data);if(!S)throw new Error(`no GPU data for output: ${C.data}`);if(b&&this.temporaryData.push(S),w){let M=this.kernelPersistentData.get(this.currentKernelId);M||(M=[],this.kernelPersistentData.set(this.currentKernelId,M)),M.push(S)}p.push(S)}if(a.length!==e.length||p.length!==h.length){if(p.length===0)return Zs(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let A;if(c){let _=0,b=[];c.forEach(M=>{let T=typeof M.data=="number"?[M.data]:M.data;if(T.length===0)return;let R=M.type===10?2:4,k,$;M.type===10?($=T.length>4?16:T.length>2?8:T.length*R,k=T.length>4?16:R*T.length):($=T.length<=2?T.length*R:16,k=16),_=Math.ceil(_/$)*$,b.push(_);let Q=M.type===10?8:4;_+=T.length>4?Math.ceil(T.length/Q)*k:T.length*R});let w=16;_=Math.ceil(_/w)*w;let C=new ArrayBuffer(_);c.forEach((M,T)=>{let R=b[T],k=typeof M.data=="number"?[M.data]:M.data;if(M.type===6)new Int32Array(C,R,k.length).set(k);else if(M.type===12)new Uint32Array(C,R,k.length).set(k);else if(M.type===10)new Uint16Array(C,R,k.length).set(k);else if(M.type===1)new Float32Array(C,R,k.length).set(k);else throw new Error(`Unsupported uniform type: ${po(M.type)}`)});let S=this.gpuDataManager.create(_,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(S.buffer,0,C,0,_),this.gpuDataManager.release(S.id),A={offset:0,size:_,buffer:S.buffer}}let y=this.programManager.normalizeDispatchGroupSize(l),m=y[1]===1&&y[2]===1,x=UR(n,e,m),g=this.programManager.getArtifact(x);if(g||(g=this.programManager.build(n,y),this.programManager.setArtifact(x,g),un("info",()=>`[artifact] key: ${x}, programName: ${n.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let _=0;_<c.length;_++){let b=c[_],w=b.type,C=typeof b.data=="number"?1:b.data.length,[S,M]=g.uniformVariablesInfo[_];if(w!==S||C!==M)throw new Error(`Uniform variable ${_} mismatch: expect type ${S} with size ${M}, got type ${w} with size ${C} in program "${g.programInfo.name}".`)}}if(un("info",()=>`[ProgramManager] run "${n.name}" (key=${x}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let _={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(_),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(_)}return this.programManager.run(g,a,p,y,A),Zs(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,r){let i=R4.get(n);if(!i)throw new Error(`kernel not implemented: ${n}`);let s={kernelType:n,kernelName:r,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(e,s)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let r=this.kernels.get(n);if(!r)throw new Error(`kernel not created: ${n}`);let i=r.kernelType,s=r.kernelName,a=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=n,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),un("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(e,o[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${i}] ${s}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,r){let i=this.sessionExternalDataMapping.get(n);i||(i=new Map,this.sessionExternalDataMapping.set(n,i));let s=i.get(e),a=this.gpuDataManager.registerExternalBuffer(t,r,s);return i.set(e,[a,t]),a}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let r=await Bw(this,n,e);return rI(r.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}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(){un("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(){un("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){un("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let r=0;r<t;r++){let i=this.getComputePassEncoder(),s=n[r];this.writeTimestamp(this.pendingDispatchNumber*2),i.setPipeline(s.computePipeline),i.setBindGroup(0,s.bindGroup),i.dispatchWorkgroups(...s.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(e[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(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),Q4={};vh(Q4,{init:()=>P4});var ng,$R,P4,ene=et(()=>{Lt(),No(),jt(),lte(),ng=class L4{constructor(e,t,r,i){this.module=e,this.dataType=t,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=Le.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 new Error("Invalid data type");let e=Le.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(Le.size(e)!==Le.size(this.dims))throw new Error("Invalid new shape");return new L4(this.module,this.dataType,this.data,e)}},$R=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=n.PTR_SIZE,i=t/n.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(n.getValue(r*i++,s));let a=Number(n.getValue(r*i++,s));this.outputCount=Number(n.getValue(r*i++,s)),this.customDataOffset=Number(n.getValue(r*i++,"*")),this.customDataSize=Number(n.getValue(r*i++,s));let o=[];for(let l=0;l<a;l++){let c=Number(n.getValue(r*i++,s)),d=Number(n.getValue(r*i++,"*")),h=Number(n.getValue(r*i++,s)),p=[];for(let A=0;A<h;A++)p.push(Number(n.getValue(r*i++,s)));o.push(new ng(n,c,d,p))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(n,e){let t=e?.inputs?.map(a=>typeof a=="number"?this.inputs[a]:a)??this.inputs,r=e?.outputs??[],i=(a,o,l)=>new ng(this.module,o,this.output(a,l),l),s=(a,o)=>{let l=Pc(a,o);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ng(this.module,a,c,o)};return this.backend.run(n,t,r,i,s,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let r=this.module.PTR_SIZE,i=r===4?"i32":"i64",s=this.module.stackAlloc((1+e.length)*r);this.module.setValue(s,e.length,i);for(let a=0;a<e.length;a++)this.module.setValue(s+r*(a+1),e[a],i);return this.module._JsepOutput(this.opKernelContext,n,s)}catch(r){throw new Error(`Failed to generate kernel's output[${n}] with dims [${e}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${r}`)}finally{this.module.stackRestore(t)}}},P4=async(n,e,t,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let s=(Zte(),Pp(k4)).WebGpuBackend,a=new s;await a.initialize(t,r),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,l,c,d=!1)=>{if(d)un("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(o),Number(l));else{un("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let h=e.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(c));a.upload(Number(l),h)}},async(o,l,c)=>{un("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${l}, size=${c}`),await a.download(Number(o),()=>e.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(o,l,c)=>a.createKernel(o,Number(l),c,e.UTF8ToString(e._JsepGetNodeName(Number(l)))),o=>a.releaseKernel(o),(o,l,c,d)=>{un("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${o}, contextDataOffset=${l}`);let h=new $R(e,a,Number(l));return a.computeKernel(Number(o),h,d)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let s=new WP(t);i("webnn",[s,()=>s.reserveTensorId(),a=>s.releaseTensorId(a),async(a,o,l,c,d)=>s.ensureTensor(a,o,l,c,d),(a,o)=>{s.uploadTensor(a,o)},async(a,o)=>s.downloadTensor(a,o),(a,o)=>s.registerMLContext(a,o),!!t.trace])}}}),GR,pI,AI,Il,VR,G_,t0,mI,gI,V_,yI,xI,vI,F4=et(()=>{xs(),ite(),ste(),Lt(),cu(),KC(),OP(),GR=(n,e)=>{kn()._OrtInit(n,e)!==0&&wn("Can't initialize onnxruntime.")},pI=async n=>{GR(n.wasm.numThreads,Xg(n.logLevel))},AI=async(n,e)=>{kn().asyncInit?.();let t=n.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(t){if(typeof t.limits!="object"||typeof t.features!="object"||typeof t.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=n.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=n.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(t=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!t)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(e==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let r=(ene(),Pp(Q4)).init;e==="webgpu"&&await r("webgpu",kn(),n,t),e==="webnn"&&await r("webnn",kn(),n)}},Il=new Map,VR=n=>{let e=kn(),t=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(n,i,i+r)!==0&&wn("Can't get session input/output count.");let s=r===4?"i32":"i64";return[Number(e.getValue(i,s)),Number(e.getValue(i+r,s))]}finally{e.stackRestore(t)}},G_=(n,e)=>{let t=kn(),r=t.stackSave(),i=0;try{let s=t.PTR_SIZE,a=t.stackAlloc(2*s);t._OrtGetInputOutputMetadata(n,e,a,a+s)!==0&&wn("Can't get session input/output metadata.");let o=Number(t.getValue(a,"*"));i=Number(t.getValue(a+s,"*"));let l=t.HEAP32[i/4];if(l===0)return[o,0];let c=t.HEAPU32[i/4+1],d=[];for(let h=0;h<c;h++){let p=Number(t.getValue(i+8+h*s,"*"));d.push(p!==0?t.UTF8ToString(p):Number(t.getValue(i+8+(h+c)*s,"*")))}return[o,l,d]}finally{t.stackRestore(r),i!==0&&t._OrtFree(i)}},t0=n=>{let e=kn(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},mI=async(n,e)=>{let t,r,i=kn();Array.isArray(n)?[t,r]=n:n.buffer===i.HEAPU8.buffer?[t,r]=[n.byteOffset,n.byteLength]:[t,r]=t0(n);let s=0,a=0,o=0,l=[],c=[],d=[];try{if([a,l]=await UP(e),e?.externalData&&i.mountExternalData){let w=[];for(let C of e.externalData){let S=typeof C=="string"?C:C.path;w.push(tI(typeof C=="string"?C:C.data).then(M=>{i.mountExternalData(S,M)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,S=C?.context,M=C?.gpuDevice,T=C?.deviceType,R=C?.powerPreference;S?i.currentContext=S:M?i.currentContext=await i.webnnCreateMLContext(M):i.currentContext=await i.webnnCreateMLContext({deviceType:T,powerPreference:R})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(t,r,a),i.webgpuOnCreateSession?.(s),s===0&&wn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=VR(s),A=!!e?.enableGraphCapture,y=[],m=[],x=[],g=[],_=[];for(let w=0;w<h;w++){let[C,S,M]=G_(s,w);C===0&&wn("Can't get an input name."),c.push(C);let T=i.UTF8ToString(C);y.push(T),x.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M})}for(let w=0;w<p;w++){let[C,S,M]=G_(s,w+h);C===0&&wn("Can't get an output name."),d.push(C);let T=i.UTF8ToString(C);m.push(T),g.push(S===0?{name:T,isTensor:!1}:{name:T,isTensor:!0,type:po(S),shape:M});{if(A&&e?.preferredOutputLocation===void 0){_.push("gpu-buffer");continue}let R=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[T]??"cpu",k=i.webnnIsGraphOutput;if(R==="cpu"&&k&&k(s,T)){_.push("ml-tensor-cpu-output");continue}if(R!=="cpu"&&R!=="cpu-pinned"&&R!=="gpu-buffer"&&R!=="ml-tensor")throw new Error(`Not supported preferred output location: ${R}.`);if(A&&R!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${R}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);_.push(R)}}let b=null;return _.some(w=>w==="gpu-buffer"||w==="ml-tensor"||w==="ml-tensor-cpu-output")&&(o=i._OrtCreateBinding(s),o===0&&wn("Can't create IO binding."),b={handle:o,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(w=>w==="ml-tensor-cpu-output"?"ml-tensor":w).map(w=>Iw(w))}),Il.set(s,[s,c,d,b,A,!1]),[s,y,m,x,g]}catch(h){throw c.forEach(p=>i._OrtFree(p)),d.forEach(p=>i._OrtFree(p)),o!==0&&i._OrtReleaseBinding(o)!==0&&wn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&wn("Can't release session."),h}finally{i._free(t),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&wn("Can't release session options."),l.forEach(h=>i._free(h)),i.unmountExternalData?.()}},gI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[r,i,s,a,o]=t;a&&(o&&e._OrtClearBoundOutputs(a.handle)!==0&&wn("Can't clear bound outputs."),e._OrtReleaseBinding(a.handle)!==0&&wn("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),i.forEach(l=>e._OrtFree(l)),s.forEach(l=>e._OrtFree(l)),e._OrtReleaseSession(r)!==0&&wn("Can't release session."),Il.delete(n)},V_=async(n,e,t,r,i,s,a=!1)=>{if(!n){e.push(0);return}let o=kn(),l=o.PTR_SIZE,c=n[0],d=n[1],h=n[3],p=h,A,y;if(c==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let g=n[2].gpuBuffer;y=Pc(Qc(c),d);{let _=o.jsepRegisterBuffer;if(!_)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');A=_(r,s,g,y)}}else if(h==="ml-tensor"){let g=n[2].mlTensor;y=Pc(Qc(c),d);let _=o.webnnRegisterMLTensor;if(!_)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');A=_(r,g,Qc(c),d)}else{let g=n[2];if(Array.isArray(g)){y=l*g.length,A=o._malloc(y),t.push(A);for(let _=0;_<g.length;_++){if(typeof g[_]!="string")throw new TypeError(`tensor data at index ${_} is not a string`);o.setValue(A+_*l,Gs(g[_],t),"*")}}else{let _=o.webnnIsGraphInput,b=o.webnnIsGraphOutput;if(c!=="string"&&_&&b){let w=o.UTF8ToString(i);if(_(r,w)||b(r,w)){let C=Qc(c);y=Pc(C,d),p="ml-tensor";let S=o.webnnCreateTemporaryTensor,M=o.webnnUploadTensor;if(!S||!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let T=await S(r,C,d);M(T,new Uint8Array(g.buffer,g.byteOffset,g.byteLength)),A=T}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}else y=g.byteLength,A=o._malloc(y),t.push(A),o.HEAPU8.set(new Uint8Array(g.buffer,g.byteOffset,y),A)}}let m=o.stackSave(),x=o.stackAlloc(4*d.length);try{d.forEach((_,b)=>o.setValue(x+b*l,_,l===4?"i32":"i64"));let g=o._OrtCreateTensor(Qc(c),A,y,x,d.length,Iw(p));g===0&&wn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(g)}finally{o.stackRestore(m)}},yI=async(n,e,t,r,i,s)=>{let a=kn(),o=a.PTR_SIZE,l=Il.get(n);if(!l)throw new Error(`cannot run inference. invalid session id: ${n}`);let c=l[0],d=l[1],h=l[2],p=l[3],A=l[4],y=l[5],m=e.length,x=r.length,g=0,_=[],b=[],w=[],C=[],S=[],M=a.stackSave(),T=a.stackAlloc(m*o),R=a.stackAlloc(m*o),k=a.stackAlloc(x*o),$=a.stackAlloc(x*o);try{[g,_]=zP(s),Wc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)await V_(t[W],b,C,n,d[e[W]],e[W],A);for(let W=0;W<x;W++)await V_(i[W],w,C,n,h[r[W]],m+r[W],A);qc("wasm prepareInputOutputTensor");for(let W=0;W<m;W++)a.setValue(T+W*o,b[W],"*"),a.setValue(R+W*o,d[e[W]],"*");for(let W=0;W<x;W++)a.setValue(k+W*o,w[W],"*"),a.setValue($+W*o,h[r[W]],"*");if(p&&!y){let{handle:W,outputPreferredLocations:K,outputPreferredLocationsEncoded:Y}=p;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);Wc("wasm bindInputsOutputs");for(let G=0;G<m;G++){let X=e[G];await a._OrtBindInput(W,d[X],b[G])!==0&&wn(`Can't bind input[${G}] for session=${n}.`)}for(let G=0;G<x;G++){let X=r[G];i[G]?.[3]?(S.push(w[G]),a._OrtBindOutput(W,h[X],w[G],0)!==0&&wn(`Can't bind pre-allocated output[${G}] for session=${n}.`)):a._OrtBindOutput(W,h[X],0,Y[X])!==0&&wn(`Can't bind output[${G}] to ${K[G]} for session=${n}.`)}qc("wasm bindInputsOutputs"),Il.set(n,[c,d,h,p,A,!0])}a.jsepOnRunStart?.(c),a.webnnOnRunStart?.(c);let Q;p?Q=await a._OrtRunWithBinding(c,p.handle,x,k,g):Q=await a._OrtRun(c,R,T,m,$,x,k,g),Q!==0&&wn("failed to call OrtRun().");let H=[],B=[];Wc("wasm ProcessOutputTensor");for(let W=0;W<x;W++){let K=Number(a.getValue(k+W*o,"*"));if(K===w[W]||S.includes(w[W])){H.push(i[W]),K!==w[W]&&a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.");continue}let Y=a.stackSave(),G=a.stackAlloc(4*o),X=!1,re,L=0;try{a._OrtGetTensorData(K,G,G+o,G+2*o,G+3*o)!==0&&wn(`Can't access output tensor data on index ${W}.`);let V=o===4?"i32":"i64",oe=Number(a.getValue(G,V));L=a.getValue(G+o,"*");let Ae=a.getValue(G+o*2,"*"),ye=Number(a.getValue(G+o*3,V)),he=[];for(let Re=0;Re<ye;Re++)he.push(Number(a.getValue(Ae+Re*o,V)));a._OrtFree(Ae)!==0&&wn("Can't free memory for tensor dims.");let fe=he.reduce((Re,ve)=>Re*ve,1);re=po(oe);let Ee=p?.outputPreferredLocations[r[W]];if(re==="string"){if(Ee==="gpu-buffer"||Ee==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Re=[];for(let ve=0;ve<fe;ve++){let Ne=a.getValue(L+ve*o,"*"),rt=a.getValue(L+(ve+1)*o,"*"),Ge=ve===fe-1?void 0:rt-Ne;Re.push(a.UTF8ToString(Ne,Ge))}H.push([re,he,Re,"cpu"])}else if(Ee==="gpu-buffer"&&fe>0){let Re=a.jsepGetBuffer;if(!Re)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=Re(L),Ne=Pc(oe,fe);if(Ne===void 0||!ZC(re))throw new Error(`Unsupported data type: ${re}`);X=!0,H.push([re,he,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,Ne,re),dispose:()=>{a._OrtReleaseTensor(K)!==0&&wn("Can't release tensor.")}},"gpu-buffer"])}else if(Ee==="ml-tensor"&&fe>0){let Re=a.webnnEnsureTensor,ve=a.webnnIsGraphInputOutputTypeSupported;if(!Re||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Pc(oe,fe)===void 0||!eI(re))throw new Error(`Unsupported data type: ${re}`);if(!ve(n,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let Ne=await Re(n,L,oe,he,!1);X=!0,H.push([re,he,{mlTensor:Ne,download:a.webnnCreateMLTensorDownloader(L,re),dispose:()=>{a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K)}},"ml-tensor"])}else if(Ee==="ml-tensor-cpu-output"&&fe>0){let Re=a.webnnCreateMLTensorDownloader(L,re)(),ve=H.length;X=!0,B.push((async()=>{let Ne=[ve,await Re];return a.webnnReleaseTensorId(L),a._OrtReleaseTensor(K),Ne})()),H.push([re,he,[],"cpu"])}else{let Re=Z0(re),ve=new Re(fe);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(L,L+ve.byteLength)),H.push([re,he,ve,"cpu"])}}finally{a.stackRestore(Y),re==="string"&&L&&a._free(L),X||a._OrtReleaseTensor(K)}}p&&!A&&(a._OrtClearBoundOutputs(p.handle)!==0&&wn("Can't clear bound outputs."),Il.set(n,[c,d,h,p,A,!1]));for(let[W,K]of await Promise.all(B))H[W][2]=K;return qc("wasm ProcessOutputTensor"),H}finally{a.webnnOnRunEnd?.(c),a.stackRestore(M),b.forEach(Q=>a._OrtReleaseTensor(Q)),w.forEach(Q=>a._OrtReleaseTensor(Q)),C.forEach(Q=>a._free(Q)),g!==0&&a._OrtReleaseRunOptions(g),_.forEach(Q=>a._free(Q))}},xI=n=>{let e=kn(),t=Il.get(n);if(!t)throw new Error("invalid session id");let r=t[0],i=e._OrtEndProfiling(r);i===0&&wn("Can't get an profile file name."),e._OrtFree(i)},vI=n=>{let e=[];for(let t of n){let r=t[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Sl,ts,Ed,qf,Yf,rg,H_,ig,Ic,Sc,HR,z4,U4,O4,$4,G4,V4,H4,j4=et(()=>{xs(),F4(),cu(),XC(),Sl=()=>!!Dn.wasm.proxy&&typeof document<"u",Ed=!1,qf=!1,Yf=!1,ig=new Map,Ic=(n,e)=>{let t=ig.get(n);t?t.push(e):ig.set(n,[e])},Sc=()=>{if(Ed||!qf||Yf||!ts)throw new Error("worker not ready")},HR=n=>{switch(n.data.type){case"init-wasm":Ed=!1,n.data.err?(Yf=!0,H_[1](n.data.err)):(qf=!0,H_[0]()),rg&&(URL.revokeObjectURL(rg),rg=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=ig.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},z4=async()=>{if(!qf){if(Ed)throw new Error("multiple calls to 'initWasm()' detected.");if(Yf)throw new Error("previous call to 'initWasm()' failed.");if(Ed=!0,Sl())return new Promise((n,e)=>{ts?.terminate(),LP().then(([t,r])=>{try{ts=r,ts.onerror=s=>e(s),ts.onmessage=HR,H_=[n,e];let i={type:"init-wasm",in:Dn};!i.in.wasm.wasmPaths&&(t||Cw)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-C887KxcQ.wasm",import.meta.url).href}),ts.postMessage(i),rg=t}catch(i){e(i)}},e)});try{await JC(Dn.wasm),await pI(Dn),qf=!0}catch(n){throw Yf=!0,n}finally{Ed=!1}}},U4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("init-ep",[e,t]);let r={type:"init-ep",in:{epName:n,env:Dn}};ts.postMessage(r)});await AI(Dn,n)},O4=async n=>Sl()?(Sc(),new Promise((e,t)=>{Ic("copy-from",[e,t]);let r={type:"copy-from",in:{buffer:n}};ts.postMessage(r,[n.buffer])})):t0(n),$4=async(n,e)=>{if(Sl()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sc(),new Promise((t,r)=>{Ic("create",[t,r]);let i={type:"create",in:{model:n,options:{...e}}},s=[];n instanceof Uint8Array&&s.push(n.buffer),ts.postMessage(i,s)})}else return mI(n,e)},G4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("release",[e,t]);let r={type:"release",in:n};ts.postMessage(r)});gI(n)},V4=async(n,e,t,r,i,s)=>{if(Sl()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sc(),new Promise((a,o)=>{Ic("run",[a,o]);let l=t,c={type:"run",in:{sessionId:n,inputIndices:e,inputs:l,outputIndices:r,options:s}};ts.postMessage(c,vI(l))})}else return yI(n,e,t,r,i,s)},H4=async n=>{if(Sl())return Sc(),new Promise((e,t)=>{Ic("end-profiling",[e,t]);let r={type:"end-profiling",in:n};ts.postMessage(r)});xI(n)}}),j_,jR,W4,tne=et(()=>{xs(),j4(),Lt(),YC(),OP(),j_=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},jR=n=>{switch(n[3]){case"cpu":return new ti(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!ZC(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:r,dispose:i}=n[2];return ti.fromGpuBuffer(t,{dataType:e,dims:n[1],download:r,dispose:i})}case"ml-tensor":{let e=n[0];if(!eI(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:r,dispose:i}=n[2];return ti.fromMLTensor(t,{dataType:e,dims:n[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${n[3]}`)}},W4=class{async fetchModelAndCopyToWasmMemory(n){return O4(await tI(n))}async loadModel(n,e){Fa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await $4(t,e),Zs()}async dispose(){return G4(this.sessionId)}async run(n,e,t){Fa();let r=[],i=[];Object.entries(n).forEach(h=>{let p=h[0],A=h[1],y=this.inputNames.indexOf(p);if(y===-1)throw new Error(`invalid input '${p}'`);r.push(A),i.push(y)});let s=[],a=[];Object.entries(e).forEach(h=>{let p=h[0],A=h[1],y=this.outputNames.indexOf(p);if(y===-1)throw new Error(`invalid output '${p}'`);s.push(A),a.push(y)});let o=r.map((h,p)=>j_(h,()=>`input "${this.inputNames[i[p]]}"`)),l=s.map((h,p)=>h?j_(h,()=>`output "${this.outputNames[a[p]]}"`):null),c=await V4(this.sessionId,i,o,a,l,t),d={};for(let h=0;h<c.length;h++)d[this.outputNames[a[h]]]=s[h]??jR(c[h]);return Zs(),d}startProfiling(){}endProfiling(){H4(this.sessionId)}}}),q4={};vh(q4,{OnnxruntimeWebAssemblyBackend:()=>Uw,initializeFlags:()=>zw,wasmBackend:()=>Y4});var zw,Uw,Y4,nne=et(()=>{xs(),j4(),tne(),zw=()=>{(typeof Dn.wasm.initTimeout!="number"||Dn.wasm.initTimeout<0)&&(Dn.wasm.initTimeout=0);let n=Dn.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(Dn.wasm.simd=!1),typeof Dn.wasm.proxy!="boolean"&&(Dn.wasm.proxy=!1),typeof Dn.wasm.trace!="boolean"&&(Dn.wasm.trace=!1),typeof Dn.wasm.numThreads!="number"||!Number.isInteger(Dn.wasm.numThreads)||Dn.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Dn.wasm.numThreads=1;else{let e=typeof navigator>"u"?Uee("node:os").cpus().length:navigator.hardwareConcurrency;Dn.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Uw=class{async init(n){zw(),await z4(),await U4(n)}async createInferenceSessionHandler(n,e){let t=new W4;return await t.loadModel(n,e),t}},Y4=new Uw});xs();xs();xs();var rne="1.24.3";{let n=(nne(),Pp(q4)).wasmBackend;Bd("webgpu",n,5),Bd("webnn",n,5),Bd("cpu",n,10),Bd("wasm",n,10)}Object.defineProperty(Dn.versions,"web",{value:rne,enumerable:!0});class ine{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=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(const t of Object.values(this.obsGroups))for(const r of t)r.reset&&r.reset(e);if(e){for(const[t,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[t]??[],e),s=this.historyBuffers[t];for(let a=0;a<r.steps;a++)s.set(i,a*i.length)}}}update(e){this.policyModule?.update();for(const t of Object.values(this.obsGroups))for(const r of t)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const t={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const a=this.buildFrame(i,e),o=this.historyBuffers[r];for(let l=o.length-1;l>=a.length;l--)o[l]=o[l-a.length];o.set(a,0),t[r]=new Float32Array(o)}else t[r]=this.buildFrame(i,e)}return t}collectObservations(e){const t=this.collectObservationsByKey(e);if(this.defaultObsKey&&t[this.defaultObsKey])return t[this.defaultObsKey];const r=Object.keys(t)[0];return r?t[r]:new Float32Array(0)}getObservationSize(){if(this.defaultObsKey&&this.obsSizes[this.defaultObsKey]!==void 0)return this.obsSizes[this.defaultObsKey];const 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(t=>({...t}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(t=>({...t})):[]}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)}setLastActions(e){if(e.length!==this.lastActions.length){this.lastActions=new Float32Array(e);return}this.lastActions.set(e)}async buildPolicyModule(e){const t=this.options.policyModules??{},r=this.config.policy_module,i=r?t[r]:t.default;if(r&&!i)throw new Error(`Unknown policy module: ${r}`);if(!i)return null;const s=new i(this.config);return await s.init(e),s}buildObservationGroups(){const e=this.options.observations??{},t=this.config.observations??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(t)){if(Array.isArray(i)){const s=i.map(a=>{const o=e[a.name];if(!o)throw new Error(`Unknown observation type: ${a.name}`);return new o(this,a)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const a=s.components.map(c=>{const d=e[c.name];if(!d)throw new Error(`Unknown observation type: ${c.name}`);const h={...c,history_steps:1};return new d(this,h)}),o=Math.max(1,Math.floor(s.history_steps??1)),l=!!s.interleaved;this.registerGroup(r,a,s.components,{steps:o,interleaved:l})}}}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,r,i){this.obsGroups[e]=t,this.obsLayouts[e]=t.map((a,o)=>({name:r[o]?.name??`obs_${o}`,size:a.size}));const s=this.obsLayouts[e].reduce((a,o)=>a+o.size,0);i&&i.steps>1?(this.historyConfig[e]=i,this.historyBuffers[e]=new Float32Array(s*i.steps),this.obsSizes[e]=s*i.steps):this.obsSizes[e]=s}buildFrame(e,t){const r=e.reduce((a,o)=>a+o.size,0),i=new Float32Array(r);let s=0;for(const a of e){const o=a.compute(t),l=o instanceof Float32Array?o:Float32Array.from(o);if(l.length!==a.size)throw new Error(`Observation size mismatch: expected ${a.size}, got ${l.length}`);i.set(l,s),s+=l.length}return i}normalizeArray(e,t,r){const i=new Float32Array(t);for(let s=0;s<t;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}Dn.wasm.proxy=!1;Dn.wasm.numThreads=1;class sne{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const t=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.configuredInKeys=t.map(i=>Array.isArray(i)?i.join(","):i),this.inKeys=[...this.configuredInKeys],this.outKeys=r.map(i=>Array.isArray(i)?i.join(","):i),this.isRecurrent=this.inKeys.includes("adapt_hx")}async init(){const e=await fetch(this.config.path);if(!e.ok)throw new Error(`Failed to fetch ONNX model: ${e.status}`);const t=await e.arrayBuffer();this.session=await qC.create(t,{executionProviders:["wasm"],graphOptimizationLevel:"all"}),this.inferInputKeys(),this.isRecurrent=this.inKeys.includes("adapt_hx")}initInput(){const e={};return this.isRecurrent&&(e.is_init=new ti("bool",[!0],[1]),e.adapt_hx=new ti("float32",new Float32Array(128),[1,128])),this.inKeys.includes("time_step")&&(e.time_step=new ti("float32",new Float32Array([0]),[1,1])),e}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const t={};for(let a=0;a<this.inKeys.length;a++){const o=this.inKeys[a],l=this.session.inputNames[a];if(!l||!e[o])throw new Error(`Missing ONNX input for key: ${o}`);t[l]=e[o]}const r=await this.session.run(t),i={};for(let a=0;a<this.outKeys.length;a++){const o=this.outKeys[a],l=this.session.outputNames[a];l&&r[l]&&(i[o]=r[l])}const s={};return this.isRecurrent&&i["next,adapt_hx"]&&(s.is_init=new ti("bool",[!1],[1]),s.adapt_hx=i["next,adapt_hx"]),[i,s]}inferInputKeys(){if(!this.session)return;const 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(t=>this.configuredInKeys.includes(t)?t:t==="obs"&&this.configuredInKeys.includes("policy")?"policy":t)}}class ane{constructor(e,t,r,i){this.mujoco=e,this.mjModel=t,this.mjData=r;const s=this.getJointNames(t);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const a of i){const o=s.indexOf(a);if(o<0)throw new Error(`Joint "${a}" not found in MuJoCo model`);this.qposAdr.push(t.jnt_qposadr[o]),this.qvelAdr.push(t.jnt_dofadr[o]),this.jointIndices.push(o)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,t=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let c=0;c<this.numActions;c++)r[c]=e[this.qposAdr[c]],i[c]=t[this.qvelAdr[c]];const s=new Float32Array([e[0],e[1],e[2]]),a=new Float32Array([e[3],e[4],e[5],e[6]]),o=new Float32Array([t[0],t[1],t[2]]),l=new Float32Array([t[3],t[4],t[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:a,rootLinVel:o,rootAngVel:l}}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;const r=e.map(c=>new RegExp(`^(?:${c})$`)),i=c=>r.some(d=>d.test(c)),s=[],a=[],o=[],l=[];for(let c=0;c<t.length;c++)i(t[c])&&(s.push(this.ctrlAdr[c]),a.push(this.qposAdr[c]),o.push(this.qvelAdr[c]),l.push(c));return s.length===0?null:{ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l}}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,t=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?t.push(this.mjModel.actuator_trnid[2*i]):t.push(-1)}const r=[];for(const i of this.jointIndices){const s=t.findIndex(a=>a===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const t=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let a=e.name_jntadr[s],o=a;for(;o<t.length&&t[o]!==0;)o++;let l=r.decode(t.subarray(a,o));!l&&s===0&&(l="floating_base_joint"),i.push(l)}return i}}class X4{constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class one{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){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],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}}class lne extends X4{constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.tracking=new one(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class cne{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){const t=e?.jointPos??new Float32Array(this.nJoints),r=e?.rootPos??new Float32Array([0,0,0]),i=e?.rootQuat??new Float32Array([1,0,0,0]);this.refJointPos=[Float32Array.from(t)],this.refRootPos=[Float32Array.from(r)],this.refRootQuat=[Float32Array.from(i)],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}}class une extends X4{constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const t=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:t};this.locomotion=new cne(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class dne{constructor(e,t){this.terms=[];for(const r of e){const i=t[r.name];i&&this.terms.push(new i(r))}}onReset(e){for(const t of this.terms)t.onReset(e)}get size(){return this.terms.length}}class J4{constructor(e){this.config=e}}const hne={};class K4 extends J4{constructor(e){super(e),this.poseRange=e.params?.pose_range??{}}onReset(e){const{mjModel:t,mjData:r}=e;if(!t||!r)return;const i=this._findFreeJoint(t);if(i===-1)return;const s=t.jnt_qposadr[i],a=l=>{const c=this.poseRange[l];return c?c[0]+Math.random()*(c[1]-c[0]):0};r.qpos[s+0]+=a("x"),r.qpos[s+1]+=a("y"),r.qpos[s+2]+=a("z");const o=a("yaw");o!==0&&this._applyYawRotation(r.qpos,s+3,o)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}class fne extends J4{constructor(e){super(e),this.patchName=e.params?.patch_name??"spawn",this.fallback=new K4(e)}onReset(e){const{mjModel:t,mjData:r,terrainData:i}=e;if(!t||!r)return;const s=i?.flat_patches?.[this.patchName];if(!s||s.length===0){this.fallback.onReset(e);return}const a=this._findFreeJoint(t);if(a===-1)return;const o=t.jnt_qposadr[a],l=s[Math.floor(Math.random()*s.length)],c=r.qpos[o+2];r.qpos[o+0]=l[0],r.qpos[o+1]=l[1],r.qpos[o+2]=l[2]+c;const h=(this.config.params?.pose_range??{}).yaw??[-Math.PI,Math.PI],p=h[0]+Math.random()*(h[1]-h[0]);this._applyYawRotation(r.qpos,o+3,p)}_findFreeJoint(e){for(let t=0;t<e.njnt;t++)if(e.jnt_type[t]===0)return t;return-1}_applyYawRotation(e,t,r){const i=Math.cos(r/2),s=Math.sin(r/2),a=e[t+0],o=e[t+1],l=e[t+2],c=e[t+3];e[t+0]=i*a-s*c,e[t+1]=i*o+s*l,e[t+2]=i*l-s*o,e[t+3]=i*c+s*a}}const pne={ResetRootStateUniform:K4,ResetRootStateFromFlatPatches:fne},Ane={...pne,...hne};function sg(n){return typeof n=="object"&&n!==null&&typeof n.setSelectedMotion=="function"}class Z4 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 WR(n){const e=n instanceof Error?n.message:String(n);return e.includes("MjModel loading returned null")||e.includes("Could not allocate memory")||e.includes("memory allocation failed")||e.includes("bad_alloc")}class mne{constructor(e,t,r={}){this.render=()=>{if(Kn().updateDebugVisuals(),this.mjData&&$Z(this.mjData,this.camera,this.controls,this.cameraState),this.controls.update(),this.mjModel&&this.mjData&&this.bodies){F3(this.camera,this.lights);for(const[o,l]of this.lastSimState.bodies){const c=this.bodies[o];c&&(c.position.copy(l.position),c.quaternion.copy(l.quaternion))}L3(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&hX({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:o,height:l}=this.getSize();this.camera.aspect=o/l,this.camera.updateProjectionMatrix(),this.renderer.setSize(o,l)},this.mujoco=e,this.container=t,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(o){o&&typeof o=="object"&&"code"in o&&o.code!=="EEXIST"&&o.code}const{width:s,height:a}=this.getSize();this.scene=new s9,this.scene.name="scene",this.camera=new zr(45,s/a,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new z7({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,a),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=NN,this.renderer.outputColorSpace=ii,this.renderer.toneMapping=QN,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.vrButton=null,navigator.xr?.isSessionSupported("immersive-vr").then(o=>{o&&(this.vrButton=RC.createButton(this.renderer),document.body.appendChild(this.vrButton))}),this.controls=new O7(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:fX()},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.loadingScene=null,this.dragStateManager=null,this.dragForceScale=100,this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.policyDebugCounter=0,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=ww.getInstance(this.mujoco),this.resourceTracker=new GZ,this.memoryMonitor=new VZ}async loadEnvironment(e,t=null,r=null,i=null,s=null,a=null){this.terrainData=a,s&&s.length>0?this.eventManager=new dne(s,Ane):this.eventManager=null,await this.stop(),this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null);const o=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const l=performance.now()-o;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:l})}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 bX(this.mujoco,e,this.baseUrl),await this.loadSceneWithOomRetry(e),await this.captureAndCacheResources(e);r&&(this.splatMesh=tB(r,this.scene),r.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(r.colliderUrl),this.scene))),await this.loadPolicyConfig(t),this.applyViewerConfig(i),this.running=!0,this.startLoop()}initializeCommands(){const e=Kn();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e,t){Kn().initialize(e,t)}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}}async setSelectedMotion(e){const t=Kn().getTerm("motion");if(!sg(t))return!1;const r=await t.setSelectedMotion(e);return r&&this.resetSimulation(),r}getSelectedMotionName(){const e=Kn().getTerm("motion");return sg(e)?e.getSelectedMotionName?.()??null:null}setReferenceVisible(e){const t=Kn().getTerm("motion");!sg(t)||typeof t.setReferenceVisible!="function"||t.setReferenceVisible(e)}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const t=this.scene.getObjectByName("MuJoCo Root");t&&this.scene.remove(t);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await vX(this.mujoco,e,r),!this.mjModel||!this.mjData)throw new Error("Failed to load MuJoCo model.");this.mujocoRoot=this.scene.getObjectByName("MuJoCo Root"),this.mujoco.mj_forward(this.mjModel,this.mjData),L3(this.mujoco,this.mjData,this.lights),F3(this.camera,this.lights),this.dynamicBodyIds=this.computeDynamicBodyIds(this.mjModel),this.syncStaticBodiesFromData(),this.timestep=this.mjModel.opt.timestep||.001,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({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(!WR(t))throw t;this.loadingScene=null,await this.sceneCacheManager.clear();try{await this.loadScene(e)}catch(r){throw this.loadingScene=null,WR(r)?new Z4:r}}}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async setSplat(e){this.splatMesh&&(nB(this.splatMesh,this.scene),this.splatMesh=null),this.colliderMesh&&(cB(this.colliderMesh,this.scene),this.colliderMesh=null),e&&(this.splatMesh=tB(e,this.scene),e.colliderUrl&&(this.colliderMesh=await lB(this.resolveAssetUrl(e.colliderUrl),this.scene)))}calibrateSplat(e){this.splatMesh&&aP(this.splatMesh,e)}setSplatVisible(e){this.splatMesh&&(this.splatMesh.visible=e)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const 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){const s=this.policyStateBuilder.build(),a=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(a),this.policyDebugCounter%60===0){const o="policy"in a?"policy":"observation"in a?"observation":Object.keys(a)[0],l=o?a[o]:null;l&&Array.from(l.slice(0,8))}this.policyDebugCounter+=1}if(this.executeSimulationSteps(),this.updateCachedState(),this.terminationManager&&this.policyStateBuilder){const s=this.policyStateBuilder.build();if(this.terminationManager.evaluate(s).done&&(this.resetSimulationState(),this.terminationManager.reset(),this.policyRunner)){const o=this.policyStateBuilder.build();this.policyRunner.reset(o)}}Kn().update(t),Kn().updateDebugVisuals()}const r=(performance.now()-e)/1e3,i=Math.max(0,t-r);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const t=this.policyConfigPath;this.policyConfigPath=e,this.policyRunner=null,this.policyStateBuilder=null,this.policyDebugCounter=0,this.policyControl=null,this.onnxModule=null,this.onnxInputDict=null,this.onnxInferencing=!1,this.onnxTimeStep=0,this.terminationManager=null;const r=Kn();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e&&!(!this.mjModel||!this.mjData)){e!==t&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(Array.isArray(i.motions)&&(i.motions=i.motions.map(o=>({...o,path:this.resolveAssetUrl(this.resolvePolicyAssetPath(e,o.path))}))),i.commands?.motion&&Array.isArray(i.motions)&&(i.commands.motion={...i.commands.motion,motions:i.motions}),this.resetSimulationState(),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState(),i.commands&&typeof i.commands=="object"){this.initializeCommandsFromConfig(i.commands,{mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene,bodies:this.bodies,mujocoRoot:this.mujocoRoot,requestReset:()=>this.resetSimulation()}),Kn().resetTerms();const o=Kn().getTerm("motion");sg(o)&&(await o.setSelectedMotion(i.motions?.find(l=>l.default)?.name??i.motions?.[0]?.name??null),o.setReferenceVisible?.(!0)),this.mujoco.mj_forward(this.mjModel,this.mjData),this.updateCachedState()}if(!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new ine(i,{policyModules:{tracking:lne,locomotion:une},observations:Mee});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData,scene:this.scene}),this.policyRunner=s,this.policyStateBuilder=new ane(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const a=this.policyStateBuilder.build();if(this.policyRunner.reset(a),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.terminations&&Object.keys(i.terminations).length>0&&(this.terminationManager=new Tee(i.terminations,Pee)),i.onnx?.path){const o=this.resolvePolicyAssetPath(e,i.onnx.path),l=this.resolveAssetUrl(o),c={...i.onnx,path:l},d=new sne(c);await d.init(),this.onnxModule=d,this.onnxInputDict=d.initInput()}}catch{}}}async fetchPolicyConfig(e){const t=this.resolveAssetUrl(e),r=await fetch(t,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:t}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const t=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(t,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,t){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${t}`.replace(/\/+/g,"/"):t}buildPolicyControl(e,t,r){const i=t.getPolicyJointNames(),s=this.mujoco.mjtBias?.mjBIAS_AFFINE?.value??1,a=(c,d,h,p,A,y,m,x)=>{const g=h.qposAdr.length,_=h.actionIndices.map(Q=>i[Q]),b=this.normalizeControlArray(p,g,1,_),w=this.normalizeControlArray(A,g,0,_),C=x?t.getDefaultJointPos():new Float32Array(i.length),S=new Float32Array(g);for(let Q=0;Q<g;Q++)S[Q]=C[h.actionIndices[Q]];const M=Array.isArray(e.encoder_bias)?Float32Array.from(e.encoder_bias):new Float32Array(i.length),T=new Float32Array(g);for(let Q=0;Q<g;Q++)T[Q]=M[h.actionIndices[Q]]??0;const R=this.normalizeControlArray(y,g,0,_),k=this.normalizeControlArray(m,g,0,_),$=h.ctrlAdr.map(Q=>Q<0||!this.mjModel?!1:this.mjModel.actuator_biastype[Q]===s);return $.some(Boolean),$.some(Q=>!Q),{controlType:d,ctrlAdr:h.ctrlAdr,qposAdr:h.qposAdr,qvelAdr:h.qvelAdr,actionIndices:h.actionIndices,actionScale:b,actionOffset:w,defaultJointPos:S,encoderBias:T,positionActuator:$,kp:R,kd:k}},o=e.actions;if(!o||Object.keys(o).length===0){const c=e.control_type??"joint_position";if(c!=="joint_position"&&c!=="torque")return null;const d=r.getControlMapping();if(!d)return null;const h={...d,actionIndices:Array.from({length:d.qposAdr.length},(p,A)=>A)};return[a("legacy",c,h,e.action_scale,void 0,e.stiffness,e.damping,!0)]}const l=[];for(const[c,d]of Object.entries(o)){const h=d.type??"joint_position";if(h!=="joint_position"&&h!=="torque")continue;const p=d.actuator_names??[".*"],A=p.length===1&&p[0]===".*";let y;if(A){const x=r.getControlMapping();if(!x)continue;y={...x,actionIndices:Array.from({length:x.qposAdr.length},(g,_)=>_)}}else if(y=r.getControlMappingFor(p,i),!y)continue;const m=d.use_default_offset!==void 0?d.use_default_offset:h==="joint_position";l.push(a(c,h,y,d.scale,d.offset,d.stiffness,d.damping,m))}return l.length===0?null:l}normalizeControlArray(e,t,r,i){const s=new Float32Array(t);if(s.fill(r),typeof e=="number")return s.fill(e),s;if(Array.isArray(e)){for(let a=0;a<t;a++)s[a]=typeof e[a]=="number"?e[a]:r;return s}if(e!==null&&typeof e=="object"&&i){for(const[a,o]of Object.entries(e)){const l=i.indexOf(a);l>=0&&l<t&&(s[l]=o)}return s}return s}resetSimulationState(){!this.mjModel||!this.mjData||(this.mjModel.nkey>0?this.mujoco.mj_resetDataKeyframe(this.mjModel,this.mjData,0):this.mujoco.mj_resetData(this.mjModel,this.mjData),this.eventManager&&this.eventManager.onReset({mjModel:this.mjModel,mjData:this.mjData,terrainData:this.terrainData}),Kn().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;const e=this.mjData.ctrl;e.fill(0);const t=this.policyRunner?.getLastActions()??new Float32Array(0);for(const r of this.policyControl){const{controlType:i,ctrlAdr:s,qposAdr:a,qvelAdr:o,actionIndices:l,actionScale:c,actionOffset:d,defaultJointPos:h,encoderBias:p,positionActuator:A,kp:y,kd:m}=r,x=s.length;if(i==="joint_position")for(let g=0;g<x;g++){const _=s[g];if(_<0)continue;const b=t[l[g]]??0,w=h[g]+d[g]+c[g]*b-p[g];if(A[g])e[_]=w;else{const C=this.mjData.qpos[a[g]],S=this.mjData.qvel[o[g]];e[_]=y[g]*(w-C)+m[g]*(0-S)}}else if(i==="torque")for(let g=0;g<x;g++){const _=s[g];_>=0&&(e[_]=c[g]*(t[l[g]]??0))}}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const t={...this.onnxInputDict};this.onnxModule.inKeys.includes("time_step")&&(t.time_step=new ti("float32",new Float32Array([this.onnxTimeStep]),[1,1]));for(const[d,h]of Object.entries(e))t[d]=new ti("float32",h,[1,h.length]);for(const d of this.onnxModule.inKeys)if(!t[d])return;const[r,i]=await this.onnxModule.runInference(t);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i}),this.onnxModule.inKeys.includes("time_step")&&(this.onnxTimeStep+=1);const s=this.onnxModule.outKeys[0],a=r.action??(s?r[s]:null)??r.policy??null;if(!a)return;const o=a.data,l=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o),c=this.policyRunner?.getNumActions()??0;if(this.policyControl&&l.length!==c)return;this.policyRunner.setLastActions(l)}catch{}finally{this.onnxInferencing=!1}}}applyDragForces(){if(!this.dragStateManager||!this.mjModel||!this.mjData||!this.bodies)return;for(let p=0;p<this.mjData.xfrc_applied.length;p++)this.mjData.xfrc_applied[p]=0;const e=this.dragStateManager.physicsObject;if(!e||!("bodyID"in e)||typeof e.bodyID!="number"||e.bodyID<=0)return;const t=e.bodyID;if(this.dynamicBodyIds&&!this.dynamicBodyIds.has(t))return;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(jc(this.mjData.xpos,p,this.bodies[p].position),pp(this.mjData.xquat,p,this.bodies[p].quaternion),this.bodies[p].updateWorldMatrix(!0,!1));this.dragStateManager.update();const r=this.dragStateManager.offset.clone().multiplyScalar(this.dragForceScale),i=P3(r),s=this.dragStateManager.worldHit.clone(),a=P3(s),o=new ue(this.mjData.xpos[t*3+0],this.mjData.xpos[t*3+1],this.mjData.xpos[t*3+2]),l=new ue(a.x-o.x,a.y-o.y,a.z-o.z),c=new ue(i.x,i.y,i.z),d=new ue().crossVectors(l,c),h=t*6;this.mjData.xfrc_applied[h+0]=i.x,this.mjData.xfrc_applied[h+1]=i.y,this.mjData.xfrc_applied[h+2]=i.z,this.mjData.xfrc_applied[h+3]=d.x,this.mjData.xfrc_applied[h+4]=d.y,this.mjData.xfrc_applied[h+5]=d.z}updateCachedState(){if(!this.mjModel||!this.mjData||!this.bodies)return;const 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 ue,quaternion:new Cn});const r=this.lastSimState.bodies.get(t);jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&dX(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}applyViewerConfig(e){this.cameraState=OZ(e,this.camera,this.controls,this.mjModel,this.mjData)}computeDynamicBodyIds(e){const t=new Set;for(let r=1;r<e.nbody;r++){let i=r;for(;i>0;){if(e.body_jntnum[i]>0){t.add(r);break}i=e.body_parentid[i]}}return t}syncStaticBodiesFromData(){if(!this.mjModel||!this.mjData||!this.bodies)return;const e=this.dynamicBodyIds;for(let t=0;t<this.mjModel.nbody;t++){if(e?.has(t))continue;const r=this.bodies[t];r&&(jc(this.mjData.xpos,t,r.position),pp(this.mjData.xquat,t,r.quaternion))}}dispose(){this.stop(),this.policyRunner=null,this.policyStateBuilder=null,this.policyConfigPath=null,this.dragStateManager&&(this.dragStateManager.dispose(),this.dragStateManager=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(t=>this.disposeMaterial(t)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const 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(){const 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){const t=this.sceneCacheManager.get(e);if(!t)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),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,this.decimation=Math.max(1,Math.round(.02/this.timestep)),this.lastSimState.bodies.clear(),this.updateCachedState(),this.dragStateManager?this.dragStateManager.setDraggableBodyIds(this.dynamicBodyIds):this.dragStateManager=new uB({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls,draggableBodyIds:this.dynamicBodyIds})}async captureAndCacheResources(e){const t=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot)return;const r=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 ph?this.scene.background:null,fsFiles:t,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const ag="mjswan_oom_reload_scene",gne=({scenePath:n,baseUrl:e,policyConfigPath:t,splatConfig:r,cameraConfig:i,eventsConfig:s,terrainData:a,selectedMotion:o,showReferenceMotion:l=!0,onStatusChange:c,onError:d,onReady:h,onRuntimeReady:p})=>{const A=U.useRef(null),y=U.useRef(null),m=U.useRef(null),x=U.useRef(r);x.current=r;const g=U.useRef(o);g.current=o;const _=U.useRef(l);return _.current=l,U.useEffect(()=>{let b=!1;const w=S=>{c?.(S)};return(async()=>{if(w("Loading MuJoCo..."),!m.current){const T=await RV(()=>import("./mujoco-Cp1xcNpc.js"),[]);m.current=await T.default()}if(b)return;const S=A.current;if(!S)throw new Error("Failed to find viewer container.");const M=m.current;if(!M)throw new Error("MuJoCo not loaded.");y.current||(y.current=new mne(M,S,{baseUrl:e}),p?.(y.current)),w("Loading scene assets..."),await y.current.loadEnvironment(n,t??null,x.current??null,i??null,s??null,a??null),await y.current.setSelectedMotion(g.current??null),y.current.setReferenceVisible(_.current),!b&&(sessionStorage.removeItem(ag),w("Running simulation"),h?.())})().catch(S=>{if(!b){if(S instanceof Z4){if(sessionStorage.getItem(ag)!==n){sessionStorage.setItem(ag,n),window.location.reload();return}sessionStorage.removeItem(ag)}d?.(S instanceof Error?S:new Error(String(S))),w("Failed to load scene")}}),()=>{b=!0,y.current?.dispose(),y.current=null}},[n,e,t,i,s,a,c,d,h]),U.useEffect(()=>{y.current&&y.current.setSelectedMotion(o??null)},[o]),U.useEffect(()=>{y.current?.setReferenceVisible(l)},[l]),j.jsx("div",{ref:A,className:"viewer"})};var yne={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"}};const ey=(n,e,t,r)=>{const i=U.forwardRef(({color:s="currentColor",size:a=24,stroke:o=2,title:l,className:c,children:d,...h},p)=>U.createElement("svg",{ref:p,...yne[n],width:a,height:a,className:["tabler-icon",`tabler-icon-${e}`,c].join(" "),strokeWidth:o,stroke:s,...h},[l&&U.createElement("title",{key:"svg-title"},l),...r.map(([A,y])=>U.createElement(A,y)),...Array.isArray(d)?d:[d]]));return i.displayName=`${t}`,i};const xne=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],ez=ey("outline","chevron-down","ChevronDown",xne);const vne=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],_ne=ey("outline","chevron-up","ChevronUp",vne);const bne=[["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"}]],wne=ey("outline","refresh","Refresh",bne);const Ene=[["path",{d:"M18 6l-12 12",key:"svg-0"}],["path",{d:"M6 6l12 12",key:"svg-1"}]],Cne=ey("outline","x","X",Ene),qR="0.5.5",YR=[{login:"ttktjmt",html_url:"https://github.com/ttktjmt"},{login:"claude",html_url:"https://github.com/claude"},{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:"Axellwppr",html_url:"https://github.com/Axellwppr"},{login:"CharlieLeee",html_url:"https://github.com/CharlieLeee"}],Ine={move:"touchmove",end:"touchend"},Sne={move:"mousemove",end:"mouseup"};function Bne(n){return n.type==="touchmove"}function Mne(n){return n.type==="mousemove"}const jp=On.createContext(null);function Ao({children:n,width:e,visible:t=!0,onVisibleChange:r,hiddenButtonTooltip:i}){const s=On.useRef(null),[a,{toggle:o}]=s0(!0),[l,c]=On.useState(800),d=On.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),h=On.useRef({}),p=(x,g,_)=>Math.abs(x+g/2)<Math.abs(x-_+g/2)?x:x-_,A=15;function y(x,g){const _=s.current;if(_===null)return[x,g];const b=_.parentElement;if(b===null)return[x,g];let w=x,C=g;return w=Math.min(w,b.clientWidth-_.clientWidth-A),w=Math.max(w,A),C=Math.min(C,b.clientHeight-_.clientHeight-A),C=Math.max(C,A),_.style.top=`${C.toString()}px`,_.style.left=`${w.toString()}px`,[p(w,_.clientWidth,b.clientWidth),p(C,_.clientHeight,b.clientHeight)]}On.useEffect(()=>{const x=s.current;if(x===null)return;const g=x.parentElement;if(g===null)return;const _=new ResizeObserver(()=>{h.current.x===void 0&&(h.current.x=p(x.offsetLeft,x.clientWidth,g.clientWidth)),h.current.y===void 0&&(h.current.y=p(x.offsetTop,x.clientHeight,g.clientHeight));const b=g.clientHeight-A*2;l!==b&&c(b);let w=h.current.x,C=h.current.y;for(;w<0;)w+=g.clientWidth;for(;C<0;)C+=g.clientHeight;y(w,C)});return _.observe(x),_.observe(g),()=>{_.disconnect()}});const m=x=>{const g=d.current,_=s.current;if(!_)return;x.type=="touchstart"?(x=x,g.startClientX=x.touches[0].clientX,g.startClientY=x.touches[0].clientY):(x=x,g.startClientX=x.clientX,g.startClientY=x.clientY),g.startPosX=_.offsetLeft,g.startPosY=_.offsetTop;const b=x.type=="touchstart"?Ine:Sne;function w(C){let S=0,M=0;if(Bne(C)?(C=C,S=C.touches[0].clientX-g.startClientX,M=C.touches[0].clientY-g.startClientY):Mne(C)&&(C=C,S=C.clientX-g.startClientX,M=C.clientY-g.startClientY),Math.abs(S)<=3&&Math.abs(M)<=3)return;g.dragging=!0;const T=g.startPosX+S,R=g.startPosY+M;[h.current.x,h.current.y]=y(T,R)}window.addEventListener(b.move,w),window.addEventListener(b.end,()=>{x.type=="touchstart"&&(g.dragging=!1),window.removeEventListener(b.move,w)},{once:!0})};if(!t){const x=j.jsx(Je,{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 j.jsx(Je,{style:{zIndex:10,position:"absolute",top:"1em",right:"1em"},children:i?j.jsx(Pl,{label:i,children:j.jsx(Je,{children:x})}):x})}return j.jsx(jp.Provider,{value:{wrapperRef:s,expanded:a,width:e,maxHeight:l,toggleExpanded:o,dragHandler:m,dragInfo:d},children:j.jsx(Xc,{radius:"xs",shadow:"0.1em 0 1em 0 rgba(0,0,0,0.1)",style:{boxSizing:"border-box",width:e,zIndex:10,position:"absolute",top:"1em",right:"1em",margin:0,"& .expandIcon":{transform:"rotate(0)"},overflow:"hidden"},ref:s,children:n})})}Ao.Handle=function({children:e}){const t=On.useContext(jp);return j.jsx(j.Fragment,{children:j.jsx(Je,{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:()=>{const r=t.dragInfo.current;if(r.dragging){r.dragging=!1;return}t.toggleExpanded()},onTouchStart:r=>{t.dragHandler(r)},onMouseDown:r=>{t.dragHandler(r)},children:e})})};Ao.Contents=function({children:e}){const t=On.useContext(jp);return j.jsxs(Mg,{in:t.expanded,children:[j.jsx(Dd,{mx:"xs"}),j.jsx(su.Autosize,{mah:t.maxHeight,children:j.jsx(Je,{style:{width:t.width},children:e})})]})};Ao.HideWhenCollapsed=function({children:e}){return On.useContext(jp)?.expanded??!0?e:null};Ao.HideWhenExpanded=function({children:e}){return On.useContext(jp)?.expanded??!0?null:e};function og({id:n,label:e,children:t}){return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsxs(EE,{align:"center",children:[j.jsx(Je,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:j.jsx("label",{htmlFor:n,children:e})})}),j.jsx(Je,{style:{flexGrow:1},children:t})]})})}function tz({label:n,expandByDefault:e=!0,children:t}){const[r,{toggle:i}]=s0(e),s=r?_ne:ez;return j.jsxs(Xc,{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:[j.jsxs(Xc,{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:[n,j.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),j.jsx(Mg,{in:r,children:j.jsx(Je,{pt:"1em",children:t})}),j.jsx(Mg,{in:!r,children:j.jsx(Je,{p:"xs"})})]})}const nz={fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"4.5em",flexShrink:0},Tne={root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}},Rne={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 W_({axis:n,value:e,min:t=-1/0,max:r=1/0,step:i,onChange:s}){const a=U.useRef(null),o=U.useRef(null);U.useEffect(()=>{const y=a.current;y&&document.activeElement!==y&&(y.value=e.toFixed(2))},[e]);const l=y=>Math.max(t,Math.min(r,parseFloat((Math.round(y/i)*i).toFixed(10)))),c=y=>{y.preventDefault(),y.currentTarget.setPointerCapture(y.pointerId),o.current={startY:y.clientY,startValue:e,moved:!1}},d=y=>{if(!o.current||!(y.buttons&1))return;const m=o.current.startY-y.clientY;if(Math.abs(m)>3&&(o.current.moved=!0),!o.current.moved)return;const x=l(o.current.startValue+m*i);s(x),a.current&&(a.current.value=x.toFixed(2))},h=()=>{if(o.current&&!o.current.moved){const y=a.current;y&&(y.focus(),y.select())}o.current=null},p=y=>{const m=parseFloat(y.target.value);isNaN(m)||s(l(m)),y.target.value=e.toFixed(2)},A=y=>{y.key==="Enter"&&y.currentTarget.blur(),y.key==="Escape"&&(a.current&&(a.current.value=e.toFixed(2)),a.current?.blur())};return j.jsxs(Je,{style:{display:"flex",alignItems:"center",gap:"0.25em",flex:1},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,letterSpacing:"-0.75px",flexShrink:0},children:n}),j.jsx("input",{ref:a,size:1,defaultValue:e.toFixed(2),onPointerDown:c,onPointerMove:d,onPointerUp:h,onBlur:p,onKeyDown:A,onFocus:y=>y.currentTarget.style.outline="2px solid var(--mantine-color-blue-5)",onBlurCapture:y=>y.currentTarget.style.outline="none",style:Rne})]})}function XR({label:n,x:e,y:t,z:r,step:i,xLabel:s="X",yLabel:a="Y",zLabel:o="Z",onX:l,onY:c,onZ:d}){return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:n}),j.jsx(W_,{axis:s,value:e,step:i,onChange:l}),j.jsx(W_,{axis:a,value:t,step:i,onChange:c}),j.jsx(W_,{axis:o,value:r,step:i,onChange:d})]})}function Dne({scale:n,xOffset:e,yOffset:t,zOffset:r,roll:i,pitch:s,yaw:a,onCalibrate:o}){const[l,c]=U.useState(n),[d,h]=U.useState(e),[p,A]=U.useState(t),[y,m]=U.useState(r),[x,g]=U.useState(i),[_,b]=U.useState(s),[w,C]=U.useState(a);U.useEffect(()=>{c(n)},[n]),U.useEffect(()=>{h(e)},[e]),U.useEffect(()=>{A(t)},[t]),U.useEffect(()=>{m(r)},[r]),U.useEffect(()=>{g(i)},[i]),U.useEffect(()=>{b(s)},[s]),U.useEffect(()=>{C(a)},[a]);const S=(M,T,R,k,$,Q,H)=>o(M,T,R,k,$,Q,H);return j.jsxs(tz,{label:"Control",expandByDefault:!0,children:[j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center",gap:"0.5em"},children:[j.jsx(Xs,{c:"dimmed",style:nz,children:"Scale"}),j.jsx(Je,{style:{flex:1},children:j.jsx(P0,{value:l,onChange:M=>{c(M),S(M,d,p,y,x,_,w)},min:.1,max:5,step:.05,size:"xs",label:M=>M.toFixed(2),styles:Tne})})]}),j.jsx(XR,{label:"Position",x:d,y:p,z:y,step:.05,onX:M=>{h(M),S(l,M,p,y,x,_,w)},onY:M=>{A(M),S(l,d,M,y,x,_,w)},onZ:M=>{m(M),S(l,d,p,M,x,_,w)}}),j.jsx(XR,{label:"Rotation",x,y:_,z:w,step:.5,xLabel:"R",yLabel:"P",zLabel:"Y",onX:M=>{g(M),S(l,d,p,y,M,_,w)},onY:M=>{b(M),S(l,d,p,y,x,M,w)},onZ:M=>{C(M),S(l,d,p,y,x,_,M)}})]})}function kne(n){return n instanceof HTMLElement?n.isContentEditable?!0:n.closest('input, textarea, select, [contenteditable], [role="textbox"], [role="searchbox"], [role="combobox"]')!==null:!1}function Nne(n){return n.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Qne({command:n,value:e,onChange:t,disabled:r,enabledWhenValue:i}){const s=n.config,a=s.enabled_when!==void 0&&(i??0)<.5,o=r||a;return j.jsxs(Je,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[j.jsx(Xs,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:s.label}),j.jsx(Je,{style:{width:"50%"},children:j.jsx(P0,{value:e,onChange:l=>t(n.id,l),min:s.min,max:s.max,step:s.step,size:"xs",disabled:o,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function Pne({command:n,value:e,onChange:t,disabled:r}){const i=n.config;return j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:i.label,checked:e>=.5,onChange:s=>t(n.id,s.currentTarget.checked?1:0),size:"xs",disabled:r})})}function Lne(n){const{visible:e,onVisibleChange:t,projects:r,projectValue:i,projectLabel:s,onProjectChange:a,scenes:o,sceneValue:l,onSceneChange:c,splats:d,splatSection:h=!1,splatValue:p,onSplatChange:A,splatConfig:y,onCalibrateSplat:m,onSplatUrlLoad:x,policies:g,policyValue:_,onPolicyChange:b,motions:w,motionValue:C,onMotionChange:S,showReferenceMotion:M,onShowReferenceMotionChange:T,commandsEnabled:R=!1,onReset:k}=n,[$,{open:Q,close:H}]=s0(!1),[B,W]=U.useState(""),[K,Y]=U.useState(null),[G,X]=U.useState(!1),re=U.useCallback(async ve=>{if(ve.key!=="Enter"||!x)return;const Ne=B.trim();if(d.some(Ge=>Ge.label===Ne||Ge.value===Ne))return;if(!Ne.toLowerCase().endsWith(".spz")){Y("URL must end with .spz");return}await x(Ne)?(Y(null),X(!0)):Y("File not found at the specified URL")},[x,B,d]),[L,V]=U.useState([]),[oe,Ae]=U.useState([]),[ye,he]=U.useState({});U.useEffect(()=>{const ve=Kn(),Ne=()=>{V(ve.getCommands()),Ae(ve.getCommandGroups()),he(ve.getValues())};return Ne(),ve.addEventListener(Ne),()=>{ve.removeEventListener(Ne)}},[]),U.useEffect(()=>{const ve=Ne=>{if(Ne.defaultPrevented||Ne.repeat||Ne.altKey||Ne.ctrlKey||Ne.metaKey||Ne.key.toLowerCase()!=="c")return;const rt=Ne.target instanceof Element?Ne.target:document.activeElement;kne(rt)||(Ne.preventDefault(),t(!e))};return window.addEventListener("keydown",ve),()=>{window.removeEventListener("keydown",ve)}},[e,t]);const fe=U.useCallback((ve,Ne)=>{Kn().setValue(ve,Ne),he(Ge=>({...Ge,[ve]:Ne}))},[]),Ee=U.useCallback(()=>{Kn().triggerButton("_system:reset"),k&&k()},[k]),Re=ve=>L.filter(Ne=>Ne.groupName===ve&&(Ne.config.type==="slider"||Ne.config.type==="checkbox"));return!r.length&&!o.length&&!g.length?null:j.jsxs(j.Fragment,{children:[j.jsx(aa,{opened:$,onClose:H,size:"lg",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:j.jsxs(sC,{gap:"md",align:"center",children:[j.jsx(Pg,{src:"./logo-color.svg",style:{width:"8em",height:"auto"}}),j.jsx(Xs,{size:"xl",fw:700,children:"powered by mjswan"}),j.jsxs(Xs,{size:"sm",c:"dimmed",children:["version ",qR]}),j.jsx(Xs,{size:"sm",c:"dimmed",children:"MuJoco Simulation on Web Assembly with Neural netwroks"}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{children:[j.jsx(up,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",j.jsx(up,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]}),j.jsx(Dd,{w:"100%"}),j.jsxs(Je,{style:{textAlign:"left",maxHeight:"120px",overflowY:"auto",lineHeight:"1",fontSize:"0.8rem",opacity:"0.75"},px:"md",children:["Thanks to our contributors! ",j.jsx("br",{}),YR.map((ve,Ne)=>j.jsxs("span",{children:[j.jsx(up,{href:ve.html_url,target:"_blank",style:{textDecoration:"none",fontSize:"0.75rem"},children:ve.login}),Ne<YR.length-1&&", "]},ve.login))]})]})}),j.jsxs(Ao,{width:"20em",visible:e,onVisibleChange:t,hiddenButtonTooltip:"Show controls (C)",children:[j.jsxs(Ao.Handle,{children:[j.jsx(Pl,{label:`mjswan ${qR}`,children:j.jsx(Je,{component:"a",onClick:ve=>{ve.stopPropagation(),Q()},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{position:"absolute",cursor:"pointer",display:"flex",top:"0.8em",left:"0.9em"},children:j.jsx(Pg,{src:"./logo.svg",style:{width:"1.2em",height:"auto"}})})}),j.jsx("div",{style:{width:"1.1em"}}),j.jsx(Ao.HideWhenCollapsed,{children:j.jsxs(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[j.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s}),r.length>1&&j.jsxs(pi,{position:"bottom-start",offset:5,children:[j.jsx(pi.Target,{children:j.jsx(Je,{onClick:ve=>ve.stopPropagation(),onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center",flexShrink:0},children:j.jsx(ez,{size:16})})}),j.jsx(pi.Dropdown,{onClick:ve=>ve.stopPropagation(),children:r.map(ve=>j.jsx(pi.Item,{onClick:Ne=>{Ne.stopPropagation(),a(ve.value)},style:{fontWeight:ve.value===i?600:400,backgroundColor:ve.value===i?"rgba(34, 139, 230, 0.1)":void 0},children:ve.label},ve.value))})]})]})}),j.jsx(Ao.HideWhenExpanded,{children:j.jsx(Je,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:s})}),j.jsx(Pl,{label:"Hide controls (C)",children:j.jsx(au,{variant:"subtle",color:"gray",size:"sm","aria-label":"Hide controls",onClick:ve=>{ve.stopPropagation(),t(!1)},onMouseDown:ve=>ve.stopPropagation(),onTouchStart:ve=>ve.stopPropagation(),children:j.jsx(Cne,{size:14})})})]}),j.jsx(Ao.Contents,{children:j.jsxs(Je,{pt:"0.375em",children:[o.length>0&&j.jsx(og,{id:"scene-select",label:"Scene",children:j.jsx(zc,{id:"scene-select",placeholder:"Select scene",data:o,value:l,onChange:c,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),(d.length>0||h)&&j.jsx(og,{id:"splat-select",label:"Splat",children:j.jsx(Pl,{label:K??"",color:"red",position:"bottom",opened:K!==null,withArrow:!0,children:j.jsx(zc,{id:"splat-select",placeholder:x!==void 0?"Select splat or paste .spz URL":"Select splat",data:d,value:p,onChange:ve=>{A(ve),Y(null),X(!1)},searchable:x!==void 0,searchValue:B,onSearchChange:ve=>{W(ve),ve&&Y(null)},onKeyDown:re,size:"xs",radius:"xs",clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})})}),(y?.control&&p!==null||G)&&m&&j.jsx(Dne,{scale:y?.scale??1,xOffset:y?.xOffset??0,yOffset:y?.yOffset??0,zOffset:y?.zOffset??0,roll:y?.roll??0,pitch:y?.pitch??0,yaw:y?.yaw??0,onCalibrate:m}),g.length>0&&j.jsx(og,{id:"policy-select",label:"Policy",children:j.jsx(zc,{id:"policy-select",placeholder:"Select policy",data:g,value:_,onChange:b,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),w.length>0&&j.jsxs(j.Fragment,{children:[j.jsx(og,{id:"motion-select",label:"Motion",children:j.jsx(zc,{id:"motion-select",placeholder:"Select motion",data:w,value:C,onChange:S,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),j.jsx(Je,{pb:"0.5em",px:"xs",children:j.jsx(Gl,{label:"Show reference",checked:M,onChange:ve=>T(ve.currentTarget.checked),size:"xs"})})]}),oe.length>0&&L.some(ve=>ve.config.type==="slider"||ve.config.type==="checkbox")&&j.jsx(j.Fragment,{children:oe.map(ve=>{const Ne=Re(ve);return Ne.length===0?null:j.jsx(tz,{label:Nne(ve),expandByDefault:!0,children:Ne.map(rt=>rt.config.type==="checkbox"?j.jsx(Pne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R},rt.id):rt.config.type!=="slider"?null:j.jsx(Qne,{command:rt,value:ye[rt.id]??0,onChange:fe,disabled:!R,enabledWhenValue:rt.config.enabled_when?ye[Ew(rt.groupName,rt.config.enabled_when)]:void 0},rt.id))},ve)})}),j.jsx(Dd,{mb:"xs",mx:"xs"}),j.jsx(Je,{px:"xs",pb:"xs",children:j.jsx(lh,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:j.jsx(wne,{size:14}),onClick:Ee,children:"Reset"})})]})})]})]})}function Xf(n,e,t){return Object.keys(n[e]).reduce((r,i)=>(r[i]=`var(--mantine-${t}-${i})`,r),{})}function JR(n,e){return n in e.breakpoints?e.breakpoints[n]:X_(n)}function Fne(n){const e=bD(c0,n),t=Xf(e,"fontSizes","font-size"),r=Xf(e,"lineHeights","line-height"),i=Xf(e,"shadows","shadow"),s=Xf(e,"radius","radius"),a=Xf(e,"spacing","spacing"),o=Object.keys(e.headings.sizes).reduce((c,d)=>(c[d]={fontSize:`var(--mantine-${d}-font-size)`,lineHeight:`var(--mantine-${d}-line-height)`,fontWeight:`var(--mantine-${d}-font-weight)`},c),{}),l=Object.keys(e.colors).reduce((c,d)=>(c[d]={0:`var(--mantine-color-${d}-0)`,1:`var(--mantine-color-${d}-1)`,2:`var(--mantine-color-${d}-2)`,3:`var(--mantine-color-${d}-3)`,4:`var(--mantine-color-${d}-4)`,5:`var(--mantine-color-${d}-5)`,6:`var(--mantine-color-${d}-6)`,7:`var(--mantine-color-${d}-7)`,8:`var(--mantine-color-${d}-8)`,9:`var(--mantine-color-${d}-9)`,filled:`var(--mantine-color-${d}-filled)`,filledHover:`var(--mantine-color-${d}-filled-hover)`,light:`var(--mantine-color-${d}-light)`,lightHover:`var(--mantine-color-${d}-light-hover)`,lightColor:`var(--mantine-color-${d}-light-color)`,outline:`var(--mantine-color-${d}-outline)`,outlineHover:`var(--mantine-color-${d}-outline-hover)`},c),{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:e.breakpoints,fontSizes:t,lineHeights:r,shadows:i,radius:s,headings:o,spacing:a,colors:l,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:c=>`(max-width: ${JR(c,e)})`,largerThan:c=>`(min-width: ${JR(c,e)})`}}const Ow={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Gl.extend({defaultProps:{radius:"xs"}}),ColorInput:jE.extend({defaultProps:{radius:"xs"}}),Select:zc.extend({defaultProps:{radius:"sm"}}),Textarea:qE.extend({defaultProps:{radius:"xs"}}),TextInput:aC.extend({defaultProps:{radius:"xs"}}),NumberInput:nC.extend({defaultProps:{radius:"xs"}}),Paper:Xc.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:au.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:lh.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};Fne(Ow);const rz=U.createContext(void 0),iz=()=>{const n=U.useContext(rz);if(!n)throw new Error("useLoading must be used within a LoadingProvider");return n},zne=({children:n})=>{const[e,t]=U.useState(!1),r=U.useRef(0),i=U.useCallback(()=>{r.current+=1,r.current>0&&t(!0)},[]),s=U.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&t(!1)},[]);return j.jsx(rz.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:n})},Une=()=>{const{isLoading:n}=iz();return n?j.jsx("div",{className:"loader-overlay",children:j.jsx("div",{className:"loader-content",children:j.jsx(sh,{size:64,type:"bars"})})}):null},$w="panel",Gw="ref";function One(){const n="/".replace(/\/+$/,"/");let t=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=n.replace(/^\/+|\/+$/g,"");if(r&&(t===r?t="":t.startsWith(`${r}/`)&&(t=t.slice(r.length+1))),!t)return null;const i=t.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function _I(n){return n.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function $ne(n,e){const t=n.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const A=new URL(h,p||window.location.href).toString();r.add(A)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,a=new URL(t,s).toString();i("assets/config.json",a);const l=window.location.pathname.split("/").filter(Boolean);l.length>0&&l[l.length-1]==="index.html"&&l.pop(),l.length>0&&l[l.length-1]===(e??"main")&&l.pop();const c=`/${l.join("/")}${l.length?"/":""}`,d=`${window.location.origin}${c}`;return i("assets/config.json",d),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function Gne(n,e){const r=new URLSearchParams(window.location.search).get("config"),i=$ne(n,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const a of i)try{const o=await fetch(a,{cache:"no-store"});if(!o.ok)throw new Error(`Failed to fetch ${a}: ${o.status}`);const l=await o.text(),c=l.trim();if((o.headers.get("content-type")||"").includes("text/html")||c.startsWith("<!doctype")||c.startsWith("<html"))throw new Error(`Received HTML from ${a}`);try{return JSON.parse(l)}catch(h){throw new Error(`Invalid JSON from ${a}: ${h instanceof Error?h.message:String(h)}`)}}catch(o){s=o instanceof Error?o:new Error(String(o))}throw s??new Error("Failed to load config.json.")}function KR(n,e){if(!n.scenes.length)return null;if(!e)return n.scenes[0];const t=e.trim().toLowerCase();return n.scenes.find(r=>r.name.toLowerCase()===t)||n.scenes.find(r=>_I(r.name)===t)||n.scenes[0]}function q_(n,e){if(!n.policies.length)return null;const t=n.policies.find(s=>s.default)??n.policies[0];if(!e)return t.name;const r=e.trim().toLowerCase();return(n.policies.find(s=>s.name.toLowerCase()===r)||n.policies.find(s=>_I(s.name)===r))?.name??t.name}function Jf(n,e){return n?.motions?.length?(n.motions.find(r=>r.default)??n.motions[0]).name:null}function Vne(n){return new URLSearchParams(n).get($w)!=="0"}function Hne(n){return new URLSearchParams(n).get(Gw)!=="0"}function jne(n){const t="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let r=t?`/${t}/`:"/";return n&&n!=="main"&&(r+=`${n}/`),r}function Wne({projectId:n,sceneName:e,policyName:t,panelVisible:r,showReference:i}){const s=jne(n),a=new URLSearchParams(window.location.search);e?a.set("scene",e):a.delete("scene"),t?a.set("policy",t):a.delete("policy"),r?a.delete($w):a.set($w,"0"),i?a.delete(Gw):a.set(Gw,"0");const o=a.toString(),l=s+(o?`?${o}`:"")+window.location.hash;window.history.replaceState({},"",l)}function qne(){const[n,e]=U.useState(null),[t,r]=U.useState(null),[i,s]=U.useState(null),[a,o]=U.useState(null),[l,c]=U.useState(null),[d,h]=U.useState(()=>Hne(window.location.search)),[p,A]=U.useState(null),[y,m]=U.useState(null),[x,g]=U.useState(null),[_,b]=U.useState(()=>Vne(window.location.search)),w=U.useRef(null),{showLoading:C,hideLoading:S}=iz(),M=U.useMemo(()=>One(),[]),T=U.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),R=U.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);U.useEffect(()=>{C(),Gne("/",M).then(J=>{e(J);const ge=J.projects.find(Ce=>M===null?Ce.id===null:Ce.id===M);if(!ge)throw new Error(`Project "${M??"(main)"}" not found in config.json.`);r(ge);const te=KR(ge,T);s(te);const ee=te?q_(te,R):null;o(ee);const ie=te?.policies.find(Ce=>Ce.name===ee)??null;c(Jf(ie))}).catch(J=>{A(J.message||"Failed to load config."),S()})},[M,T,R,C,S]);const k=U.useMemo(()=>{if(!t||!i)return null;const J=t.id?t.id:"main",ge=i.path?i.path:`scene/${_I(i.name)}/scene.xml`;return`${J}/assets/${ge}`.replace(/\/+/g,"/")},[t,i]),$=U.useMemo(()=>!i||!a?null:i.policies.find(J=>J.name===a)??null,[i,a]),Q=U.useMemo(()=>!t||!$?.config?null:`${t.id?t.id:"main"}/assets/${$.config}`.replace(/\/+/g,"/"),[t,$]),H=U.useMemo(()=>$?.motions?.length?$.motions.map(J=>({value:J.name,label:J.name})):[],[$]),B=U.useMemo(()=>{if(!t||!i?.splats?.length)return[];const J=t.id?t.id:"main";return i.splats.map(ge=>{if(ge.path){const te=`${J}/assets/${ge.path}`.replace(/\/+/g,"/");return{...ge,url:te}}return ge})},[t,i?.splats]),W=U.useMemo(()=>y?B.find(J=>J.name===y)??null:x?{name:"Custom",url:x}:null,[B,y,x]),K=U.useMemo(()=>n?n.projects.map(J=>({value:J.id??"main",label:J.name||(J.id??"Main")})):[],[n]),Y=U.useMemo(()=>t?t.scenes.map(J=>({value:J.name,label:J.name})):[],[t]),G=U.useMemo(()=>!i||!i.policies?[]:i.policies.map(J=>({value:J.name,label:J.name})),[i]),X=t?t.id??"main":null,re=i?.name??null,L=U.useCallback(J=>{A(J.message),S()},[S]),V=U.useCallback(()=>{S()},[S]);U.useEffect(()=>{const J=i?.splats?.[0];m(J?J.name:null),g(null)},[i]);const oe=U.useCallback(J=>{w.current=J},[]);U.useEffect(()=>{c(Jf($)),h(!!$?.motions?.length)},[$]);const Ae=U.useMemo(()=>i?.splats?.length?i.splats.map(J=>({value:J.name,label:J.name})):[],[i?.splats]),ye=U.useCallback(J=>{if(J===null)w.current?.setSplat(null);else{const ge=B.find(te=>te.name===J);ge&&w.current?.setSplat(ge)}m(J),g(null)},[B]),he=U.useCallback(async J=>{try{if(!(await fetch(J,{method:"HEAD"})).ok)return!1}catch{return!1}return w.current?.setSplat({name:"Custom",url:J}),g(J),!0},[]),fe=U.useCallback((J,ge,te,ee,ie,Ce,be)=>{const de=W??(x?{name:"Custom",url:x}:null);de&&w.current?.calibrateSplat({...de,scale:J,xOffset:ge,yOffset:te,zOffset:ee,roll:ie,pitch:Ce,yaw:be})},[W,x]),Ee=U.useCallback(J=>{Wne({projectId:J.projectId??t?.id??null,sceneName:J.sceneName??i?.name??null,policyName:J.policyName??a,panelVisible:J.panelVisible??_,showReference:J.showReference??d})},[t?.id,i?.name,a,_,d]),Re=U.useCallback(J=>{if(!n||!J)return;const ge=J==="main"?null:J,te=n.projects.find(be=>(be.id??"main")===(ge??"main"));if(!te)return;C(),r(te);const ee=KR(te,null);s(ee);const ie=ee?q_(ee,null):null;o(ie);const Ce=ee?.policies.find(be=>be.name===ie)??null;c(Jf(Ce)),Ee({projectId:te.id,sceneName:ee?.name??null,policyName:ie})},[n,C,Ee]),ve=U.useCallback(J=>{if(!t||!J)return;const ge=t.scenes.find(ie=>ie.name===J);if(!ge)return;C(),s(ge);const te=q_(ge,null);o(te);const ee=ge.policies.find(ie=>ie.name===te)??null;c(Jf(ee)),Ee({projectId:t.id,sceneName:J,policyName:te})},[t,C,Ee]),Ne=U.useCallback(J=>{J!==a&&C(),o(J);const ge=i?.policies.find(te=>te.name===J)??null;c(Jf(ge)),Ee({policyName:J})},[a,C,Ee]),rt=U.useCallback(J=>{b(J),Ee({panelVisible:J})},[Ee]),Ge=U.useCallback(J=>{const ge=l;c(J),w.current?.setSelectedMotion(J)?.then(ee=>{ee===!1&&J!==null&&c(w.current?.getSelectedMotionName()??ge)})},[l]),F=U.useCallback(J=>{h(J),w.current?.setReferenceVisible(J),Ee({showReference:J})},[Ee]);return p?j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsx("div",{className:"app",children:j.jsxs("div",{className:"hud hud-error",children:[j.jsx("h1",{className:"hud-title",children:"mjswan"}),j.jsx("p",{className:"hud-message",children:p})]})})}):!t||!i||!k?null:j.jsx(eb,{theme:Ow,defaultColorScheme:"auto",children:j.jsxs("div",{className:"app",children:[j.jsx(Une,{}),j.jsx(Lne,{visible:_,onVisibleChange:rt,projects:K,projectValue:X,projectLabel:t?.name??"mjswan",onProjectChange:Re,scenes:Y,sceneValue:re,onSceneChange:ve,splats:Ae,splatSection:i?.splatSection??!1,splatValue:y,onSplatChange:ye,splatConfig:W,onCalibrateSplat:fe,onSplatUrlLoad:he,policies:G,policyValue:a,onPolicyChange:Ne,motions:H,motionValue:l,onMotionChange:Ge,showReferenceMotion:d,onShowReferenceMotionChange:F,commandsEnabled:!!Q}),j.jsx(gne,{scenePath:k,baseUrl:"/",policyConfigPath:Q,splatConfig:W,cameraConfig:i?.camera,eventsConfig:i?.events,terrainData:i?.terrainData,selectedMotion:l,showReferenceMotion:d,onError:L,onReady:V,onRuntimeReady:oe})]})})}function Yne(){return j.jsx(zne,{children:j.jsx(qne,{})})}const ZR=document.getElementById("root");ZR&&Wz.createRoot(ZR).render(j.jsx(On.StrictMode,{children:j.jsx(Yne,{})}));export{RV as _};
@@ -1,4 +1,4 @@
1
- import{_ as Gn}from"./index-BBC2lLaG.js";const Yn=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var tc=(async function(De={}){var Tr,v=De,Ke=typeof window=="object",Z=typeof WorkerGlobalScope<"u",V=typeof process=="object"&&process.versions?.node&&process.type!="renderer",ct=!Ke&&!V&&!Z,A=Z&&self.name?.startsWith("em-pthread");if(A&&(p(!globalThis.moduleLoaded,"module should only be loaded once on each pthread worker"),globalThis.moduleLoaded=!0),V){const{createRequire:e}=await Gn(async()=>{const{createRequire:r}=await Promise.resolve().then(()=>Yn);return{createRequire:r}},void 0);var ve=e(import.meta.url),Xe=ve("worker_threads");global.Worker=Xe.Worker,Z=!Xe.isMainThread,A=Z&&Xe.workerData=="em-pthread"}var Fr="./this.program",Pr=(e,r)=>{throw r},Ar=import.meta.url,Je="";function Kn(e){return v.locateFile?v.locateFile(e,Je):Je+e}var Ze,Oe;if(V){if(!(typeof process=="object"&&process.versions?.node&&process.type!="renderer"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");var lt=process.versions.node,Ie=lt.split(".").slice(0,3);if(Ie=Ie[0]*1e4+Ie[1]*100+Ie[2].split("-")[0]*1,Ie<160400)throw new Error("This emscripten-generated code requires node v16.04.4.0 (detected v"+lt+")");var Me=ve("fs");Ar.startsWith("file:")&&(Je=ve("path").dirname(ve("url").fileURLToPath(Ar))+"/"),Oe=r=>{r=xe(r)?new URL(r):r;var t=Me.readFileSync(r);return p(Buffer.isBuffer(t)),t},Ze=async(r,t=!0)=>{r=xe(r)?new URL(r):r;var n=Me.readFileSync(r,t?void 0:"utf8");return p(t?Buffer.isBuffer(n):typeof n=="string"),n},process.argv.length>1&&(Fr=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),Pr=(r,t)=>{throw process.exitCode=r,t}}else if(ct){if(typeof process=="object"&&process.versions?.node&&process.type!="renderer"||typeof window=="object"||typeof WorkerGlobalScope<"u")throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else if(Ke||Z){try{Je=new URL(".",Ar).href}catch{}if(!(typeof window=="object"||typeof WorkerGlobalScope<"u"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");V||(Z&&(Oe=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),Ze=async e=>{if(xe(e))return new Promise((t,n)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{if(i.status==200||i.status==0&&i.response){t(i.response);return}n(i.status)},i.onerror=n,i.send(null)});var r=await fetch(e,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)})}else throw new Error("environment detection error");var ut=(()=>{}).bind(console),dt=(()=>{}).bind(console);if(V){var Xn=ve("util"),ft=e=>typeof e=="object"?Xn.inspect(e):e;ut=(...e)=>Me.writeSync(1,e.map(ft).join(" ")+`
1
+ import{_ as Gn}from"./index-BuyVQoco.js";const Yn=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));var tc=(async function(De={}){var Tr,v=De,Ke=typeof window=="object",Z=typeof WorkerGlobalScope<"u",V=typeof process=="object"&&process.versions?.node&&process.type!="renderer",ct=!Ke&&!V&&!Z,A=Z&&self.name?.startsWith("em-pthread");if(A&&(p(!globalThis.moduleLoaded,"module should only be loaded once on each pthread worker"),globalThis.moduleLoaded=!0),V){const{createRequire:e}=await Gn(async()=>{const{createRequire:r}=await Promise.resolve().then(()=>Yn);return{createRequire:r}},void 0);var ve=e(import.meta.url),Xe=ve("worker_threads");global.Worker=Xe.Worker,Z=!Xe.isMainThread,A=Z&&Xe.workerData=="em-pthread"}var Fr="./this.program",Pr=(e,r)=>{throw r},Ar=import.meta.url,Je="";function Kn(e){return v.locateFile?v.locateFile(e,Je):Je+e}var Ze,Oe;if(V){if(!(typeof process=="object"&&process.versions?.node&&process.type!="renderer"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");var lt=process.versions.node,Ie=lt.split(".").slice(0,3);if(Ie=Ie[0]*1e4+Ie[1]*100+Ie[2].split("-")[0]*1,Ie<160400)throw new Error("This emscripten-generated code requires node v16.04.4.0 (detected v"+lt+")");var Me=ve("fs");Ar.startsWith("file:")&&(Je=ve("path").dirname(ve("url").fileURLToPath(Ar))+"/"),Oe=r=>{r=xe(r)?new URL(r):r;var t=Me.readFileSync(r);return p(Buffer.isBuffer(t)),t},Ze=async(r,t=!0)=>{r=xe(r)?new URL(r):r;var n=Me.readFileSync(r,t?void 0:"utf8");return p(t?Buffer.isBuffer(n):typeof n=="string"),n},process.argv.length>1&&(Fr=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),Pr=(r,t)=>{throw process.exitCode=r,t}}else if(ct){if(typeof process=="object"&&process.versions?.node&&process.type!="renderer"||typeof window=="object"||typeof WorkerGlobalScope<"u")throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)")}else if(Ke||Z){try{Je=new URL(".",Ar).href}catch{}if(!(typeof window=="object"||typeof WorkerGlobalScope<"u"))throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");V||(Z&&(Oe=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),Ze=async e=>{if(xe(e))return new Promise((t,n)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{if(i.status==200||i.status==0&&i.response){t(i.response);return}n(i.status)},i.onerror=n,i.send(null)});var r=await fetch(e,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)})}else throw new Error("environment detection error");var ut=(()=>{}).bind(console),dt=(()=>{}).bind(console);if(V){var Xn=ve("util"),ft=e=>typeof e=="object"?Xn.inspect(e):e;ut=(...e)=>Me.writeSync(1,e.map(ft).join(" ")+`
2
2
  `),dt=(...e)=>Me.writeSync(2,e.map(ft).join(" ")+`
3
3
  `)}var ue=ut,C=dt;p(Ke||Z||V,"Pthreads do not work in this environment yet (need Web Workers, or an alternative to them)"),p(!ct,"shell environment detected but not enabled at build time. Add `shell` to `-sENVIRONMENT` to enable.");var Ne;typeof WebAssembly!="object"&&C("no native wasm support detected");var Cr,ke=!1,Se;function p(e,r){e||z("Assertion failed"+(r?": "+r:""))}var xe=e=>e.startsWith("file://");function vt(){var e=tt();p((e&3)==0),e==0&&(e+=4),(d(),T)[e>>2]=34821223,(d(),T)[e+4>>2]=2310721022,(d(),T)[0]=1668509029}function Le(){if(!ke){var e=tt();e==0&&(e+=4);var r=(d(),T)[e>>2],t=(d(),T)[e+4>>2];(r!=34821223||t!=2310721022)&&z(`Stack overflow! Stack cookie has been overwritten at ${he(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${he(t)} ${he(r)}`),(d(),T)[0]!=1668509029&&z("Runtime error: The application has corrupted its heap memory area (address zero)!")}}class b extends Error{}class Jn extends b{}class $r extends b{constructor(r){super(r),this.excPtr=r;const t=Pn(r);this.name=t[0],this.message=t[1]}}(()=>{var e=new Int16Array(1),r=new Int8Array(e.buffer);if(e[0]=25459,r[0]!==115||r[1]!==99)throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})();function Qe(e){Object.getOwnPropertyDescriptor(v,e)||Object.defineProperty(v,e,{configurable:!0,set(){z(`Attempt to set \`Module.${e}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`)}})}function M(e){return()=>p(!1,`call to '${e}' via reference taken before Wasm module initialization`)}function Zn(e){Object.getOwnPropertyDescriptor(v,e)&&z(`\`Module.${e}\` was supplied but \`${e}\` not included in INCOMING_MODULE_JS_API`)}function _t(e){return e==="FS_createPath"||e==="FS_createDataFile"||e==="FS_createPreloadedFile"||e==="FS_unlink"||e==="addRunDependency"||e==="FS_createLazyFile"||e==="FS_createDevice"||e==="removeRunDependency"}function pt(e,r){typeof globalThis<"u"&&!Object.getOwnPropertyDescriptor(globalThis,e)&&Object.defineProperty(globalThis,e,{configurable:!0,get(){r()}})}function ht(e,r){pt(e,()=>{ae(`\`${e}\` is not longer defined by emscripten. ${r}`)})}ht("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),ht("asm","Please use wasmExports instead");function Qn(e){pt(e,()=>{var r=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,t=e;t.startsWith("_")||(t="$"+e),r+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${t}')`,_t(e)&&(r+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),ae(r)}),mt(e)}function mt(e){A||Object.getOwnPropertyDescriptor(v,e)||Object.defineProperty(v,e,{configurable:!0,get(){var r=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;_t(e)&&(r+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),z(r)}})}function d(){Q.buffer!=B.buffer&&er()}var Rr,Dr,gt;if(V&&A){var yt=Xe.parentPort;yt.on("message",e=>global.onmessage?.({data:e})),Object.assign(globalThis,{self:global,postMessage:e=>yt.postMessage(e)})}var ei=0;if(A){let e=function(r){try{var t=r.data,n=t.cmd;if(n==="load"){ei=t.workerID;let i=[];self.onmessage=a=>i.push(a),self.startWorker=a=>{postMessage({cmd:"loaded"});for(let s of i)e(s);self.onmessage=e};for(const a of t.handlers)(!v[a]||v[a].proxy)&&(v[a]=(...s)=>{postMessage({cmd:"callHandler",handler:a,args:s})},a=="print"&&(ue=v[a]),a=="printErr"&&(C=v[a]));Q=t.wasmMemory,er(),gt(t.wasmModule)}else if(n==="run"){p(t.pthread_ptr),vi(t.pthread_ptr),rt(t.pthread_ptr,0,0,1,0,0),$.threadInitTLS(),Yr(t.pthread_ptr),Or||(Cn(),Or=!0);try{_i(t.start_routine,t.arg)}catch(i){if(i!="unwind")throw i}}else t.target==="setimmediate"||(n==="checkMailbox"?Or&&wr():n&&(C(`worker: received unknown command ${n}`),C(t)))}catch(i){throw C(`worker: onmessage() captured an uncaught exception: ${i}`),i?.stack&&C(i.stack),$n(),i}};var Or=!1;self.onunhandledrejection=r=>{throw r.reason||r},self.onmessage=e}var Q,B,K,de,ie,S,T,wt,Ue,Y,Et,We=!1;function er(){var e=Q.buffer;B=new Int8Array(e),de=new Int16Array(e),K=new Uint8Array(e),ie=new Uint16Array(e),S=new Int32Array(e),T=new Uint32Array(e),wt=new Float32Array(e),Ue=new Float64Array(e),Y=new BigInt64Array(e),Et=new BigUint64Array(e)}function ri(){if(!A){if(v.wasmMemory)Q=v.wasmMemory;else{var e=v.INITIAL_MEMORY||16777216;p(e>=65536,"INITIAL_MEMORY should be larger than STACK_SIZE, was "+e+"! (STACK_SIZE=65536)"),Q=new WebAssembly.Memory({initial:e/65536,maximum:32768,shared:!0})}er()}}p(typeof Int32Array<"u"&&typeof Float64Array<"u"&&Int32Array.prototype.subarray!=null&&Int32Array.prototype.set!=null,"JS engine does not provide full typed array support");function ti(){if(p(!A),v.preRun)for(typeof v.preRun=="function"&&(v.preRun=[v.preRun]);v.preRun.length;)Ct(v.preRun.shift());Qe("preRun"),Pt(At)}function bt(){if(p(!We),We=!0,A)return startWorker(v);Le(),!v.noFSInit&&!o.initialized&&o.init(),Ee.__wasm_call_ctors(),o.ignorePermissions=!1}function ni(){if(Le(),!A){if(v.postRun)for(typeof v.postRun=="function"&&(v.postRun=[v.postRun]);v.postRun.length;)fi(v.postRun.shift());Qe("postRun"),Pt(Rt)}}var _e=0,je=null,Te={},pe=null;function rr(e){_e++,v.monitorRunDependencies?.(_e),e?(p(!Te[e]),Te[e]=1,pe===null&&typeof setInterval<"u"&&(pe=setInterval(()=>{if(ke){clearInterval(pe),pe=null;return}var r=!1;for(var t in Te)r||(r=!0,C("still waiting on run dependencies:")),C(`dependency: ${t}`);r&&C("(end of list)")},1e4))):C("warning: run dependency added without ID")}function Be(e){if(_e--,v.monitorRunDependencies?.(_e),e?(p(Te[e]),delete Te[e]):C("warning: run dependency removed without ID"),_e==0&&(pe!==null&&(clearInterval(pe),pe=null),je)){var r=je;je=null,r()}}function z(e){v.onAbort?.(e),e="Aborted("+e+")",C(e),ke=!0;var r=new WebAssembly.RuntimeError(e);throw Dr?.(r),r}function U(e,r){return(...t)=>{p(We,`native function \`${e}\` called before runtime initialization`);var n=Ee[e];return p(n,`exported native function \`${e}\` not found`),p(t.length<=r,`native function \`${e}\` called with ${t.length} args but expects ${r}`),n(...t)}}var ze;function ii(){return v.locateFile?Kn("mujoco.wasm"):new URL("/assets/mujoco-BrqJA_5D.wasm",import.meta.url).href}function ai(e){if(e==ze&&Ne)return new Uint8Array(Ne);if(Oe)return Oe(e);throw"both async and sync fetching of the wasm failed"}async function oi(e){if(!Ne)try{var r=await Ze(e);return new Uint8Array(r)}catch{}return ai(e)}async function si(e,r){try{var t=await oi(e),n=await WebAssembly.instantiate(t,r);return n}catch(i){C(`failed to asynchronously prepare wasm: ${i}`),xe(ze)&&C(`warning: Loading from a file URI (${ze}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`),z(i)}}async function ci(e,r,t){if(!e&&typeof WebAssembly.instantiateStreaming=="function"&&!xe(r)&&!V)try{var n=fetch(r,{credentials:"same-origin"}),i=await WebAssembly.instantiateStreaming(n,t);return i}catch(a){C(`wasm streaming compile failed: ${a}`),C("falling back to ArrayBuffer instantiation")}return si(r,t)}function kt(){return zo(),{env:ot,wasi_snapshot_preview1:ot}}async function li(){function e(s,c){return Ee=s.exports,pi(Ee._emscripten_tls_init),nr=Ee.__indirect_function_table,p(nr,"table not found in wasm exports"),Cr=c,Bo(Ee),Be("wasm-instantiate"),Ee}rr("wasm-instantiate");var r=v;function t(s){return p(v===r,"the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?"),r=null,e(s.instance,s.module)}var n=kt();if(v.instantiateWasm)return new Promise((s,c)=>{try{v.instantiateWasm(n,(l,u)=>{s(e(l,u))})}catch(l){C(`Module.instantiateWasm callback failed with error: ${l}`),c(l)}});if(A)return new Promise(s=>{gt=c=>{var l=new WebAssembly.Instance(c,kt());s(e(l,c))}});ze??=ii();var i=await ci(Ne,ze,n),a=t(i);return a}class St{name="ExitStatus";constructor(r){this.message=`Program terminated with exit(${r})`,this.status=r}}var Tt=e=>{e.terminate(),e.onmessage=r=>{var t=r.data.cmd;C(`received "${t}" command from terminated worker: ${e.workerID}`)}},Ft=e=>{p(!A,"Internal Error! cleanupThread() can only ever be called from main application thread!"),p(e,"Internal Error! Null pthread_ptr in cleanupThread!");var r=$.pthreads[e];p(r),$.returnWorkerToPool(r)},Pt=e=>{for(;e.length>0;)e.shift()(v)},At=[],Ct=e=>At.push(e),ui=e=>{p(!A,"Internal Error! spawnThread() can only ever be called from main application thread!"),p(e.pthread_ptr,"Internal error, no pthread ptr!");var r=$.getNewWorker();if(!r)return 6;p(!r.pthread_ptr,"Internal error!"),$.runningWorkers.push(r),$.pthreads[e.pthread_ptr]=r,r.pthread_ptr=e.pthread_ptr;var t={cmd:"run",start_routine:e.startRoutine,arg:e.arg,pthread_ptr:e.pthread_ptr};return V&&r.unref(),r.postMessage(t,e.transferList),0},He=0,tr=()=>ir||He>0,w=()=>it(),y=e=>Un(e),Ve=e=>Wn(e),G=(e,r,t,...n)=>{for(var i=n.length*2,a=w(),s=Ve(i*8),c=s>>3,l=0;l<n.length;l++){var u=n[l];typeof u=="bigint"?((d(),Y)[c+2*l]=1n,(d(),Y)[c+2*l+1]=u):((d(),Y)[c+2*l]=0n,(d(),Ue)[c+2*l+1]=u)}var f=Rn(e,r,i,s,t);return y(a),f};function Ir(e){if(A)return G(0,0,1,e);Se=e,tr()||($.terminateAllThreads(),v.onExit?.(e),ke=!0),Pr(e,new St(e))}function $t(e){if(A)return G(1,0,0,e);Mr(e)}var di=(e,r)=>{if(Se=e,ec(),A)throw p(!r),$t(e),"unwind";if(tr()&&!r){var t=`program exited (with status: ${e}), but keepRuntimeAlive() is set (counter=${He}) due to an async operation, so halting execution but not exiting the runtime or preventing further async execution (you can use emscripten_force_exit, if you want to force a true shutdown)`;Dr?.(t),C(t)}Ir(e)},Mr=di,he=e=>(p(typeof e=="number"),e>>>=0,"0x"+e.toString(16).padStart(8,"0")),$={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},nextWorkerID:1,init(){A||$.initMainThread()},initMainThread(){Ct(()=>{rr("loading-workers"),$.loadWasmModuleToAllWorkers(()=>Be("loading-workers"))})},terminateAllThreads:()=>{p(!A,"Internal Error! terminateAllThreads() can only ever be called from main application thread!");for(var e of $.runningWorkers)Tt(e);for(var e of $.unusedWorkers)Tt(e);$.unusedWorkers=[],$.runningWorkers=[],$.pthreads={}},returnWorkerToPool:e=>{var r=e.pthread_ptr;delete $.pthreads[r],$.unusedWorkers.push(e),$.runningWorkers.splice($.runningWorkers.indexOf(e),1),e.pthread_ptr=0,Dn(r)},threadInitTLS(){$.tlsInitFunctions.forEach(e=>e())},loadWasmModuleToWorker:e=>new Promise(r=>{e.onmessage=a=>{var s=a.data,c=s.cmd;if(s.targetThread&&s.targetThread!=Zr()){var l=$.pthreads[s.targetThread];l?l.postMessage(s,s.transferList):C(`Internal error! Worker sent a message "${c}" to target pthread ${s.targetThread}, but that thread no longer exists!`);return}c==="checkMailbox"?wr():c==="spawnThread"?ui(s):c==="cleanupThread"?Ft(s.thread):c==="loaded"?(e.loaded=!0,r(e)):s.target==="setimmediate"?e.postMessage(s):c==="callHandler"?v[s.handler](...s.args):c&&C(`worker sent an unknown command ${c}`)},e.onerror=a=>{var s="worker sent an error!";throw e.pthread_ptr&&(s=`Pthread ${he(e.pthread_ptr)} sent an error!`),C(`${s} ${a.filename}:${a.lineno}: ${a.message}`),a},V&&(e.on("message",a=>e.onmessage({data:a})),e.on("error",a=>e.onerror(a))),p(Q instanceof WebAssembly.Memory,"WebAssembly memory should have been loaded by now!"),p(Cr instanceof WebAssembly.Module,"WebAssembly Module should have been loaded by now!");var t=[],n=["onExit","onAbort","print","printErr"];for(var i of n)v.propertyIsEnumerable(i)&&t.push(i);e.postMessage({cmd:"load",handlers:t,wasmMemory:Q,wasmModule:Cr,workerID:e.workerID})}),loadWasmModuleToAllWorkers(e){e()},allocateUnusedWorker(){var e;if(v.mainScriptUrlOrBlob){var r=v.mainScriptUrlOrBlob;typeof r!="string"&&(r=URL.createObjectURL(r)),e=new Worker(r,{type:"module",workerData:"em-pthread",name:"em-pthread-"+$.nextWorkerID})}else e=new Worker(new URL("/assets/mujoco-BYnSNfgd.js",import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread-"+$.nextWorkerID});e.workerID=$.nextWorkerID++,$.unusedWorkers.push(e)},getNewWorker(){return $.unusedWorkers.length==0&&(V||C("Tried to spawn a new thread, but the thread pool is exhausted.\nThis might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.\nIf you want to increase the pool size, use setting `-sPTHREAD_POOL_SIZE=...`.\nIf you want to throw an explicit error instead of the risk of deadlocking in those cases, use setting `-sPTHREAD_POOL_SIZE_STRICT=2`."),$.allocateUnusedWorker(),$.loadWasmModuleToWorker($.unusedWorkers[0])),$.unusedWorkers.pop()}},Rt=[],fi=e=>Rt.push(e);function vi(e){var r=(d(),T)[e+52>>2],t=(d(),T)[e+56>>2],n=r-t;p(r!=0),p(n!=0),p(r>n,"stackHigh must be higher then stackLow"),Ln(r,n),y(r),vt()}var Dt=[],nr,E=e=>{var r=Dt[e];return r||(Dt[e]=r=nr.get(e)),p(nr.get(e)==r,"JavaScript-side Wasm function table mirror is out of date!"),r},_i=(e,r)=>{He=0,ir=0;var t=E(e)(r);Le();function n(i){tr()?Se=i:nt(i)}n(t)},ir=!0,pi=e=>$.tlsInitFunctions.push(e),ae=e=>{ae.shown||={},ae.shown[e]||(ae.shown[e]=1,V&&(e="warning: "+e),C(e))},Ot=typeof TextDecoder<"u"?new TextDecoder:void 0,Fe=(e,r=0,t=NaN)=>{for(var n=r+t,i=r;e[i]&&!(i>=n);)++i;if(i-r>16&&e.buffer&&Ot)return Ot.decode(e.buffer instanceof ArrayBuffer?e.subarray(r,i):e.slice(r,i));for(var a="";r<i;){var s=e[r++];if(!(s&128)){a+=String.fromCharCode(s);continue}var c=e[r++]&63;if((s&224)==192){a+=String.fromCharCode((s&31)<<6|c);continue}var l=e[r++]&63;if((s&240)==224?s=(s&15)<<12|c<<6|l:((s&248)!=240&&ae("Invalid UTF-8 leading byte "+he(s)+" encountered when deserializing a UTF-8 string in wasm memory to a JS string!"),s=(s&7)<<18|c<<12|l<<6|e[r++]&63),s<65536)a+=String.fromCharCode(s);else{var u=s-65536;a+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return a},oe=(e,r)=>(p(typeof e=="number",`UTF8ToString expects a number (got ${typeof e})`),e?Fe((d(),K),e,r):""),hi=(e,r,t,n)=>z(`Assertion failed: ${oe(e)}, at: `+[r?oe(r):"unknown filename",t,n?oe(n):"unknown function"]),mi=(e,r)=>E(e)(r),se=[],ar=0,gi=e=>{var r=new or(e);return r.get_caught()||(r.set_caught(!0),ar--),r.set_rethrown(!1),se.push(r),Sr(e),zn(e)},yi=()=>{if(!se.length)return 0;var e=se[se.length-1];return Sr(e.excPtr),e.excPtr},ce=0,wi=()=>{k(0,0),p(se.length>0);var e=se.pop();at(e.excPtr),ce=0};class or{constructor(r){this.excPtr=r,this.ptr=r-24}set_type(r){(d(),T)[this.ptr+4>>2]=r}get_type(){return(d(),T)[this.ptr+4>>2]}set_destructor(r){(d(),T)[this.ptr+8>>2]=r}get_destructor(){return(d(),T)[this.ptr+8>>2]}set_caught(r){r=r?1:0,(d(),B)[this.ptr+12]=r}get_caught(){return(d(),B)[this.ptr+12]!=0}set_rethrown(r){r=r?1:0,(d(),B)[this.ptr+13]=r}get_rethrown(){return(d(),B)[this.ptr+13]!=0}init(r,t){this.set_adjusted_ptr(0),this.set_type(r),this.set_destructor(t)}set_adjusted_ptr(r){(d(),T)[this.ptr+16>>2]=r}get_adjusted_ptr(){return(d(),T)[this.ptr+16>>2]}}var sr=e=>Nn(e),Nr=e=>{var r=ce?.excPtr;if(!r)return sr(0),0;var t=new or(r);t.set_adjusted_ptr(r);var n=t.get_type();if(!n)return sr(0),r;for(var i of e){if(i===0||i===n)break;var a=t.ptr+16;if(Bn(i,n,a))return sr(i),r}return sr(n),r},Ei=()=>Nr([]),bi=e=>Nr([e]),ki=(e,r)=>Nr([e,r]),It=()=>{var e=se.pop();e||z("no exception to throw");var r=e.excPtr;throw e.get_rethrown()||(se.push(e),e.set_rethrown(!0),e.set_caught(!1),ar++),ce=new $r(r),ce},Si=e=>{if(e){var r=new or(e);se.push(r),r.set_rethrown(!0),It()}},Ti=(e,r,t)=>{var n=new or(e);throw n.init(r,t),ce=new $r(e),ar++,ce},Fi=()=>ar,Pi=e=>{throw ce||(ce=new $r(e)),ce},O={isAbs:e=>e.charAt(0)==="/",splitPath:e=>{var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return r.exec(e).slice(1)},normalizeArray:(e,r)=>{for(var t=0,n=e.length-1;n>=0;n--){var i=e[n];i==="."?e.splice(n,1):i===".."?(e.splice(n,1),t++):t&&(e.splice(n,1),t--)}if(r)for(;t;t--)e.unshift("..");return e},normalize:e=>{var r=O.isAbs(e),t=e.slice(-1)==="/";return e=O.normalizeArray(e.split("/").filter(n=>!!n),!r).join("/"),!e&&!r&&(e="."),e&&t&&(e+="/"),(r?"/":"")+e},dirname:e=>{var r=O.splitPath(e),t=r[0],n=r[1];return!t&&!n?".":(n&&(n=n.slice(0,-1)),t+n)},basename:e=>e&&e.match(/([^\/]+|\/)\/*$/)[1],join:(...e)=>O.normalize(e.join("/")),join2:(e,r)=>O.normalize(e+"/"+r)},Ai=()=>{if(V){var e=ve("crypto");return r=>e.randomFillSync(r)}return r=>r.set(crypto.getRandomValues(new Uint8Array(r.byteLength)))},Mt=e=>{(Mt=Ai())(e)},Pe={resolve:(...e)=>{for(var r="",t=!1,n=e.length-1;n>=-1&&!t;n--){var i=n>=0?e[n]:o.cwd();if(typeof i!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";r=i+"/"+r,t=O.isAbs(i)}return r=O.normalizeArray(r.split("/").filter(a=>!!a),!t).join("/"),(t?"/":"")+r||"."},relative:(e,r)=>{e=Pe.resolve(e).slice(1),r=Pe.resolve(r).slice(1);function t(u){for(var f=0;f<u.length&&u[f]==="";f++);for(var h=u.length-1;h>=0&&u[h]==="";h--);return f>h?[]:u.slice(f,h-f+1)}for(var n=t(e.split("/")),i=t(r.split("/")),a=Math.min(n.length,i.length),s=a,c=0;c<a;c++)if(n[c]!==i[c]){s=c;break}for(var l=[],c=s;c<n.length;c++)l.push("..");return l=l.concat(i.slice(s)),l.join("/")}},xr=[],Ae=e=>{for(var r=0,t=0;t<e.length;++t){var n=e.charCodeAt(t);n<=127?r++:n<=2047?r+=2:n>=55296&&n<=57343?(r+=4,++t):r+=3}return r},Nt=(e,r,t,n)=>{if(p(typeof e=="string",`stringToUTF8Array expects a string (got ${typeof e})`),!(n>0))return 0;for(var i=t,a=t+n-1,s=0;s<e.length;++s){var c=e.codePointAt(s);if(c<=127){if(t>=a)break;r[t++]=c}else if(c<=2047){if(t+1>=a)break;r[t++]=192|c>>6,r[t++]=128|c&63}else if(c<=65535){if(t+2>=a)break;r[t++]=224|c>>12,r[t++]=128|c>>6&63,r[t++]=128|c&63}else{if(t+3>=a)break;c>1114111&&ae("Invalid Unicode code point "+he(c)+" encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF)."),r[t++]=240|c>>18,r[t++]=128|c>>12&63,r[t++]=128|c>>6&63,r[t++]=128|c&63,s++}}return r[t]=0,t-i},Lr=(e,r,t)=>{var n=Ae(e)+1,i=new Array(n),a=Nt(e,i,0,i.length);return i.length=a,i},Ci=()=>{if(!xr.length){var e=null;if(V){var r=256,t=Buffer.alloc(r),n=0,i=process.stdin.fd;try{n=Me.readSync(i,t,0,r)}catch(a){if(a.toString().includes("EOF"))n=0;else throw a}n>0&&(e=t.slice(0,n).toString("utf-8"))}else typeof window<"u"&&typeof window.prompt=="function"&&(e=window.prompt("Input: "),e!==null&&(e+=`
4
4
  `));if(!e)return null;xr=Lr(e)}return xr.shift()},fe={ttys:[],init(){},shutdown(){},register(e,r){fe.ttys[e]={input:[],output:[],ops:r},o.registerDevice(e,fe.stream_ops)},stream_ops:{open(e){var r=fe.ttys[e.node.rdev];if(!r)throw new o.ErrnoError(43);e.tty=r,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,r,t,n,i){if(!e.tty||!e.tty.ops.get_char)throw new o.ErrnoError(60);for(var a=0,s=0;s<n;s++){var c;try{c=e.tty.ops.get_char(e.tty)}catch{throw new o.ErrnoError(29)}if(c===void 0&&a===0)throw new o.ErrnoError(6);if(c==null)break;a++,r[t+s]=c}return a&&(e.node.atime=Date.now()),a},write(e,r,t,n,i){if(!e.tty||!e.tty.ops.put_char)throw new o.ErrnoError(60);try{for(var a=0;a<n;a++)e.tty.ops.put_char(e.tty,r[t+a])}catch{throw new o.ErrnoError(29)}return n&&(e.node.mtime=e.node.ctime=Date.now()),a}},default_tty_ops:{get_char(e){return Ci()},put_char(e,r){r===null||r===10?(ue(Fe(e.output)),e.output=[]):r!=0&&e.output.push(r)},fsync(e){e.output?.length>0&&(ue(Fe(e.output)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,r,t){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,r){r===null||r===10?(C(Fe(e.output)),e.output=[]):r!=0&&e.output.push(r)},fsync(e){e.output?.length>0&&(C(Fe(e.output)),e.output=[])}}},xt=e=>{z("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported")},P={ops_table:null,mount(e){return P.createNode(null,"/",16895,0)},createNode(e,r,t,n){if(o.isBlkdev(t)||o.isFIFO(t))throw new o.ErrnoError(63);P.ops_table||={dir:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr,lookup:P.node_ops.lookup,mknod:P.node_ops.mknod,rename:P.node_ops.rename,unlink:P.node_ops.unlink,rmdir:P.node_ops.rmdir,readdir:P.node_ops.readdir,symlink:P.node_ops.symlink},stream:{llseek:P.stream_ops.llseek}},file:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr},stream:{llseek:P.stream_ops.llseek,read:P.stream_ops.read,write:P.stream_ops.write,mmap:P.stream_ops.mmap,msync:P.stream_ops.msync}},link:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr,readlink:P.node_ops.readlink},stream:{}},chrdev:{node:{getattr:P.node_ops.getattr,setattr:P.node_ops.setattr},stream:o.chrdev_stream_ops}};var i=o.createNode(e,r,t,n);return o.isDir(i.mode)?(i.node_ops=P.ops_table.dir.node,i.stream_ops=P.ops_table.dir.stream,i.contents={}):o.isFile(i.mode)?(i.node_ops=P.ops_table.file.node,i.stream_ops=P.ops_table.file.stream,i.usedBytes=0,i.contents=null):o.isLink(i.mode)?(i.node_ops=P.ops_table.link.node,i.stream_ops=P.ops_table.link.stream):o.isChrdev(i.mode)&&(i.node_ops=P.ops_table.chrdev.node,i.stream_ops=P.ops_table.chrdev.stream),i.atime=i.mtime=i.ctime=Date.now(),e&&(e.contents[r]=i,e.atime=e.mtime=e.ctime=i.atime),i},getFileDataAsTypedArray(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage(e,r){var t=e.contents?e.contents.length:0;if(!(t>=r)){var n=1024*1024;r=Math.max(r,t*(t<n?2:1.125)>>>0),t!=0&&(r=Math.max(r,256));var i=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,r){if(e.usedBytes!=r)if(r==0)e.contents=null,e.usedBytes=0;else{var t=e.contents;e.contents=new Uint8Array(r),t&&e.contents.set(t.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr(e){var r={};return r.dev=o.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,o.isDir(e.mode)?r.size=4096:o.isFile(e.mode)?r.size=e.usedBytes:o.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.atime),r.mtime=new Date(e.mtime),r.ctime=new Date(e.ctime),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr(e,r){for(const t of["mode","atime","mtime","ctime"])r[t]!=null&&(e[t]=r[t]);r.size!==void 0&&P.resizeFileStorage(e,r.size)},lookup(e,r){throw new o.ErrnoError(44)},mknod(e,r,t,n){return P.createNode(e,r,t,n)},rename(e,r,t){var n;try{n=o.lookupNode(r,t)}catch{}if(n){if(o.isDir(e.mode))for(var i in n.contents)throw new o.ErrnoError(55);o.hashRemoveNode(n)}delete e.parent.contents[e.name],r.contents[t]=e,e.name=t,r.ctime=r.mtime=e.parent.ctime=e.parent.mtime=Date.now()},unlink(e,r){delete e.contents[r],e.ctime=e.mtime=Date.now()},rmdir(e,r){var t=o.lookupNode(e,r);for(var n in t.contents)throw new o.ErrnoError(55);delete e.contents[r],e.ctime=e.mtime=Date.now()},readdir(e){return[".","..",...Object.keys(e.contents)]},symlink(e,r,t){var n=P.createNode(e,r,41471,0);return n.link=t,n},readlink(e){if(!o.isLink(e.mode))throw new o.ErrnoError(28);return e.link}},stream_ops:{read(e,r,t,n,i){var a=e.node.contents;if(i>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-i,n);if(p(s>=0),s>8&&a.subarray)r.set(a.subarray(i,i+s),t);else for(var c=0;c<s;c++)r[t+c]=a[i+c];return s},write(e,r,t,n,i,a){if(p(!(r instanceof ArrayBuffer)),r.buffer===(d(),B).buffer&&(a=!1),!n)return 0;var s=e.node;if(s.mtime=s.ctime=Date.now(),r.subarray&&(!s.contents||s.contents.subarray)){if(a)return p(i===0,"canOwn must imply no weird position inside the file"),s.contents=r.subarray(t,t+n),s.usedBytes=n,n;if(s.usedBytes===0&&i===0)return s.contents=r.slice(t,t+n),s.usedBytes=n,n;if(i+n<=s.usedBytes)return s.contents.set(r.subarray(t,t+n),i),n}if(P.expandFileStorage(s,i+n),s.contents.subarray&&r.subarray)s.contents.set(r.subarray(t,t+n),i);else for(var c=0;c<n;c++)s.contents[i+c]=r[t+c];return s.usedBytes=Math.max(s.usedBytes,i+n),n},llseek(e,r,t){var n=r;if(t===1?n+=e.position:t===2&&o.isFile(e.node.mode)&&(n+=e.node.usedBytes),n<0)throw new o.ErrnoError(28);return n},mmap(e,r,t,n,i){if(!o.isFile(e.node.mode))throw new o.ErrnoError(43);var a,s,c=e.node.contents;if(!(i&2)&&c&&c.buffer===(d(),B).buffer)s=!1,a=c.byteOffset;else{if(s=!0,a=xt(),!a)throw new o.ErrnoError(48);c&&((t>0||t+r<c.length)&&(c.subarray?c=c.subarray(t,t+r):c=Array.prototype.slice.call(c,t,t+r)),(d(),B).set(c,a))}return{ptr:a,allocated:s}},msync(e,r,t,n,i){return P.stream_ops.write(e,r,0,n,t,!1),0}}},$i=async e=>{var r=await Ze(e);return p(r,`Loading data file "${e}" failed (no arrayBuffer).`),new Uint8Array(r)},Lt=(...e)=>o.createDataFile(...e),Ri=e=>{for(var r=e;;){if(!Te[e])return e;e=r+Math.random()}},Ut=[],Di=(e,r,t,n)=>{typeof Browser<"u"&&Browser.init();var i=!1;return Ut.forEach(a=>{i||a.canHandle(r)&&(a.handle(e,r,t,n),i=!0)}),i},Wt=(e,r,t,n,i,a,s,c,l,u)=>{var f=r?Pe.resolve(O.join2(e,r)):e,h=Ri(`cp ${f}`);function m(_){function g(F){u?.(),c||Lt(e,r,F,n,i,l),a?.(),Be(h)}Di(_,f,g,()=>{s?.(),Be(h)})||g(_)}rr(h),typeof t=="string"?$i(t).then(m,s):m(t)},Oi=e=>{var r={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},t=r[e];if(typeof t>"u")throw new Error(`Unknown file open mode: ${e}`);return t},Ur=(e,r)=>{var t=0;return e&&(t|=365),r&&(t|=146),t},Ii=e=>oe(In(e)),jt={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},o={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class extends Error{name="ErrnoError";constructor(e){super(We?Ii(e):""),this.errno=e;for(var r in jt)if(jt[r]===e){this.code=r;break}}},FSStream:class{shared={};get object(){return this.node}set object(e){this.node=e}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(e,r,t,n){e||(e=this),this.parent=e,this.mount=e.mount,this.id=o.nextInode++,this.name=r,this.mode=t,this.rdev=n,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return o.isDir(this.mode)}get isDevice(){return o.isChrdev(this.mode)}},lookupPath(e,r={}){if(!e)throw new o.ErrnoError(44);r.follow_mount??=!0,O.isAbs(e)||(e=o.cwd()+"/"+e);e:for(var t=0;t<40;t++){for(var n=e.split("/").filter(u=>!!u),i=o.root,a="/",s=0;s<n.length;s++){var c=s===n.length-1;if(c&&r.parent)break;if(n[s]!=="."){if(n[s]===".."){if(a=O.dirname(a),o.isRoot(i)){e=a+"/"+n.slice(s+1).join("/");continue e}else i=i.parent;continue}a=O.join2(a,n[s]);try{i=o.lookupNode(i,n[s])}catch(u){if(u?.errno===44&&c&&r.noent_okay)return{path:a};throw u}if(o.isMountpoint(i)&&(!c||r.follow_mount)&&(i=i.mounted.root),o.isLink(i.mode)&&(!c||r.follow)){if(!i.node_ops.readlink)throw new o.ErrnoError(52);var l=i.node_ops.readlink(i);O.isAbs(l)||(l=O.dirname(a)+"/"+l),e=l+"/"+n.slice(s+1).join("/");continue e}}}return{path:a,node:i}}throw new o.ErrnoError(32)},getPath(e){for(var r;;){if(o.isRoot(e)){var t=e.mount.mountpoint;return r?t[t.length-1]!=="/"?`${t}/${r}`:t+r:t}r=r?`${e.name}/${r}`:e.name,e=e.parent}},hashName(e,r){for(var t=0,n=0;n<r.length;n++)t=(t<<5)-t+r.charCodeAt(n)|0;return(e+t>>>0)%o.nameTable.length},hashAddNode(e){var r=o.hashName(e.parent.id,e.name);e.name_next=o.nameTable[r],o.nameTable[r]=e},hashRemoveNode(e){var r=o.hashName(e.parent.id,e.name);if(o.nameTable[r]===e)o.nameTable[r]=e.name_next;else for(var t=o.nameTable[r];t;){if(t.name_next===e){t.name_next=e.name_next;break}t=t.name_next}},lookupNode(e,r){var t=o.mayLookup(e);if(t)throw new o.ErrnoError(t);for(var n=o.hashName(e.id,r),i=o.nameTable[n];i;i=i.name_next){var a=i.name;if(i.parent.id===e.id&&a===r)return i}return o.lookup(e,r)},createNode(e,r,t,n){p(typeof e=="object");var i=new o.FSNode(e,r,t,n);return o.hashAddNode(i),i},destroyNode(e){o.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)===32768},isDir(e){return(e&61440)===16384},isLink(e){return(e&61440)===40960},isChrdev(e){return(e&61440)===8192},isBlkdev(e){return(e&61440)===24576},isFIFO(e){return(e&61440)===4096},isSocket(e){return(e&49152)===49152},flagsToPermissionString(e){var r=["r","w","rw"][e&3];return e&512&&(r+="w"),r},nodePermissions(e,r){return o.ignorePermissions?0:r.includes("r")&&!(e.mode&292)||r.includes("w")&&!(e.mode&146)||r.includes("x")&&!(e.mode&73)?2:0},mayLookup(e){if(!o.isDir(e.mode))return 54;var r=o.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate(e,r){if(!o.isDir(e.mode))return 54;try{var t=o.lookupNode(e,r);return 20}catch{}return o.nodePermissions(e,"wx")},mayDelete(e,r,t){var n;try{n=o.lookupNode(e,r)}catch(a){return a.errno}var i=o.nodePermissions(e,"wx");if(i)return i;if(t){if(!o.isDir(n.mode))return 54;if(o.isRoot(n)||o.getPath(n)===o.cwd())return 10}else if(o.isDir(n.mode))return 31;return 0},mayOpen(e,r){return e?o.isLink(e.mode)?32:o.isDir(e.mode)&&(o.flagsToPermissionString(r)!=="r"||r&576)?31:o.nodePermissions(e,o.flagsToPermissionString(r)):44},checkOpExists(e,r){if(!e)throw new o.ErrnoError(r);return e},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=o.MAX_OPEN_FDS;e++)if(!o.streams[e])return e;throw new o.ErrnoError(33)},getStreamChecked(e){var r=o.getStream(e);if(!r)throw new o.ErrnoError(8);return r},getStream:e=>o.streams[e],createStream(e,r=-1){return p(r>=-1),e=Object.assign(new o.FSStream,e),r==-1&&(r=o.nextfd()),e.fd=r,o.streams[r]=e,e},closeStream(e){o.streams[e]=null},dupStream(e,r=-1){var t=o.createStream(e,r);return t.stream_ops?.dup?.(t),t},doSetAttr(e,r,t){var n=e?.stream_ops.setattr,i=n?e:r;n??=r.node_ops.setattr,o.checkOpExists(n,63),n(i,t)},chrdev_stream_ops:{open(e){var r=o.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,e.stream_ops.open?.(e)},llseek(){throw new o.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,r)=>e<<8|r,registerDevice(e,r){o.devices[e]={stream_ops:r}},getDevice:e=>o.devices[e],getMounts(e){for(var r=[],t=[e];t.length;){var n=t.pop();r.push(n),t.push(...n.mounts)}return r},syncfs(e,r){typeof e=="function"&&(r=e,e=!1),o.syncFSRequests++,o.syncFSRequests>1&&C(`warning: ${o.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var t=o.getMounts(o.root.mount),n=0;function i(s){return p(o.syncFSRequests>0),o.syncFSRequests--,r(s)}function a(s){if(s)return a.errored?void 0:(a.errored=!0,i(s));++n>=t.length&&i(null)}t.forEach(s=>{if(!s.type.syncfs)return a(null);s.type.syncfs(s,e,a)})},mount(e,r,t){if(typeof e=="string")throw e;var n=t==="/",i=!t,a;if(n&&o.root)throw new o.ErrnoError(10);if(!n&&!i){var s=o.lookupPath(t,{follow_mount:!1});if(t=s.path,a=s.node,o.isMountpoint(a))throw new o.ErrnoError(10);if(!o.isDir(a.mode))throw new o.ErrnoError(54)}var c={type:e,opts:r,mountpoint:t,mounts:[]},l=e.mount(c);return l.mount=c,c.root=l,n?o.root=l:a&&(a.mounted=c,a.mount&&a.mount.mounts.push(c)),l},unmount(e){var r=o.lookupPath(e,{follow_mount:!1});if(!o.isMountpoint(r.node))throw new o.ErrnoError(28);var t=r.node,n=t.mounted,i=o.getMounts(n);Object.keys(o.nameTable).forEach(s=>{for(var c=o.nameTable[s];c;){var l=c.name_next;i.includes(c.mount)&&o.destroyNode(c),c=l}}),t.mounted=null;var a=t.mount.mounts.indexOf(n);p(a!==-1),t.mount.mounts.splice(a,1)},lookup(e,r){return e.node_ops.lookup(e,r)},mknod(e,r,t){var n=o.lookupPath(e,{parent:!0}),i=n.node,a=O.basename(e);if(!a)throw new o.ErrnoError(28);if(a==="."||a==="..")throw new o.ErrnoError(20);var s=o.mayCreate(i,a);if(s)throw new o.ErrnoError(s);if(!i.node_ops.mknod)throw new o.ErrnoError(63);return i.node_ops.mknod(i,a,r,t)},statfs(e){return o.statfsNode(o.lookupPath(e,{follow:!0}).node)},statfsStream(e){return o.statfsNode(e.node)},statfsNode(e){var r={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:o.nextInode,ffree:o.nextInode-1,fsid:42,flags:2,namelen:255};return e.node_ops.statfs&&Object.assign(r,e.node_ops.statfs(e.mount.opts.root)),r},create(e,r=438){return r&=4095,r|=32768,o.mknod(e,r,0)},mkdir(e,r=511){return r&=1023,r|=16384,o.mknod(e,r,0)},mkdirTree(e,r){var t=e.split("/"),n="";for(var i of t)if(i){(n||O.isAbs(e))&&(n+="/"),n+=i;try{o.mkdir(n,r)}catch(a){if(a.errno!=20)throw a}}},mkdev(e,r,t){return typeof t>"u"&&(t=r,r=438),r|=8192,o.mknod(e,r,t)},symlink(e,r){if(!Pe.resolve(e))throw new o.ErrnoError(44);var t=o.lookupPath(r,{parent:!0}),n=t.node;if(!n)throw new o.ErrnoError(44);var i=O.basename(r),a=o.mayCreate(n,i);if(a)throw new o.ErrnoError(a);if(!n.node_ops.symlink)throw new o.ErrnoError(63);return n.node_ops.symlink(n,i,e)},rename(e,r){var t=O.dirname(e),n=O.dirname(r),i=O.basename(e),a=O.basename(r),s,c,l;if(s=o.lookupPath(e,{parent:!0}),c=s.node,s=o.lookupPath(r,{parent:!0}),l=s.node,!c||!l)throw new o.ErrnoError(44);if(c.mount!==l.mount)throw new o.ErrnoError(75);var u=o.lookupNode(c,i),f=Pe.relative(e,n);if(f.charAt(0)!==".")throw new o.ErrnoError(28);if(f=Pe.relative(r,t),f.charAt(0)!==".")throw new o.ErrnoError(55);var h;try{h=o.lookupNode(l,a)}catch{}if(u!==h){var m=o.isDir(u.mode),_=o.mayDelete(c,i,m);if(_)throw new o.ErrnoError(_);if(_=h?o.mayDelete(l,a,m):o.mayCreate(l,a),_)throw new o.ErrnoError(_);if(!c.node_ops.rename)throw new o.ErrnoError(63);if(o.isMountpoint(u)||h&&o.isMountpoint(h))throw new o.ErrnoError(10);if(l!==c&&(_=o.nodePermissions(c,"w"),_))throw new o.ErrnoError(_);o.hashRemoveNode(u);try{c.node_ops.rename(u,l,a),u.parent=l}catch(g){throw g}finally{o.hashAddNode(u)}}},rmdir(e){var r=o.lookupPath(e,{parent:!0}),t=r.node,n=O.basename(e),i=o.lookupNode(t,n),a=o.mayDelete(t,n,!0);if(a)throw new o.ErrnoError(a);if(!t.node_ops.rmdir)throw new o.ErrnoError(63);if(o.isMountpoint(i))throw new o.ErrnoError(10);t.node_ops.rmdir(t,n),o.destroyNode(i)},readdir(e){var r=o.lookupPath(e,{follow:!0}),t=r.node,n=o.checkOpExists(t.node_ops.readdir,54);return n(t)},unlink(e){var r=o.lookupPath(e,{parent:!0}),t=r.node;if(!t)throw new o.ErrnoError(44);var n=O.basename(e),i=o.lookupNode(t,n),a=o.mayDelete(t,n,!1);if(a)throw new o.ErrnoError(a);if(!t.node_ops.unlink)throw new o.ErrnoError(63);if(o.isMountpoint(i))throw new o.ErrnoError(10);t.node_ops.unlink(t,n),o.destroyNode(i)},readlink(e){var r=o.lookupPath(e),t=r.node;if(!t)throw new o.ErrnoError(44);if(!t.node_ops.readlink)throw new o.ErrnoError(28);return t.node_ops.readlink(t)},stat(e,r){var t=o.lookupPath(e,{follow:!r}),n=t.node,i=o.checkOpExists(n.node_ops.getattr,63);return i(n)},fstat(e){var r=o.getStreamChecked(e),t=r.node,n=r.stream_ops.getattr,i=n?r:t;return n??=t.node_ops.getattr,o.checkOpExists(n,63),n(i)},lstat(e){return o.stat(e,!0)},doChmod(e,r,t,n){o.doSetAttr(e,r,{mode:t&4095|r.mode&-4096,ctime:Date.now(),dontFollow:n})},chmod(e,r,t){var n;if(typeof e=="string"){var i=o.lookupPath(e,{follow:!t});n=i.node}else n=e;o.doChmod(null,n,r,t)},lchmod(e,r){o.chmod(e,r,!0)},fchmod(e,r){var t=o.getStreamChecked(e);o.doChmod(t,t.node,r,!1)},doChown(e,r,t){o.doSetAttr(e,r,{timestamp:Date.now(),dontFollow:t})},chown(e,r,t,n){var i;if(typeof e=="string"){var a=o.lookupPath(e,{follow:!n});i=a.node}else i=e;o.doChown(null,i,n)},lchown(e,r,t){o.chown(e,r,t,!0)},fchown(e,r,t){var n=o.getStreamChecked(e);o.doChown(n,n.node,!1)},doTruncate(e,r,t){if(o.isDir(r.mode))throw new o.ErrnoError(31);if(!o.isFile(r.mode))throw new o.ErrnoError(28);var n=o.nodePermissions(r,"w");if(n)throw new o.ErrnoError(n);o.doSetAttr(e,r,{size:t,timestamp:Date.now()})},truncate(e,r){if(r<0)throw new o.ErrnoError(28);var t;if(typeof e=="string"){var n=o.lookupPath(e,{follow:!0});t=n.node}else t=e;o.doTruncate(null,t,r)},ftruncate(e,r){var t=o.getStreamChecked(e);if(r<0||(t.flags&2097155)===0)throw new o.ErrnoError(28);o.doTruncate(t,t.node,r)},utime(e,r,t){var n=o.lookupPath(e,{follow:!0}),i=n.node,a=o.checkOpExists(i.node_ops.setattr,63);a(i,{atime:r,mtime:t})},open(e,r,t=438){if(e==="")throw new o.ErrnoError(44);r=typeof r=="string"?Oi(r):r,r&64?t=t&4095|32768:t=0;var n,i;if(typeof e=="object")n=e;else{i=e.endsWith("/");var a=o.lookupPath(e,{follow:!(r&131072),noent_okay:!0});n=a.node,e=a.path}var s=!1;if(r&64)if(n){if(r&128)throw new o.ErrnoError(20)}else{if(i)throw new o.ErrnoError(31);n=o.mknod(e,t|511,0),s=!0}if(!n)throw new o.ErrnoError(44);if(o.isChrdev(n.mode)&&(r&=-513),r&65536&&!o.isDir(n.mode))throw new o.ErrnoError(54);if(!s){var c=o.mayOpen(n,r);if(c)throw new o.ErrnoError(c)}r&512&&!s&&o.truncate(n,0),r&=-131713;var l=o.createStream({node:n,path:o.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return l.stream_ops.open&&l.stream_ops.open(l),s&&o.chmod(n,t&511),v.logReadFiles&&!(r&1)&&(e in o.readFiles||(o.readFiles[e]=1)),l},close(e){if(o.isClosed(e))throw new o.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(r){throw r}finally{o.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,r,t){if(o.isClosed(e))throw new o.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new o.ErrnoError(70);if(t!=0&&t!=1&&t!=2)throw new o.ErrnoError(28);return e.position=e.stream_ops.llseek(e,r,t),e.ungotten=[],e.position},read(e,r,t,n,i){if(p(t>=0),n<0||i<0)throw new o.ErrnoError(28);if(o.isClosed(e))throw new o.ErrnoError(8);if((e.flags&2097155)===1)throw new o.ErrnoError(8);if(o.isDir(e.node.mode))throw new o.ErrnoError(31);if(!e.stream_ops.read)throw new o.ErrnoError(28);var a=typeof i<"u";if(!a)i=e.position;else if(!e.seekable)throw new o.ErrnoError(70);var s=e.stream_ops.read(e,r,t,n,i);return a||(e.position+=s),s},write(e,r,t,n,i,a){if(p(t>=0),n<0||i<0)throw new o.ErrnoError(28);if(o.isClosed(e))throw new o.ErrnoError(8);if((e.flags&2097155)===0)throw new o.ErrnoError(8);if(o.isDir(e.node.mode))throw new o.ErrnoError(31);if(!e.stream_ops.write)throw new o.ErrnoError(28);e.seekable&&e.flags&1024&&o.llseek(e,0,2);var s=typeof i<"u";if(!s)i=e.position;else if(!e.seekable)throw new o.ErrnoError(70);var c=e.stream_ops.write(e,r,t,n,i,a);return s||(e.position+=c),c},mmap(e,r,t,n,i){if((n&2)!==0&&(i&2)===0&&(e.flags&2097155)!==2)throw new o.ErrnoError(2);if((e.flags&2097155)===1)throw new o.ErrnoError(2);if(!e.stream_ops.mmap)throw new o.ErrnoError(43);if(!r)throw new o.ErrnoError(28);return e.stream_ops.mmap(e,r,t,n,i)},msync(e,r,t,n,i){return p(t>=0),e.stream_ops.msync?e.stream_ops.msync(e,r,t,n,i):0},ioctl(e,r,t){if(!e.stream_ops.ioctl)throw new o.ErrnoError(59);return e.stream_ops.ioctl(e,r,t)},readFile(e,r={}){if(r.flags=r.flags||0,r.encoding=r.encoding||"binary",r.encoding!=="utf8"&&r.encoding!=="binary")throw new Error(`Invalid encoding type "${r.encoding}"`);var t=o.open(e,r.flags),n=o.stat(e),i=n.size,a=new Uint8Array(i);return o.read(t,a,0,i,0),r.encoding==="utf8"&&(a=Fe(a)),o.close(t),a},writeFile(e,r,t={}){t.flags=t.flags||577;var n=o.open(e,t.flags,t.mode);if(typeof r=="string"&&(r=new Uint8Array(Lr(r))),ArrayBuffer.isView(r))o.write(n,r,0,r.byteLength,void 0,t.canOwn);else throw new Error("Unsupported data type");o.close(n)},cwd:()=>o.currentPath,chdir(e){var r=o.lookupPath(e,{follow:!0});if(r.node===null)throw new o.ErrnoError(44);if(!o.isDir(r.node.mode))throw new o.ErrnoError(54);var t=o.nodePermissions(r.node,"x");if(t)throw new o.ErrnoError(t);o.currentPath=r.path},createDefaultDirectories(){o.mkdir("/tmp"),o.mkdir("/home"),o.mkdir("/home/web_user")},createDefaultDevices(){o.mkdir("/dev"),o.registerDevice(o.makedev(1,3),{read:()=>0,write:(n,i,a,s,c)=>s,llseek:()=>0}),o.mkdev("/dev/null",o.makedev(1,3)),fe.register(o.makedev(5,0),fe.default_tty_ops),fe.register(o.makedev(6,0),fe.default_tty1_ops),o.mkdev("/dev/tty",o.makedev(5,0)),o.mkdev("/dev/tty1",o.makedev(6,0));var e=new Uint8Array(1024),r=0,t=()=>(r===0&&(Mt(e),r=e.byteLength),e[--r]);o.createDevice("/dev","random",t),o.createDevice("/dev","urandom",t),o.mkdir("/dev/shm"),o.mkdir("/dev/shm/tmp")},createSpecialDirectories(){o.mkdir("/proc");var e=o.mkdir("/proc/self");o.mkdir("/proc/self/fd"),o.mount({mount(){var r=o.createNode(e,"fd",16895,73);return r.stream_ops={llseek:P.stream_ops.llseek},r.node_ops={lookup(t,n){var i=+n,a=o.getStreamChecked(i),s={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>a.path},id:i+1};return s.parent=s,s},readdir(){return Array.from(o.streams.entries()).filter(([t,n])=>n).map(([t,n])=>t.toString())}},r}},{},"/proc/self/fd")},createStandardStreams(e,r,t){e?o.createDevice("/dev","stdin",e):o.symlink("/dev/tty","/dev/stdin"),r?o.createDevice("/dev","stdout",null,r):o.symlink("/dev/tty","/dev/stdout"),t?o.createDevice("/dev","stderr",null,t):o.symlink("/dev/tty1","/dev/stderr");var n=o.open("/dev/stdin",0),i=o.open("/dev/stdout",1),a=o.open("/dev/stderr",1);p(n.fd===0,`invalid handle for stdin (${n.fd})`),p(i.fd===1,`invalid handle for stdout (${i.fd})`),p(a.fd===2,`invalid handle for stderr (${a.fd})`)},staticInit(){o.nameTable=new Array(4096),o.mount(P,{},"/"),o.createDefaultDirectories(),o.createDefaultDevices(),o.createSpecialDirectories(),o.filesystems={MEMFS:P}},init(e,r,t){p(!o.initialized,"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)"),o.initialized=!0,e??=v.stdin,r??=v.stdout,t??=v.stderr,o.createStandardStreams(e,r,t)},quit(){o.initialized=!1,et(0);for(var e of o.streams)e&&o.close(e)},findObject(e,r){var t=o.analyzePath(e,r);return t.exists?t.object:null},analyzePath(e,r){try{var t=o.lookupPath(e,{follow:!r});e=t.path}catch{}var n={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var t=o.lookupPath(e,{parent:!0});n.parentExists=!0,n.parentPath=t.path,n.parentObject=t.node,n.name=O.basename(e),t=o.lookupPath(e,{follow:!r}),n.exists=!0,n.path=t.path,n.object=t.node,n.name=t.node.name,n.isRoot=t.path==="/"}catch(i){n.error=i.errno}return n},createPath(e,r,t,n){e=typeof e=="string"?e:o.getPath(e);for(var i=r.split("/").reverse();i.length;){var a=i.pop();if(a){var s=O.join2(e,a);try{o.mkdir(s)}catch(c){if(c.errno!=20)throw c}e=s}}return s},createFile(e,r,t,n,i){var a=O.join2(typeof e=="string"?e:o.getPath(e),r),s=Ur(n,i);return o.create(a,s)},createDataFile(e,r,t,n,i,a){var s=r;e&&(e=typeof e=="string"?e:o.getPath(e),s=r?O.join2(e,r):e);var c=Ur(n,i),l=o.create(s,c);if(t){if(typeof t=="string"){for(var u=new Array(t.length),f=0,h=t.length;f<h;++f)u[f]=t.charCodeAt(f);t=u}o.chmod(l,c|146);var m=o.open(l,577);o.write(m,t,0,t.length,0,a),o.close(m),o.chmod(l,c)}},createDevice(e,r,t,n){var i=O.join2(typeof e=="string"?e:o.getPath(e),r),a=Ur(!!t,!!n);o.createDevice.major??=64;var s=o.makedev(o.createDevice.major++,0);return o.registerDevice(s,{open(c){c.seekable=!1},close(c){n?.buffer?.length&&n(10)},read(c,l,u,f,h){for(var m=0,_=0;_<f;_++){var g;try{g=t()}catch{throw new o.ErrnoError(29)}if(g===void 0&&m===0)throw new o.ErrnoError(6);if(g==null)break;m++,l[u+_]=g}return m&&(c.node.atime=Date.now()),m},write(c,l,u,f,h){for(var m=0;m<f;m++)try{n(l[u+m])}catch{throw new o.ErrnoError(29)}return f&&(c.node.mtime=c.node.ctime=Date.now()),m}}),o.mkdev(i,a,s)},forceLoadFile(e){if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if(typeof XMLHttpRequest<"u")throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");try{e.contents=Oe(e.url),e.usedBytes=e.contents.length}catch{throw new o.ErrnoError(29)}},createLazyFile(e,r,t,n,i){class a{lengthKnown=!1;chunks=[];get(_){if(!(_>this.length-1||_<0)){var g=_%this.chunkSize,F=_/this.chunkSize|0;return this.getter(F)[g]}}setDataGetter(_){this.getter=_}cacheLength(){var _=new XMLHttpRequest;if(_.open("HEAD",t,!1),_.send(null),!(_.status>=200&&_.status<300||_.status===304))throw new Error("Couldn't load "+t+". Status: "+_.status);var g=Number(_.getResponseHeader("Content-length")),F,I=(F=_.getResponseHeader("Accept-Ranges"))&&F==="bytes",D=(F=_.getResponseHeader("Content-Encoding"))&&F==="gzip",H=1024*1024;I||(H=g);var N=(q,le)=>{if(q>le)throw new Error("invalid range ("+q+", "+le+") or no bytes requested!");if(le>g-1)throw new Error("only "+g+" bytes available! programmer error!");var L=new XMLHttpRequest;if(L.open("GET",t,!1),g!==H&&L.setRequestHeader("Range","bytes="+q+"-"+le),L.responseType="arraybuffer",L.overrideMimeType&&L.overrideMimeType("text/plain; charset=x-user-defined"),L.send(null),!(L.status>=200&&L.status<300||L.status===304))throw new Error("Couldn't load "+t+". Status: "+L.status);return L.response!==void 0?new Uint8Array(L.response||[]):Lr(L.responseText||"")},be=this;be.setDataGetter(q=>{var le=q*H,L=(q+1)*H-1;if(L=Math.min(L,g-1),typeof be.chunks[q]>"u"&&(be.chunks[q]=N(le,L)),typeof be.chunks[q]>"u")throw new Error("doXHR failed!");return be.chunks[q]}),(D||!g)&&(H=g=1,g=this.getter(0).length,H=g,ue("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=g,this._chunkSize=H,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(typeof XMLHttpRequest<"u"){if(!Z)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var s=new a,c={isDevice:!1,contents:s}}else var c={isDevice:!1,url:t};var l=o.createFile(e,r,c,n,i);c.contents?l.contents=c.contents:c.url&&(l.contents=null,l.url=c.url),Object.defineProperties(l,{usedBytes:{get:function(){return this.contents.length}}});var u={},f=Object.keys(l.stream_ops);f.forEach(m=>{var _=l.stream_ops[m];u[m]=(...g)=>(o.forceLoadFile(l),_(...g))});function h(m,_,g,F,I){var D=m.node.contents;if(I>=D.length)return 0;var H=Math.min(D.length-I,F);if(p(H>=0),D.slice)for(var N=0;N<H;N++)_[g+N]=D[I+N];else for(var N=0;N<H;N++)_[g+N]=D.get(I+N);return H}return u.read=(m,_,g,F,I)=>(o.forceLoadFile(l),h(m,_,g,F,I)),u.mmap=(m,_,g,F,I)=>{o.forceLoadFile(l);var D=xt();if(!D)throw new o.ErrnoError(48);return h(m,(d(),B),D,_,g),{ptr:D,allocated:!0}},l.stream_ops=u,l},absolutePath(){z("FS.absolutePath has been removed; use PATH_FS.resolve instead")},createFolder(){z("FS.createFolder has been removed; use FS.mkdir instead")},createLink(){z("FS.createLink has been removed; use FS.symlink instead")},joinPath(){z("FS.joinPath has been removed; use PATH.join instead")},mmapAlloc(){z("FS.mmapAlloc has been replaced by the top level function mmapAlloc")},standardizePath(){z("FS.standardizePath has been removed; use PATH.normalize instead")}},x={DEFAULT_POLLMASK:5,calculateAt(e,r,t){if(O.isAbs(r))return r;var n;if(e===-100)n=o.cwd();else{var i=x.getStreamFromFD(e);n=i.path}if(r.length==0){if(!t)throw new o.ErrnoError(44);return n}return n+"/"+r},writeStat(e,r){(d(),S)[e>>2]=r.dev,(d(),S)[e+4>>2]=r.mode,(d(),T)[e+8>>2]=r.nlink,(d(),S)[e+12>>2]=r.uid,(d(),S)[e+16>>2]=r.gid,(d(),S)[e+20>>2]=r.rdev,(d(),Y)[e+24>>3]=BigInt(r.size),(d(),S)[e+32>>2]=4096,(d(),S)[e+36>>2]=r.blocks;var t=r.atime.getTime(),n=r.mtime.getTime(),i=r.ctime.getTime();return(d(),Y)[e+40>>3]=BigInt(Math.floor(t/1e3)),(d(),T)[e+48>>2]=t%1e3*1e3*1e3,(d(),Y)[e+56>>3]=BigInt(Math.floor(n/1e3)),(d(),T)[e+64>>2]=n%1e3*1e3*1e3,(d(),Y)[e+72>>3]=BigInt(Math.floor(i/1e3)),(d(),T)[e+80>>2]=i%1e3*1e3*1e3,(d(),Y)[e+88>>3]=BigInt(r.ino),0},writeStatFs(e,r){(d(),S)[e+4>>2]=r.bsize,(d(),S)[e+40>>2]=r.bsize,(d(),S)[e+8>>2]=r.blocks,(d(),S)[e+12>>2]=r.bfree,(d(),S)[e+16>>2]=r.bavail,(d(),S)[e+20>>2]=r.files,(d(),S)[e+24>>2]=r.ffree,(d(),S)[e+28>>2]=r.fsid,(d(),S)[e+44>>2]=r.flags,(d(),S)[e+36>>2]=r.namelen},doMsync(e,r,t,n,i){if(!o.isFile(r.node.mode))throw new o.ErrnoError(43);if(n&2)return 0;var a=(d(),K).slice(e,e+t);o.msync(r,a,i,t,n)},getStreamFromFD(e){var r=o.getStreamChecked(e);return r},varargs:void 0,getStr(e){var r=oe(e);return r}};function Bt(e,r,t){if(A)return G(2,0,1,e,r,t);try{var n=x.getStreamFromFD(e);if(p(!t),n.fd===r)return-28;if(r<0||r>=o.MAX_OPEN_FDS)return-8;var i=o.getStream(r);return i&&o.close(i),o.dupStream(n,r).fd}catch(a){if(typeof o>"u"||a.name!=="ErrnoError")throw a;return-a.errno}}var cr=()=>{p(x.varargs!=null);var e=(d(),S)[+x.varargs>>2];return x.varargs+=4,e},Ce=cr;function zt(e,r,t){if(A)return G(3,0,1,e,r,t);x.varargs=t;try{var n=x.getStreamFromFD(e);switch(r){case 0:{var i=cr();if(i<0)return-28;for(;o.streams[i];)i++;var a;return a=o.dupStream(n,i),a.fd}case 1:case 2:return 0;case 3:return n.flags;case 4:{var i=cr();return n.flags|=i,0}case 12:{var i=Ce(),s=0;return(d(),de)[i+s>>1]=2,0}case 13:case 14:return 0}return-28}catch(c){if(typeof o>"u"||c.name!=="ErrnoError")throw c;return-c.errno}}function Ht(e,r){if(A)return G(4,0,1,e,r);try{return x.writeStat(r,o.fstat(e))}catch(t){if(typeof o>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function Vt(e,r,t){if(A)return G(5,0,1,e,r,t);x.varargs=t;try{var n=x.getStreamFromFD(e);switch(r){case 21509:return n.tty?0:-59;case 21505:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tcgets){var i=n.tty.ops.ioctl_tcgets(n),a=Ce();(d(),S)[a>>2]=i.c_iflag||0,(d(),S)[a+4>>2]=i.c_oflag||0,(d(),S)[a+8>>2]=i.c_cflag||0,(d(),S)[a+12>>2]=i.c_lflag||0;for(var s=0;s<32;s++)(d(),B)[a+s+17]=i.c_cc[s]||0;return 0}return 0}case 21510:case 21511:case 21512:return n.tty?0:-59;case 21506:case 21507:case 21508:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tcsets){for(var a=Ce(),c=(d(),S)[a>>2],l=(d(),S)[a+4>>2],u=(d(),S)[a+8>>2],f=(d(),S)[a+12>>2],h=[],s=0;s<32;s++)h.push((d(),B)[a+s+17]);return n.tty.ops.ioctl_tcsets(n.tty,r,{c_iflag:c,c_oflag:l,c_cflag:u,c_lflag:f,c_cc:h})}return 0}case 21519:{if(!n.tty)return-59;var a=Ce();return(d(),S)[a>>2]=0,0}case 21520:return n.tty?-28:-59;case 21531:{var a=Ce();return o.ioctl(n,r,a)}case 21523:{if(!n.tty)return-59;if(n.tty.ops.ioctl_tiocgwinsz){var m=n.tty.ops.ioctl_tiocgwinsz(n.tty),a=Ce();(d(),de)[a>>1]=m[0],(d(),de)[a+2>>1]=m[1]}return 0}case 21524:return n.tty?0:-59;case 21515:return n.tty?0:-59;default:return-28}}catch(_){if(typeof o>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Gt(e,r){if(A)return G(6,0,1,e,r);try{return e=x.getStr(e),x.writeStat(r,o.lstat(e))}catch(t){if(typeof o>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function Yt(e,r,t,n){if(A)return G(7,0,1,e,r,t,n);try{r=x.getStr(r);var i=n&256,a=n&4096;return n=n&-6401,p(!n,`unknown flags in __syscall_newfstatat: ${n}`),r=x.calculateAt(e,r,a),x.writeStat(t,i?o.lstat(r):o.stat(r))}catch(s){if(typeof o>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function qt(e,r,t,n){if(A)return G(8,0,1,e,r,t,n);x.varargs=n;try{r=x.getStr(r),r=x.calculateAt(e,r);var i=n?cr():0;return o.open(r,t,i).fd}catch(a){if(typeof o>"u"||a.name!=="ErrnoError")throw a;return-a.errno}}function Kt(e,r){if(A)return G(9,0,1,e,r);try{return e=x.getStr(e),x.writeStat(r,o.stat(e))}catch(t){if(typeof o>"u"||t.name!=="ErrnoError")throw t;return-t.errno}}var Mi=()=>z("native code called abort()"),W=e=>{for(var r="";;){var t=(d(),K)[e++];if(!t)return r;r+=String.fromCharCode(t)}},$e={},me={},lr={},Ge=class extends Error{constructor(r){super(r),this.name="BindingError"}},R=e=>{throw new Ge(e)};function Ni(e,r,t={}){var n=r.name;if(e||R(`type "${n}" must have a positive integer typeid pointer`),me.hasOwnProperty(e)){if(t.ignoreDuplicateRegistrations)return;R(`Cannot register type '${n}' twice`)}if(me[e]=r,delete lr[e],$e.hasOwnProperty(e)){var i=$e[e];delete $e[e],i.forEach(a=>a())}}function X(e,r,t={}){if(r.argPackAdvance===void 0)throw new TypeError("registerType registeredInstance requires argPackAdvance");return Ni(e,r,t)}var Xt=(e,r,t)=>{switch(r){case 1:return t?n=>(d(),B)[n]:n=>(d(),K)[n];case 2:return t?n=>(d(),de)[n>>1]:n=>(d(),ie)[n>>1];case 4:return t?n=>(d(),S)[n>>2]:n=>(d(),T)[n>>2];case 8:return t?n=>(d(),Y)[n>>3]:n=>(d(),Et)[n>>3];default:throw new TypeError(`invalid integer width (${r}): ${e}`)}},ge=e=>{if(e===null)return"null";var r=typeof e;return r==="object"||r==="array"||r==="function"?e.toString():""+e},Jt=(e,r,t,n)=>{if(r<t||r>n)throw new TypeError(`Passing a number "${ge(r)}" from JS side to C/C++ side to an argument of type "${e}", which is outside the valid range [${t}, ${n}]!`)},xi=(e,r,t,n,i)=>{r=W(r);const a=n===0n;let s=c=>c;if(a){const c=t*8;s=l=>BigInt.asUintN(c,l),i=s(i)}X(e,{name:r,fromWireType:s,toWireType:(c,l)=>{if(typeof l=="number")l=BigInt(l);else if(typeof l!="bigint")throw new TypeError(`Cannot convert "${ge(l)}" to ${this.name}`);return Jt(r,l,n,i),l},argPackAdvance:ee,readValueFromPointer:Xt(r,t,!a),destructorFunction:null})},ee=8,Li=(e,r,t,n)=>{r=W(r),X(e,{name:r,fromWireType:function(i){return!!i},toWireType:function(i,a){return a?t:n},argPackAdvance:ee,readValueFromPointer:function(i){return this.fromWireType((d(),K)[i])},destructorFunction:null})},Ui=e=>({count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType}),Wr=e=>{function r(t){return t.$$.ptrType.registeredClass.name}R(r(e)+" instance already deleted")},jr=!1,Zt=e=>{},Wi=e=>{e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)},Qt=e=>{e.count.value-=1;var r=e.count.value===0;r&&Wi(e)},en=(e,r,t)=>{if(r===t)return e;if(t.baseClass===void 0)return null;var n=en(e,r,t.baseClass);return n===null?null:t.downcast(n)},rn={},ji={},Bi=(e,r)=>{for(r===void 0&&R("ptr should not be undefined");e.baseClass;)r=e.upcast(r),e=e.baseClass;return r},zi=(e,r)=>(r=Bi(e,r),ji[r]),Hi=class extends Error{constructor(r){super(r),this.name="InternalError"}},ur=e=>{throw new Hi(e)},dr=(e,r)=>{(!r.ptrType||!r.ptr)&&ur("makeClassHandle requires ptr and ptrType");var t=!!r.smartPtrType,n=!!r.smartPtr;return t!==n&&ur("Both smartPtrType and smartPtr must be specified"),r.count={value:1},Ye(Object.create(e,{$$:{value:r,writable:!0}}))};function tn(e){var r=this.getPointee(e);if(!r)return this.destructor(e),null;var t=zi(this.registeredClass,r);if(t!==void 0){if(t.$$.count.value===0)return t.$$.ptr=r,t.$$.smartPtr=e,t.clone();var n=t.clone();return this.destructor(e),n}function i(){return this.isSmartPointer?dr(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:e}):dr(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var a=this.registeredClass.getActualType(r),s=rn[a];if(!s)return i.call(this);var c;this.isConst?c=s.constPointerType:c=s.pointerType;var l=en(r,this.registeredClass,c.registeredClass);return l===null?i.call(this):this.isSmartPointer?dr(c.registeredClass.instancePrototype,{ptrType:c,ptr:l,smartPtrType:this,smartPtr:e}):dr(c.registeredClass.instancePrototype,{ptrType:c,ptr:l})}var Ye=e=>typeof FinalizationRegistry>"u"?(Ye=r=>r,e):(jr=new FinalizationRegistry(r=>{Qt(r.$$)}),Ye=r=>{var t=r.$$,n=!!t.smartPtr;if(n){var i={$$:t},a=t.ptrType.registeredClass,s=new Error(`Embind found a leaked C++ instance ${a.name} <${he(t.ptr)}>.
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-BBC2lLaG.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-BuyVQoco.js"></script>
15
15
  <link rel="stylesheet" crossorigin href="/assets/index-B4SJqdSr.css">
16
16
  </head>
17
17
  <body>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mjswan",
3
3
  "type": "module",
4
- "version": "0.5.4",
4
+ "version": "0.5.5",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/ttktjmt/mjswan.git"