mjswan 0.0.10 → 0.0.13

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.
@@ -6792,4 +6792,4 @@ fn calculateOutputIndex(index: u32) -> u32 {
6792
6792
  }`},MC=t=>{let e=t[1].dims,n=t[2].dims,r=t[0].dims,i=t[1].dataType,s=!(Le.areEqual(e,n)&&Le.areEqual(n,r)),o=e,a=Le.size(e);if(s){let d=Ec.calcShape(Ec.calcShape(e,n,!1),r,!1);if(!d)throw new Error("Can't perform where op on the given tensors");o=d,a=Le.size(o)}let u=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>EC(d,t,o,s,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:u},...Et(r,e,n,o)]})}},m$=t=>{t.compute(MC(t.inputs))}}),g$,t7=Ze(()=>{mj(),$w(),gj(),vj(),yj(),xj(),_j(),Mj(),Cj(),Aj(),Rj(),Ij(),Pj(),kj(),Dj(),$j(),Nj(),Lj(),Oj(),zj(),Uj(),Fj(),Bj(),Vj(),Hj(),ND(),Gj(),Wj(),jj(),qj(),Xj(),Dw(),Kj(),FD(),Yj(),Zj(),Jj(),zD(),Qj(),Ha(),Nw(),e7(),g$=new Map([["Abs",[uk]],["Acos",[ck]],["Acosh",[dk]],["Add",[Wk]],["ArgMax",[sk,w_]],["ArgMin",[ik,w_]],["Asin",[fk]],["Asinh",[hk]],["Atan",[pk]],["Atanh",[mk]],["Attention",[ok]],["AveragePool",[KD,XD]],["BatchNormalization",[ak]],["BiasAdd",[lk]],["BiasSplitGelu",[Gk]],["Cast",[vk,gk]],["Ceil",[xk]],["Clip",[yk]],["Concat",[tD,nD]],["Conv",[A_,C_]],["ConvTranspose",[fD,dD]],["Cos",[_k]],["Cosh",[bk]],["CumSum",[hD,pD]],["DepthToSpace",[mD,gD]],["DequantizeLinear",[n$,r$]],["Div",[jk]],["Einsum",[vD,yD]],["Elu",[wk,Sf]],["Equal",[qk]],["Erf",[Sk]],["Exp",[Ek]],["Expand",[xD]],["FastGelu",[_D]],["Floor",[Mk]],["FusedConv",[A_,C_]],["Gather",[wD,bD]],["GatherElements",[AD,CD]],["GatherBlockQuantized",[MD,TD]],["GatherND",[SD,ED]],["Gelu",[Tk]],["Gemm",[ID,RD]],["GlobalAveragePool",[ZD,YD]],["GlobalMaxPool",[t$,e$]],["Greater",[Zk]],["GreaterOrEqual",[Qk]],["GridSample",[PD,kD]],["GroupQueryAttention",[BD]],["HardSigmoid",[$k,Dk]],["InstanceNormalization",[VD]],["LayerNormalization",[HD]],["LeakyRelu",[Ck,Sf]],["Less",[Jk]],["LessOrEqual",[eD]],["Log",[Vk]],["MatMul",[GD]],["MatMulNBits",[WD,jD]],["MaxPool",[JD,QD]],["Mul",[Xk]],["MultiHeadAttention",[$D,DD]],["Neg",[Rk]],["Not",[Ak]],["Pad",[qD]],["Pow",[Kk]],["QuickGelu",[Hk,Sf]],["Range",[i$]],["Reciprocal",[Ik]],["ReduceMin",[QP]],["ReduceMean",[XP]],["ReduceMax",[JP]],["ReduceSum",[tk]],["ReduceProd",[ek]],["ReduceL1",[KP]],["ReduceL2",[YP]],["ReduceLogSum",[rk]],["ReduceLogSumExp",[ZP]],["ReduceSumSquare",[nk]],["Relu",[Pk]],["Resize",[a$,l$]],["RotaryEmbedding",[UD]],["ScatterND",[o$,s$]],["Sigmoid",[kk]],["Sin",[Nk]],["Sinh",[Lk]],["Slice",[c$,d$]],["SkipLayerNormalization",[u$]],["Split",[LD,OD]],["Sqrt",[Ok]],["Softmax",[f$,h$]],["Sub",[Yk]],["Tan",[zk]],["Tanh",[Uk]],["ThresholdedRelu",[Bk,Sf]],["Tile",[p$]],["Transpose",[LP,OP]],["Where",[m$]]])}),v$,n7=Ze(()=>{Bi(),No(),Wt(),v$=class{constructor(t){this.backend=t,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,n,r,i){Ks(t.programInfo.name);let s=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let d of e)a.push({binding:a.length,resource:{buffer:d.buffer}});for(let d of n)a.push({binding:a.length,resource:{buffer:d.buffer}});i&&a.push({binding:a.length,resource:i});let u=s.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:a,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:u,dispatchGroup:r};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}o.setPipeline(t.computePipeline),o.setBindGroup(0,u),o.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),ms(t.programInfo.name)}dispose(){}build(t,e){Ks(t.name);let n=this.backend.device,r=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(d=>{n.features.has(d.feature)&&r.push(`enable ${d.extension};`)});let i=NP(e,this.backend.device.limits),s=t.getShaderSource(i),o=`${r.join(`
6793
6793
  `)}
6794
6794
  ${i.additionalImplementations}
6795
- ${s}`,a=n.createShaderModule({code:o,label:t.name});on("verbose",()=>`[WebGPU] ${t.name} shader code: ${o}`);let u=n.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return ms(t.name),{programInfo:t,computePipeline:u,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(t){let e=typeof t=="number"?t:t.x,n=typeof t=="number"?1:t.y||1,r=typeof t=="number"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&n<=i&&r<=i)return[e,n,r];let s=e*n*r,o=Math.ceil(Math.sqrt(s));if(o>i){if(o=Math.ceil(Math.cbrt(s)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),y$={};Hc(y$,{WebGpuBackend:()=>x$});var TC,CC,AC,x$,r7=Ze(()=>{Bi(),$t(),No(),IP(),hj(),t7(),n7(),TC=(t,e)=>{if(e.length!==t.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${t.length}.`);let n=[];for(let r=0;r<t.length;++r){let i=t[r].dataType;switch(e[r]){case"none":{n.push("");break}case"type":{n.push(`${i}`);break}case"rank":{let s=t[r].dims.length;n.push(`${i};${s}`);break}case"dims":{let s=t[r].dims.join(",");n.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return n.join("|")},CC=(t,e,n)=>{let r=t.name;return t.shaderCache?.hint&&(r+="["+t.shaderCache.hint+"]"),r+=":"+n+`:${TC(e,t.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},AC=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},x$=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 t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,e){this.env=t;let n=[],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:n},i=s=>e.features.has(s)&&n.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 AC(e.info||await e.requestAdapterInfo()),this.gpuDataManager=DP(this),this.programManager=new v$(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Rw(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},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 t=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ks(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let r=0;r<e.length/2;r++){let i=n[r],s=i.kernelId,o=this.kernels.get(s),a=o.kernelType,u=o.kernelName,d=i.programName,f=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],m=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let _=Number(p-this.queryTimeBase),x=Number(m-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:f.map(y=>({dims:y.dims,dataType:wo(y.dataType)})),outputsMetadata:h.map(y=>({dims:y.dims,dataType:wo(y.dataType)})),kernelId:s,kernelType:a,kernelName:u,programName:d,startTime:_,endTime:x});else{let y="";f.forEach((b,S)=>{y+=`input[${S}]: [${b.dims}] | ${wo(b.dataType)}, `});let v="";h.forEach((b,S)=>{v+=`output[${S}]: [${b.dims}] | ${wo(b.dataType)}, `}),console.log(`[profiling] kernel "${s}|${a}|${u}|${d}" ${y}${v}start time: ${_} ns, execution time: ${x-_} ns`)}Lm("GPU",`${d}::${p}::${m}`)}t.unmap(),this.pendingQueries.delete(t)}),ms()}run(t,e,n,r,i,s){Ks(t.name);let o=[];for(let b=0;b<e.length;++b){let S=e[b].data;if(S===0)continue;let E=this.gpuDataManager.get(S);if(!E)throw new Error(`no GPU data for input: ${S}`);o.push(E)}let{outputs:a,dispatchGroup:u,programUniforms:d}=t.getRunData(e),f=n.length===0?a.map((b,S)=>S):n;if(f.length!==a.length)throw new Error(`Output size ${f.length} must be equal to ${a.length}.`);let h=[],p=[];for(let b=0;b<a.length;++b){if(!Number.isInteger(f[b])||f[b]<-3||f[b]>=s)throw new Error(`Invalid output index: ${f[b]}`);if(f[b]===-3)continue;let S=f[b]===-1,E=f[b]===-2,T=S||E?i(a[b].dataType,a[b].dims):r(f[b],a[b].dataType,a[b].dims);if(h.push(T),T.data===0)continue;let A=this.gpuDataManager.get(T.data);if(!A)throw new Error(`no GPU data for output: ${T.data}`);if(S&&this.temporaryData.push(A),E){let k=this.kernelPersistentData.get(this.currentKernelId);k||(k=[],this.kernelPersistentData.set(this.currentKernelId,k)),k.push(A)}p.push(A)}if(o.length!==e.length||p.length!==h.length){if(p.length===0)return ms(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let m;if(d){let b=0,S=[];d.forEach(k=>{let I=typeof k.data=="number"?[k.data]:k.data;if(I.length===0)return;let P=k.type===10?2:4,$,X;k.type===10?(X=I.length>4?16:I.length>2?8:I.length*P,$=I.length>4?16:P*I.length):(X=I.length<=2?I.length*P:16,$=16),b=Math.ceil(b/X)*X,S.push(b);let L=k.type===10?8:4;b+=I.length>4?Math.ceil(I.length/L)*$:I.length*P});let E=16;b=Math.ceil(b/E)*E;let T=new ArrayBuffer(b);d.forEach((k,I)=>{let P=S[I],$=typeof k.data=="number"?[k.data]:k.data;if(k.type===6)new Int32Array(T,P,$.length).set($);else if(k.type===12)new Uint32Array(T,P,$.length).set($);else if(k.type===10)new Uint16Array(T,P,$.length).set($);else if(k.type===1)new Float32Array(T,P,$.length).set($);else throw new Error(`Unsupported uniform type: ${wo(k.type)}`)});let A=this.gpuDataManager.create(b,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(A.buffer,0,T,0,b),this.gpuDataManager.release(A.id),m={offset:0,size:b,buffer:A.buffer}}let _=this.programManager.normalizeDispatchGroupSize(u),x=_[1]===1&&_[2]===1,y=CC(t,e,x),v=this.programManager.getArtifact(y);if(v||(v=this.programManager.build(t,_),this.programManager.setArtifact(y,v),on("info",()=>`[artifact] key: ${y}, programName: ${t.name}`)),d&&v.uniformVariablesInfo){if(d.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${d.length} in program "${v.programInfo.name}".`);for(let b=0;b<d.length;b++){let S=d[b],E=S.type,T=typeof S.data=="number"?1:S.data.length,[A,k]=v.uniformVariablesInfo[b];if(E!==A||T!==k)throw new Error(`Uniform variable ${b} mismatch: expect type ${A} with size ${k}, got type ${E} with size ${T} in program "${v.programInfo.name}".`)}}if(on("info",()=>`[ProgramManager] run "${t.name}" (key=${y}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let b={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(b),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(b)}return this.programManager.run(v,o,p,_,m),ms(t.name),h}upload(t,e){this.gpuDataManager.upload(t,e)}memcpy(t,e){this.gpuDataManager.memcpy(t,e)}async download(t,e){await this.gpuDataManager.download(t,e)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,e,n,r){let i=g$.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let s={kernelType:t,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(e,s)}releaseKernel(t){let e=this.kernelPersistentData.get(t);if(e){for(let n of e)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,e,n){let r=this.kernels.get(t);if(!r)throw new Error(`kernel not created: ${t}`);let i=r.kernelType,s=r.kernelName,o=r.kernelEntry,a=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=t,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),on("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let u=this.env.debug;this.temporaryData=[];try{return u&&this.device.pushErrorScope("validation"),o(e,a[1]),0}catch(d){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${d}`)),1}finally{u&&n.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${i}] ${s}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,e,n,r){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let s=i.get(e),o=this.gpuDataManager.registerExternalBuffer(n,r,s);return i.set(e,[o,n]),o}unregisterBuffers(t){let e=this.sessionExternalDataMapping.get(t);e&&(e.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let e=this.gpuDataManager.get(t);if(!e)throw new Error(`no GPU data for buffer: ${t}`);return e.buffer}createDownloader(t,e,n){return async()=>{let r=await x_(this,t,e);return Iw(r.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}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(){on("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(){on("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){on("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let r=0;r<n;r++){let i=this.getComputePassEncoder(),s=t[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(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),_$={};Hc(_$,{init:()=>b$});var em,RC,b$,i7=Ze(()=>{$t(),No(),Gt(),fj(),em=class w${constructor(e,n,r,i){this.module=e,this.dataType=n,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 w$(this.module,this.dataType,this.data,e)}},RC=class{constructor(t,e,n){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=t.PTR_SIZE,i=n/t.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(t.getValue(r*i++,s));let o=Number(t.getValue(r*i++,s));this.outputCount=Number(t.getValue(r*i++,s)),this.customDataOffset=Number(t.getValue(r*i++,"*")),this.customDataSize=Number(t.getValue(r*i++,s));let a=[];for(let u=0;u<o;u++){let d=Number(t.getValue(r*i++,s)),f=Number(t.getValue(r*i++,"*")),h=Number(t.getValue(r*i++,s)),p=[];for(let m=0;m<h;m++)p.push(Number(t.getValue(r*i++,s)));a.push(new em(t,d,f,p))}this.inputs=a}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(t,e){let n=e?.inputs?.map(o=>typeof o=="number"?this.inputs[o]:o)??this.inputs,r=e?.outputs??[],i=(o,a,u)=>new em(this.module,a,this.output(o,u),u),s=(o,a)=>{let u=Rl(o,a);if(!u)throw new Error(`Unsupported data type: ${o}`);let d=u>0?this.backend.gpuDataManager.create(u).id:0;return new em(this.module,o,d,a)};return this.backend.run(t,n,r,i,s,this.outputCount)}output(t,e){let n=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 o=0;o<e.length;o++)this.module.setValue(s+r*(o+1),e[o],i);return this.module._JsepOutput(this.opKernelContext,t,s)}catch(r){throw new Error(`Failed to generate kernel's output[${t}] 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(n)}}},b$=async(t,e,n,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let s=(r7(),Vf(y$)).WebGpuBackend,o=new s;await o.initialize(n,r),i("webgpu",[o,a=>o.alloc(Number(a)),a=>o.free(a),(a,u,d,f=!1)=>{if(f)on("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(u)}, size=${Number(d)}`),o.memcpy(Number(a),Number(u));else{on("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(u)}, size=${Number(d)}`);let h=e.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));o.upload(Number(u),h)}},async(a,u,d)=>{on("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${u}, size=${d}`),await o.download(Number(a),()=>e.HEAPU8.subarray(Number(u)>>>0,Number(u+d)>>>0))},(a,u,d)=>o.createKernel(a,Number(u),d,e.UTF8ToString(e._JsepGetNodeName(Number(u)))),a=>o.releaseKernel(a),(a,u,d,f)=>{on("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${u}`);let h=new RC(e,o,Number(u));return o.computeKernel(Number(a),h,f)},()=>o.captureBegin(),()=>o.captureEnd(),()=>o.replay()])}else{let s=new kP(n);i("webnn",[s,()=>s.reserveTensorId(),o=>s.releaseTensorId(o),async(o,a,u,d,f)=>s.ensureTensor(o,a,u,d,f),(o,a)=>{s.uploadTensor(o,a)},async(o,a)=>s.downloadTensor(o,a),(o,a)=>s.registerMLContext(o,a),!!n.trace])}}}),IC,Bw,Vw,Ma,PC,Qy,Hm,Hw,Gw,ex,Ww,jw,qw,S$=Ze(()=>{Bi(),uj(),cj(),$t(),Yl(),Mw(),TP(),IC=(t,e)=>{Mn()._OrtInit(t,e)!==0&&vn("Can't initialize onnxruntime.")},Bw=async t=>{IC(t.wasm.numThreads,zm(t.logLevel))},Vw=async(t,e)=>{Mn().asyncInit?.();let n=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=t.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=t.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!n)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=(i7(),Vf(_$)).init;e==="webgpu"&&await r("webgpu",Mn(),t,n),e==="webnn"&&await r("webnn",Mn(),t)}},Ma=new Map,PC=t=>{let e=Mn(),n=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(t,i,i+r)!==0&&vn("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(n)}},Qy=(t,e)=>{let n=Mn(),r=n.stackSave(),i=0;try{let s=n.PTR_SIZE,o=n.stackAlloc(2*s);n._OrtGetInputOutputMetadata(t,e,o,o+s)!==0&&vn("Can't get session input/output metadata.");let a=Number(n.getValue(o,"*"));i=Number(n.getValue(o+s,"*"));let u=n.HEAP32[i/4];if(u===0)return[a,0];let d=n.HEAPU32[i/4+1],f=[];for(let h=0;h<d;h++){let p=Number(n.getValue(i+8+h*s,"*"));f.push(p!==0?n.UTF8ToString(p):Number(n.getValue(i+8+(h+d)*s,"*")))}return[a,u,f]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Hm=t=>{let e=Mn(),n=e._malloc(t.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,n),[n,t.byteLength]},Hw=async(t,e)=>{let n,r,i=Mn();Array.isArray(t)?[n,r]=t:t.buffer===i.HEAPU8.buffer?[n,r]=[t.byteOffset,t.byteLength]:[n,r]=Hm(t);let s=0,o=0,a=0,u=[],d=[],f=[];try{if([o,u]=await MP(e),e?.externalData&&i.mountExternalData){let E=[];for(let T of e.externalData){let A=typeof T=="string"?T:T.path;E.push(Aw(typeof T=="string"?T:T.data).then(k=>{i.mountExternalData(A,k)}))}await Promise.all(E)}for(let E of e?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof E!="string"){let T=E,A=T?.context,k=T?.gpuDevice,I=T?.deviceType,P=T?.powerPreference;A?i.currentContext=A:k?i.currentContext=await i.webnnCreateMLContext(k):i.currentContext=await i.webnnCreateMLContext({deviceType:I,powerPreference:P})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(s),s===0&&vn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=PC(s),m=!!e?.enableGraphCapture,_=[],x=[],y=[],v=[],b=[];for(let E=0;E<h;E++){let[T,A,k]=Qy(s,E);T===0&&vn("Can't get an input name."),d.push(T);let I=i.UTF8ToString(T);_.push(I),y.push(A===0?{name:I,isTensor:!1}:{name:I,isTensor:!0,type:wo(A),shape:k})}for(let E=0;E<p;E++){let[T,A,k]=Qy(s,E+h);T===0&&vn("Can't get an output name."),f.push(T);let I=i.UTF8ToString(T);x.push(I),v.push(A===0?{name:I,isTensor:!1}:{name:I,isTensor:!0,type:wo(A),shape:k});{if(m&&e?.preferredOutputLocation===void 0){b.push("gpu-buffer");continue}let P=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[I]??"cpu",$=i.webnnIsGraphOutput;if(P==="cpu"&&$&&$(s,I)){b.push("ml-tensor-cpu-output");continue}if(P!=="cpu"&&P!=="cpu-pinned"&&P!=="gpu-buffer"&&P!=="ml-tensor")throw new Error(`Not supported preferred output location: ${P}.`);if(m&&P!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${P}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);b.push(P)}}let S=null;return b.some(E=>E==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(a=i._OrtCreateBinding(s),a===0&&vn("Can't create IO binding."),S={handle:a,outputPreferredLocations:b,outputPreferredLocationsEncoded:b.map(E=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map(E=>v_(E))}),Ma.set(s,[s,d,f,S,m,!1]),[s,_,x,y,v]}catch(h){throw d.forEach(p=>i._OrtFree(p)),f.forEach(p=>i._OrtFree(p)),a!==0&&i._OrtReleaseBinding(a)!==0&&vn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&vn("Can't release session."),h}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&vn("Can't release session options."),u.forEach(h=>i._free(h)),i.unmountExternalData?.()}},Gw=t=>{let e=Mn(),n=Ma.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[r,i,s,o,a]=n;o&&(a&&e._OrtClearBoundOutputs(o.handle)!==0&&vn("Can't clear bound outputs."),e._OrtReleaseBinding(o.handle)!==0&&vn("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),i.forEach(u=>e._OrtFree(u)),s.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(r)!==0&&vn("Can't release session."),Ma.delete(t)},ex=async(t,e,n,r,i,s,o=!1)=>{if(!t){e.push(0);return}let a=Mn(),u=a.PTR_SIZE,d=t[0],f=t[1],h=t[3],p=h,m,_;if(d==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&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 v=t[2].gpuBuffer;_=Rl(Al(d),f);{let b=a.jsepRegisterBuffer;if(!b)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=b(r,s,v,_)}}else if(h==="ml-tensor"){let v=t[2].mlTensor;_=Rl(Al(d),f);let b=a.webnnRegisterMLTensor;if(!b)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=b(r,v,Al(d),f)}else{let v=t[2];if(Array.isArray(v)){_=u*v.length,m=a._malloc(_),n.push(m);for(let b=0;b<v.length;b++){if(typeof v[b]!="string")throw new TypeError(`tensor data at index ${b} is not a string`);a.setValue(m+b*u,us(v[b],n),"*")}}else{let b=a.webnnIsGraphInput,S=a.webnnIsGraphOutput;if(d!=="string"&&b&&S){let E=a.UTF8ToString(i);if(b(r,E)||S(r,E)){let T=Al(d);_=Rl(T,f),p="ml-tensor";let A=a.webnnCreateTemporaryTensor,k=a.webnnUploadTensor;if(!A||!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let I=await A(r,T,f);k(I,new Uint8Array(v.buffer,v.byteOffset,v.byteLength)),m=I}else _=v.byteLength,m=a._malloc(_),n.push(m),a.HEAPU8.set(new Uint8Array(v.buffer,v.byteOffset,_),m)}else _=v.byteLength,m=a._malloc(_),n.push(m),a.HEAPU8.set(new Uint8Array(v.buffer,v.byteOffset,_),m)}}let x=a.stackSave(),y=a.stackAlloc(4*f.length);try{f.forEach((b,S)=>a.setValue(y+S*u,b,u===4?"i32":"i64"));let v=a._OrtCreateTensor(Al(d),m,_,y,f.length,v_(p));v===0&&vn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(v)}finally{a.stackRestore(x)}},Ww=async(t,e,n,r,i,s)=>{let o=Mn(),a=o.PTR_SIZE,u=Ma.get(t);if(!u)throw new Error(`cannot run inference. invalid session id: ${t}`);let d=u[0],f=u[1],h=u[2],p=u[3],m=u[4],_=u[5],x=e.length,y=r.length,v=0,b=[],S=[],E=[],T=[],A=[],k=o.stackSave(),I=o.stackAlloc(x*a),P=o.stackAlloc(x*a),$=o.stackAlloc(y*a),X=o.stackAlloc(y*a);try{[v,b]=EP(s),Dl("wasm prepareInputOutputTensor");for(let j=0;j<x;j++)await ex(n[j],S,T,t,f[e[j]],e[j],m);for(let j=0;j<y;j++)await ex(i[j],E,T,t,h[r[j]],x+r[j],m);$l("wasm prepareInputOutputTensor");for(let j=0;j<x;j++)o.setValue(I+j*a,S[j],"*"),o.setValue(P+j*a,f[e[j]],"*");for(let j=0;j<y;j++)o.setValue($+j*a,E[j],"*"),o.setValue(X+j*a,h[r[j]],"*");if(p&&!_){let{handle:j,outputPreferredLocations:Z,outputPreferredLocationsEncoded:Y}=p;if(f.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${f.length}).`);Dl("wasm bindInputsOutputs");for(let V=0;V<x;V++){let K=e[V];await o._OrtBindInput(j,f[K],S[V])!==0&&vn(`Can't bind input[${V}] for session=${t}.`)}for(let V=0;V<y;V++){let K=r[V];i[V]?.[3]?(A.push(E[V]),o._OrtBindOutput(j,h[K],E[V],0)!==0&&vn(`Can't bind pre-allocated output[${V}] for session=${t}.`)):o._OrtBindOutput(j,h[K],0,Y[K])!==0&&vn(`Can't bind output[${V}] to ${Z[V]} for session=${t}.`)}$l("wasm bindInputsOutputs"),Ma.set(t,[d,f,h,p,m,!0])}o.jsepOnRunStart?.(d),o.webnnOnRunStart?.(d);let L;p?L=await o._OrtRunWithBinding(d,p.handle,y,$,v):L=await o._OrtRun(d,P,I,x,X,y,$,v),L!==0&&vn("failed to call OrtRun().");let G=[],C=[];Dl("wasm ProcessOutputTensor");for(let j=0;j<y;j++){let Z=Number(o.getValue($+j*a,"*"));if(Z===E[j]||A.includes(E[j])){G.push(i[j]),Z!==E[j]&&o._OrtReleaseTensor(Z)!==0&&vn("Can't release tensor.");continue}let Y=o.stackSave(),V=o.stackAlloc(4*a),K=!1,re,O=0;try{o._OrtGetTensorData(Z,V,V+a,V+2*a,V+3*a)!==0&&vn(`Can't access output tensor data on index ${j}.`);let B=a===4?"i32":"i64",le=Number(o.getValue(V,B));O=o.getValue(V+a,"*");let pe=o.getValue(V+a*2,"*"),xe=Number(o.getValue(V+a*3,B)),he=[];for(let De=0;De<xe;De++)he.push(Number(o.getValue(pe+De*a,B)));o._OrtFree(pe)!==0&&vn("Can't free memory for tensor dims.");let me=he.reduce((De,Ne)=>De*Ne,1);re=wo(le);let Ce=p?.outputPreferredLocations[r[j]];if(re==="string"){if(Ce==="gpu-buffer"||Ce==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let De=[];for(let Ne=0;Ne<me;Ne++){let He=o.getValue(O+Ne*a,"*"),yt=o.getValue(O+(Ne+1)*a,"*"),Xe=Ne===me-1?void 0:yt-He;De.push(o.UTF8ToString(He,Xe))}G.push([re,he,De,"cpu"])}else if(Ce==="gpu-buffer"&&me>0){let De=o.jsepGetBuffer;if(!De)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ne=De(O),He=Rl(le,me);if(He===void 0||!Tw(re))throw new Error(`Unsupported data type: ${re}`);K=!0,G.push([re,he,{gpuBuffer:Ne,download:o.jsepCreateDownloader(Ne,He,re),dispose:()=>{o._OrtReleaseTensor(Z)!==0&&vn("Can't release tensor.")}},"gpu-buffer"])}else if(Ce==="ml-tensor"&&me>0){let De=o.webnnEnsureTensor,Ne=o.webnnIsGraphInputOutputTypeSupported;if(!De||!Ne)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Rl(le,me)===void 0||!Cw(re))throw new Error(`Unsupported data type: ${re}`);if(!Ne(t,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let He=await De(t,O,le,he,!1);K=!0,G.push([re,he,{mlTensor:He,download:o.webnnCreateMLTensorDownloader(O,re),dispose:()=>{o.webnnReleaseTensorId(O),o._OrtReleaseTensor(Z)}},"ml-tensor"])}else if(Ce==="ml-tensor-cpu-output"&&me>0){let De=o.webnnCreateMLTensorDownloader(O,re)(),Ne=G.length;K=!0,C.push((async()=>{let He=[Ne,await De];return o.webnnReleaseTensorId(O),o._OrtReleaseTensor(Z),He})()),G.push([re,he,[],"cpu"])}else{let De=Rg(re),Ne=new De(me);new Uint8Array(Ne.buffer,Ne.byteOffset,Ne.byteLength).set(o.HEAPU8.subarray(O,O+Ne.byteLength)),G.push([re,he,Ne,"cpu"])}}finally{o.stackRestore(Y),re==="string"&&O&&o._free(O),K||o._OrtReleaseTensor(Z)}}p&&!m&&(o._OrtClearBoundOutputs(p.handle)!==0&&vn("Can't clear bound outputs."),Ma.set(t,[d,f,h,p,m,!1]));for(let[j,Z]of await Promise.all(C))G[j][2]=Z;return $l("wasm ProcessOutputTensor"),G}finally{o.webnnOnRunEnd?.(d),o.stackRestore(k),S.forEach(L=>o._OrtReleaseTensor(L)),E.forEach(L=>o._OrtReleaseTensor(L)),T.forEach(L=>o._free(L)),v!==0&&o._OrtReleaseRunOptions(v),b.forEach(L=>o._free(L))}},jw=t=>{let e=Mn(),n=Ma.get(t);if(!n)throw new Error("invalid session id");let r=n[0],i=e._OrtEndProfiling(r);i===0&&vn("Can't get an profile file name."),e._OrtFree(i)},qw=t=>{let e=[];for(let n of t){let r=n[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Ta,Ai,sc,mf,gf,tm,tx,nm,bl,wl,kC,E$,M$,T$,C$,A$,R$,I$,P$=Ze(()=>{Bi(),S$(),Yl(),Sw(),Ta=()=>!!En.wasm.proxy&&typeof document<"u",sc=!1,mf=!1,gf=!1,nm=new Map,bl=(t,e)=>{let n=nm.get(t);n?n.push(e):nm.set(t,[e])},wl=()=>{if(sc||!mf||gf||!Ai)throw new Error("worker not ready")},kC=t=>{switch(t.data.type){case"init-wasm":sc=!1,t.data.err?(gf=!0,tx[1](t.data.err)):(mf=!0,tx[0]()),tm&&(URL.revokeObjectURL(tm),tm=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=nm.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},E$=async()=>{if(!mf){if(sc)throw new Error("multiple calls to 'initWasm()' detected.");if(gf)throw new Error("previous call to 'initWasm()' failed.");if(sc=!0,Ta())return new Promise((t,e)=>{Ai?.terminate(),wP().then(([n,r])=>{try{Ai=r,Ai.onerror=s=>e(s),Ai.onmessage=kC,tx=[t,e];let i={type:"init-wasm",in:En};!i.in.wasm.wasmPaths&&(n||g_)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-CVw3nYo7.wasm",import.meta.url).href}),Ai.postMessage(i),tm=n}catch(i){e(i)}},e)});try{await Ew(En.wasm),await Bw(En),mf=!0}catch(t){throw gf=!0,t}finally{sc=!1}}},M$=async t=>{if(Ta())return wl(),new Promise((e,n)=>{bl("init-ep",[e,n]);let r={type:"init-ep",in:{epName:t,env:En}};Ai.postMessage(r)});await Vw(En,t)},T$=async t=>Ta()?(wl(),new Promise((e,n)=>{bl("copy-from",[e,n]);let r={type:"copy-from",in:{buffer:t}};Ai.postMessage(r,[t.buffer])})):Hm(t),C$=async(t,e)=>{if(Ta()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return wl(),new Promise((n,r)=>{bl("create",[n,r]);let i={type:"create",in:{model:t,options:{...e}}},s=[];t instanceof Uint8Array&&s.push(t.buffer),Ai.postMessage(i,s)})}else return Hw(t,e)},A$=async t=>{if(Ta())return wl(),new Promise((e,n)=>{bl("release",[e,n]);let r={type:"release",in:t};Ai.postMessage(r)});Gw(t)},R$=async(t,e,n,r,i,s)=>{if(Ta()){if(n.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return wl(),new Promise((o,a)=>{bl("run",[o,a]);let u=n,d={type:"run",in:{sessionId:t,inputIndices:e,inputs:u,outputIndices:r,options:s}};Ai.postMessage(d,qw(u))})}else return Ww(t,e,n,r,i,s)},I$=async t=>{if(Ta())return wl(),new Promise((e,n)=>{bl("end-profiling",[e,n]);let r={type:"end-profiling",in:t};Ai.postMessage(r)});jw(t)}}),nx,DC,k$,s7=Ze(()=>{Bi(),P$(),$t(),ww(),TP(),nx=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},DC=t=>{switch(t[3]){case"cpu":return new ti(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Tw(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=t[2];return ti.fromGpuBuffer(n,{dataType:e,dims:t[1],download:r,dispose:i})}case"ml-tensor":{let e=t[0];if(!Cw(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=t[2];return ti.fromMLTensor(n,{dataType:e,dims:t[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${t[3]}`)}},k$=class{async fetchModelAndCopyToWasmMemory(t){return T$(await Aw(t))}async loadModel(t,e){Ks();let n;typeof t=="string"?n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await C$(n,e),ms()}async dispose(){return A$(this.sessionId)}async run(t,e,n){Ks();let r=[],i=[];Object.entries(t).forEach(h=>{let p=h[0],m=h[1],_=this.inputNames.indexOf(p);if(_===-1)throw new Error(`invalid input '${p}'`);r.push(m),i.push(_)});let s=[],o=[];Object.entries(e).forEach(h=>{let p=h[0],m=h[1],_=this.outputNames.indexOf(p);if(_===-1)throw new Error(`invalid output '${p}'`);s.push(m),o.push(_)});let a=r.map((h,p)=>nx(h,()=>`input "${this.inputNames[i[p]]}"`)),u=s.map((h,p)=>h?nx(h,()=>`output "${this.outputNames[o[p]]}"`):null),d=await R$(this.sessionId,i,a,o,u,n),f={};for(let h=0;h<d.length;h++)f[this.outputNames[o[h]]]=s[h]??DC(d[h]);return ms(),f}startProfiling(){}endProfiling(){I$(this.sessionId)}}}),D$={};Hc(D$,{OnnxruntimeWebAssemblyBackend:()=>P_,initializeFlags:()=>I_,wasmBackend:()=>$$});var I_,P_,$$,o7=Ze(()=>{Bi(),P$(),s7(),I_=()=>{(typeof En.wasm.initTimeout!="number"||En.wasm.initTimeout<0)&&(En.wasm.initTimeout=0);let t=En.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),En.wasm.simd=!1),typeof En.wasm.proxy!="boolean"&&(En.wasm.proxy=!1),typeof En.wasm.trace!="boolean"&&(En.wasm.trace=!1),typeof En.wasm.numThreads!="number"||!Number.isInteger(En.wasm.numThreads)||En.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)En.wasm.numThreads=1;else{let e=typeof navigator>"u"?WW("node:os").cpus().length:navigator.hardwareConcurrency;En.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},P_=class{async init(t){I_(),await E$(),await M$(t)}async createInferenceSessionHandler(t,e){let n=new k$;return await n.loadModel(t,e),n}},$$=new P_});Bi();Bi();Bi();var a7="1.24.2";{let t=(o7(),Vf(D$)).wasmBackend;lc("webgpu",t,5),lc("webnn",t,5),lc("cpu",t,10),lc("wasm",t,10)}Object.defineProperty(En.versions,"web",{value:a7,enumerable:!0});class l7{constructor(e,n={}){this.config=e,this.options=n,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)}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 n of Object.values(this.obsGroups))for(const r of n)r.reset&&r.reset(e);if(e){for(const[n,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[n]??[],e),s=this.historyBuffers[n];for(let o=0;o<r.steps;o++)s.set(i,o*i.length)}}}update(e){this.policyModule?.update();for(const n of Object.values(this.obsGroups))for(const r of n)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const n={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const o=this.buildFrame(i,e),a=this.historyBuffers[r];for(let u=a.length-1;u>=o.length;u--)a[u]=a[u-o.length];a.set(o,0),n[r]=new Float32Array(a)}else n[r]=this.buildFrame(i,e)}return n}collectObservations(e){const n=this.collectObservationsByKey(e);if(this.defaultObsKey&&n[this.defaultObsKey])return n[this.defaultObsKey];const r=Object.keys(n)[0];return r?n[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(n=>({...n}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(n=>({...n})):[]}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)}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 n=this.options.policyModules??{},r=this.config.policy_module,i=r?n[r]:n.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??{},n=this.config.obs_config??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(n)){if(Array.isArray(i)){const s=i.map(o=>{const a=e[o.name];if(!a)throw new Error(`Unknown observation type: ${o.name}`);return new a(this,o)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const o=s.components.map(d=>{const f=e[d.name];if(!f)throw new Error(`Unknown observation type: ${d.name}`);const h={...d,history_steps:1};return new f(this,h)}),a=Math.max(1,Math.floor(s.history_steps??1)),u=!!s.interleaved;this.registerGroup(r,o,s.components,{steps:a,interleaved:u})}}}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,n,r,i){this.obsGroups[e]=n,this.obsLayouts[e]=n.map((o,a)=>({name:r[a]?.name??`obs_${a}`,size:o.size}));const s=this.obsLayouts[e].reduce((o,a)=>o+a.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,n){const r=e.reduce((o,a)=>o+a.size,0),i=new Float32Array(r);let s=0;for(const o of e){const a=o.compute(n),u=a instanceof Float32Array?a:Float32Array.from(a);if(u.length!==o.size)throw new Error(`Observation size mismatch: expected ${o.size}, got ${u.length}`);i.set(u,s),s+=u.length}return i}normalizeArray(e,n,r){const i=new Float32Array(n);for(let s=0;s<n;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}En.wasm.proxy=!1;En.wasm.numThreads=1;class u7{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const n=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.inKeys=n.map(i=>Array.isArray(i)?i.join(","):i),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 n=await e.arrayBuffer();this.session=await bw.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}initInput(){return this.isRecurrent?{is_init:new ti("bool",[!0],[1]),adapt_hx:new ti("float32",new Float32Array(128),[1,128])}:{}}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const n={};for(let o=0;o<this.inKeys.length;o++){const a=this.inKeys[o],u=this.session.inputNames[o];if(!u||!e[a])throw new Error(`Missing ONNX input for key: ${a}`);n[u]=e[a]}const r=await this.session.run(n),i={};for(let o=0;o<this.outKeys.length;o++){const a=this.outKeys[o],u=this.session.outputNames[o];u&&r[u]&&(i[a]=r[u])}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]}}class c7{constructor(e,n,r,i){this.mujoco=e,this.mjModel=n,this.mjData=r;const s=this.getJointNames(n);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const o of i){const a=s.indexOf(o);if(a<0)throw new Error(`Joint "${o}" not found in MuJoCo model`);this.qposAdr.push(n.jnt_qposadr[a]),this.qvelAdr.push(n.jnt_dofadr[a]),this.jointIndices.push(a)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,n=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let d=0;d<this.numActions;d++)r[d]=e[this.qposAdr[d]],i[d]=n[this.qvelAdr[d]];const s=new Float32Array([e[0],e[1],e[2]]),o=new Float32Array([e[3],e[4],e[5],e[6]]),a=new Float32Array([n[0],n[1],n[2]]),u=new Float32Array([n[3],n[4],n[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:o,rootLinVel:a,rootAngVel:u}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,n=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?n.push(this.mjModel.actuator_trnid[2*i]):n.push(-1)}const r=[];for(const i of this.jointIndices){const s=n.findIndex(o=>o===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const n=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let o=e.name_jntadr[s],a=o;for(;a<n.length&&n[a]!==0;)a++;let u=r.decode(n.subarray(o,a));!u&&s===0&&(u="floating_base_joint"),i.push(u)}return i}}class N${constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class d7{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 n=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(n)],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 f7 extends N${constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const n=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:n};this.tracking=new d7(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class h7{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 n=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(n)],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 p7 extends N${constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const n=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:n};this.locomotion=new h7(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class m7{constructor(e,n,r={}){this.render=()=>{if(this.controls.update(),this.mjModel&&this.mjData&&this.bodies){rW(this.camera,this.lights);for(const[a,u]of this.lastSimState.bodies){const d=this.bodies[a];d&&(d.position.copy(u.position),d.quaternion.copy(u.quaternion),d.updateWorldMatrix(!0,!1))}nW(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&uW({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:a,height:u}=this.getSize();this.camera.aspect=a/u,this.camera.updateProjectionMatrix(),this.renderer.setSize(a,u)},this.mujoco=e,this.container=n,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(a){a&&typeof a=="object"&&"code"in a&&a.code!=="EEXIST"&&console.warn("Failed to create /working directory:",a)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(a){a&&typeof a=="object"&&"code"in a&&a.code!=="EEXIST"&&a.code!=="EBUSY"&&console.warn("Failed to mount MEMFS at /working:",a)}const{width:s,height:o}=this.getSize();this.scene=new I8,this.scene.name="scene",this.scene.background=new Ot(.15,.25,.35),this.camera=new ei(45,s/o,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new $G({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,o),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=_I,this.renderer.outputColorSpace=Ul,this.renderer.toneMapping=bI,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.controls=new LG(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:cW()},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.sceneCacheManager=m_.getInstance(this.mujoco),this.resourceTracker=new yW,this.memoryMonitor=new xW}async loadEnvironment(e,n=null){await this.stop();const r=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const i=performance.now()-r;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:i})}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.resourceTracker.startTracking(this.mujoco),await vW(this.mujoco,e,this.baseUrl),await this.loadScene(e),await this.captureAndCacheResources(e);await this.loadPolicyConfig(n),this.running=!0,this.startLoop()}initializeCommands(){const e=$i();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e){$i().registerCommandsFromConfig(e),console.log("[mjswanRuntime] Commands loaded from policy config:",Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log("[mjswanRuntime] Simulation reset")}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const n=this.scene.getObjectByName("MuJoCo Root");n&&this.scene.remove(n);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await gW(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),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=new Q3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls})),this.loadingScene=null})(),await this.loadingScene}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now();if(this.mjModel&&this.mjData){if(this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),o=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(o),this.policyDebugCounter%60===0){const a="policy"in o?"policy":"observation"in o?"observation":Object.keys(o)[0],u=a?o[a]:null,d=u?Array.from(u.slice(0,8)):[];console.log("[PolicyRunner] obs",{key:a,size:u?u.length:0,sample:d})}this.policyDebugCounter+=1}this.executeSimulationSteps(),this.updateCachedState()}const n=(performance.now()-e)/1e3,r=this.timestep*this.decimation,i=Math.max(0,r-n);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const n=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;const r=$i();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e){if(!this.mjModel||!this.mjData){console.warn("Policy config loaded before MuJoCo model is ready.");return}e!==n&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(i.commands&&typeof i.commands=="object"&&this.initializeCommandsFromConfig(i.commands),!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new l7(i,{policyModules:{tracking:f7,locomotion:p7},observations:BW});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData}),this.policyRunner=s,this.policyStateBuilder=new c7(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const o=this.policyStateBuilder.build();if(this.policyRunner.reset(o),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.onnx?.path){const a=this.resolvePolicyAssetPath(e,i.onnx.path),u=this.resolveAssetUrl(a),d={...i.onnx,path:u},f=new u7(d);await f.init(),this.onnxModule=f,this.onnxInputDict=f.initInput()}console.log("[PolicyRunner] config loaded",{obsSize:s.getObservationSize(),obsLayout:s.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(i){console.warn("Failed to load policy config:",i)}}}async fetchPolicyConfig(e){const n=this.resolveAssetUrl(e),r=await fetch(n,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:n}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const n=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(n,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,n){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${n}`.replace(/\/+/g,"/"):n}buildPolicyControl(e,n,r){const i=e.control_type??"joint_position";if(i!=="joint_position"&&i!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${i}`),null;const s=r.getControlMapping();if(!s)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const o=s.qposAdr.length,a=this.normalizeControlArray(e.action_scale,o,1),u=n.getDefaultJointPos(),d=this.normalizeControlArray(e.stiffness,o,0),f=this.normalizeControlArray(e.damping,o,0);return{controlType:i,...s,actionScale:a,defaultJointPos:u,kp:d,kd:f}}normalizeControlArray(e,n,r){const i=new Float32Array(n);if(typeof e=="number")return i.fill(e),i;if(Array.isArray(e)){for(let s=0;s<n;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}return i.fill(r),i}resetSimulationState(){!this.mjModel||!this.mjData||(this.mujoco.mj_resetData(this.mjModel,this.mjData),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{controlType:e,ctrlAdr:n,qposAdr:r,qvelAdr:i,actionScale:s,defaultJointPos:o,kp:a,kd:u}=this.policyControl,d=n.length,f=this.policyRunner?.getLastActions()??new Float32Array(d),h=this.mjData.ctrl;if(h.fill(0),e==="joint_position")for(let p=0;p<d;p++){const m=o[p]+s[p]*f[p],_=this.mjData.qpos[r[p]],x=this.mjData.qvel[i[p]],y=a[p]*(m-_)+u[p]*(0-x),v=n[p];v>=0&&(h[v]=y)}else if(e==="torque")for(let p=0;p<d;p++){const m=n[p];m>=0&&(h[m]=s[p]*f[p])}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const n={...this.onnxInputDict};for(const[u,d]of Object.entries(e))n[u]=new ti("float32",d,[1,d.length]);for(const u of this.onnxModule.inKeys)if(!n[u]){console.warn("[PolicyRunner] Missing ONNX input:",{key:u,available:Object.keys(n)});return}const[r,i]=await this.onnxModule.runInference(n);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i});const s=r.action??r.policy??null;if(!s)return;const o=s.data,a=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o);if(this.policyControl&&a.length!==this.policyControl.ctrlAdr.length){console.warn("[PolicyRunner] Action size mismatch:",{expected:this.policyControl.ctrlAdr.length,got:a.length});return}this.policyRunner.setLastActions(a)}catch(n){console.warn("[PolicyRunner] ONNX inference failed:",n)}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 n=e.bodyID;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(Ff(this.mjData.xpos,p,this.bodies[p].position),p_(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=Z3(r),s=this.dragStateManager.worldHit.clone(),o=Z3(s),a=new Ee(this.mjData.xpos[n*3+0],this.mjData.xpos[n*3+1],this.mjData.xpos[n*3+2]),u=new Ee(o.x-a.x,o.y-a.y,o.z-a.z),d=new Ee(i.x,i.y,i.z),f=new Ee().crossVectors(u,d),h=n*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]=f.x,this.mjData.xfrc_applied[h+4]=f.y,this.mjData.xfrc_applied[h+5]=f.z}updateCachedState(){if(!(!this.mjModel||!this.mjData||!this.bodies)){for(let e=0;e<this.mjModel.nbody;e++)if(this.bodies[e]){this.lastSimState.bodies.has(e)||this.lastSimState.bodies.set(e,{position:new Ee,quaternion:new Di});const n=this.lastSimState.bodies.get(e);Ff(this.mjData.xpos,e,n.position),p_(this.mjData.xquat,e,n.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&lW(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}}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.bodies=null,this.lights=[],this.mujocoRoot=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(n=>this.disposeMaterial(n)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const n=e;n.map&&n.map.dispose(),n.aoMap&&n.aoMap.dispose(),n.emissiveMap&&n.emissiveMap.dispose(),n.metalnessMap&&n.metalnessMap.dispose(),n.normalMap&&n.normalMap.dispose(),n.roughnessMap&&n.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,n=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,n)}}async restoreFromCache(e){const n=this.sceneCacheManager.get(e);if(!n)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=n.mjModel,this.mjData=n.mjData,this.bodies=n.bodies,this.lights=n.lights,this.mujocoRoot=n.mujocoRoot,this.scene.add(this.mujocoRoot),this.mujoco.mj_forward(this.mjModel,this.mjData),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=new Q3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls}))}async captureAndCacheResources(e){const n=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn("[SceneCache] Cannot cache scene: missing resources");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,fsFiles:n,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const g7=({scenePath:t,baseUrl:e,policyConfigPath:n,onStatusChange:r,onError:i,onReady:s})=>{const o=H.useRef(null),a=H.useRef(null),u=H.useRef(null);return H.useEffect(()=>{let d=!1;const f=p=>{r?.(p)};return(async()=>{if(f("Loading MuJoCo..."),!u.current){const y=await import("/assets/mujoco/mujoco_wasm.js".replace(/\/+/g,"/"));u.current=await y.default()}if(d)return;const p=o.current;if(!p)throw new Error("Failed to find viewer container.");const m=u.current;if(!m)throw new Error("MuJoCo not loaded.");a.current||(a.current=new m7(m,p,{baseUrl:e})),f("Loading scene assets..."),await a.current.loadEnvironment(t,n??null),!d&&(f("Running simulation"),s?.())})().catch(p=>{d||(console.error("Failed to initialize MuJoCo viewer:",p),i?.(p instanceof Error?p:new Error(String(p))),f("Failed to load scene"))}),()=>{d=!0,a.current?.dispose(),a.current=null}},[t,e,n,r,i,s]),q.jsx("div",{ref:o,className:"viewer"})};var v7={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 Ig=(t,e,n,r)=>{const i=H.forwardRef(({color:s="currentColor",size:o=24,stroke:a=2,title:u,className:d,children:f,...h},p)=>H.createElement("svg",{ref:p,...v7[t],width:o,height:o,className:["tabler-icon",`tabler-icon-${e}`,d].join(" "),strokeWidth:a,stroke:s,...h},[u&&H.createElement("title",{key:"svg-title"},u),...r.map(([m,_])=>H.createElement(m,_)),...Array.isArray(f)?f:[f]]));return i.displayName=`${n}`,i};const y7=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],L$=Ig("outline","chevron-down","ChevronDown",y7);const x7=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],_7=Ig("outline","chevron-up","ChevronUp",x7);const b7=[["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"}]],w7=Ig("outline","refresh","Refresh",b7);const S7=[["path",{d:"M6 6a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -4",key:"svg-0"}],["path",{d:"M12 2v2",key:"svg-1"}],["path",{d:"M9 12v9",key:"svg-2"}],["path",{d:"M15 12v9",key:"svg-3"}],["path",{d:"M5 16l4 -2",key:"svg-4"}],["path",{d:"M15 14l4 2",key:"svg-5"}],["path",{d:"M9 18h6",key:"svg-6"}],["path",{d:"M10 8v.01",key:"svg-7"}],["path",{d:"M14 8v.01",key:"svg-8"}]],E7=Ig("outline","robot","Robot",S7),M7={move:"touchmove",end:"touchend"},T7={move:"mousemove",end:"mouseup"};function C7(t){return t.type==="touchmove"}function A7(t){return t.type==="mousemove"}const eh=Dn.createContext(null);function So({children:t,width:e}){const n=Dn.useRef(null),[r,{toggle:i}]=qm(!0),[s,o]=Dn.useState(800),a=Dn.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),u=Dn.useRef({}),d=(m,_,x)=>Math.abs(m+_/2)<Math.abs(m-x+_/2)?m:m-x,f=15;function h(m,_){const x=n.current;if(x===null)return[m,_];const y=x.parentElement;if(y===null)return[m,_];let v=m,b=_;return v=Math.min(v,y.clientWidth-x.clientWidth-f),v=Math.max(v,f),b=Math.min(b,y.clientHeight-x.clientHeight-f),b=Math.max(b,f),x.style.top=`${b.toString()}px`,x.style.left=`${v.toString()}px`,[d(v,x.clientWidth,y.clientWidth),d(b,x.clientHeight,y.clientHeight)]}Dn.useEffect(()=>{const m=n.current;if(m===null)return;const _=m.parentElement;if(_===null)return;const x=new ResizeObserver(()=>{u.current.x===void 0&&(u.current.x=d(m.offsetLeft,m.clientWidth,_.clientWidth)),u.current.y===void 0&&(u.current.y=d(m.offsetTop,m.clientHeight,_.clientHeight));const y=_.clientHeight-f*2;s!==y&&o(y);let v=u.current.x,b=u.current.y;for(;v<0;)v+=_.clientWidth;for(;b<0;)b+=_.clientHeight;h(v,b)});return x.observe(m),x.observe(_),()=>{x.disconnect()}});const p=m=>{const _=a.current,x=n.current;if(!x)return;m.type=="touchstart"?(m=m,_.startClientX=m.touches[0].clientX,_.startClientY=m.touches[0].clientY):(m=m,_.startClientX=m.clientX,_.startClientY=m.clientY),_.startPosX=x.offsetLeft,_.startPosY=x.offsetTop;const y=m.type=="touchstart"?M7:T7;function v(b){let S=0,E=0;if(C7(b)?(b=b,S=b.touches[0].clientX-_.startClientX,E=b.touches[0].clientY-_.startClientY):A7(b)&&(b=b,S=b.clientX-_.startClientX,E=b.clientY-_.startClientY),Math.abs(S)<=3&&Math.abs(E)<=3)return;_.dragging=!0;const T=_.startPosX+S,A=_.startPosY+E;[u.current.x,u.current.y]=h(T,A)}window.addEventListener(y.move,v),window.addEventListener(y.end,()=>{m.type=="touchstart"&&(_.dragging=!1),window.removeEventListener(y.move,v)},{once:!0})};return q.jsx(eh.Provider,{value:{wrapperRef:n,expanded:r,width:e,maxHeight:s,toggleExpanded:i,dragHandler:p,dragInfo:a},children:q.jsx(Ll,{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:n,children:t})})}So.Handle=function({children:e}){const n=Dn.useContext(eh);return q.jsx(q.Fragment,{children:q.jsx(tt,{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=n.dragInfo.current;if(r.dragging){r.dragging=!1;return}n.toggleExpanded()},onTouchStart:r=>{n.dragHandler(r)},onMouseDown:r=>{n.dragHandler(r)},children:e})})};So.Contents=function({children:e}){const n=Dn.useContext(eh);return q.jsxs(bm,{in:n.expanded,children:[q.jsx(qf,{mx:"xs"}),q.jsx(ql.Autosize,{mah:n.maxHeight,children:q.jsx(tt,{style:{width:n.width},children:e})})]})};So.HideWhenCollapsed=function({children:e}){return Dn.useContext(eh)?.expanded??!0?e:null};So.HideWhenExpanded=function({children:e}){return Dn.useContext(eh)?.expanded??!0?null:e};function $C({id:t,label:e,children:n}){return q.jsx(tt,{pb:"0.5em",px:"xs",children:q.jsxs(hb,{align:"center",children:[q.jsx(tt,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:q.jsx(Na,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:q.jsx("label",{htmlFor:t,children:e})})}),q.jsx(tt,{style:{flexGrow:1},children:n})]})})}function R7({label:t,expandByDefault:e=!0,children:n}){const[r,{toggle:i}]=qm(e),s=r?_7:L$;return q.jsxs(Ll,{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:[q.jsxs(Ll,{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:[t,q.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),q.jsx(bm,{in:r,children:q.jsx(tt,{pt:"1em",children:n})}),q.jsx(bm,{in:!r,children:q.jsx(tt,{p:"xs"})})]})}function I7(t){return t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function P7({command:t,value:e,onChange:n,disabled:r}){const i=t.config;return q.jsxs(tt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[q.jsx(Na,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),q.jsx(tt,{style:{width:"50%"},children:q.jsx(Xb,{value:e,onChange:s=>n(t.id,s),min:i.min,max:i.max,step:i.step,size:"xs",disabled:r,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function k7(t){const{projects:e,projectValue:n,projectLabel:r,onProjectChange:i,scenes:s,sceneValue:o,onSceneChange:a,policies:u,policyValue:d,onPolicyChange:f,commandsEnabled:h=!1,onReset:p}=t,[m,_]=H.useState([]),[x,y]=H.useState([]),[v,b]=H.useState({});H.useEffect(()=>{const A=$i(),k=()=>{_(A.getCommands()),y(A.getCommandGroups()),b(A.getValues())};return k(),A.addEventListener(k),()=>{A.removeEventListener(k)}},[]);const S=H.useCallback((A,k)=>{$i().setValue(A,k),b(P=>({...P,[A]:k}))},[]),E=H.useCallback(()=>{$i().triggerButton("_system:reset"),p&&p()},[p]),T=A=>m.filter(k=>k.groupName===A&&k.config.type==="slider");return!e.length&&!s.length&&!u.length?null:q.jsxs(So,{width:"20em",children:[q.jsxs(So.Handle,{children:[q.jsx("div",{style:{width:"1.1em"}}),q.jsx(E7,{color:"#228be6",style:{position:"absolute",width:"1.25em",height:"1.25em"}}),q.jsx(So.HideWhenCollapsed,{children:q.jsxs(tt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[q.jsx("span",{style:{flexGrow:1},children:r}),e.length>1&&q.jsxs(Fr,{position:"bottom-start",offset:5,children:[q.jsx(Fr.Target,{children:q.jsx(tt,{onClick:A=>A.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center"},children:q.jsx(L$,{size:16})})}),q.jsx(Fr.Dropdown,{onClick:A=>A.stopPropagation(),children:e.map(A=>q.jsx(Fr.Item,{onClick:k=>{k.stopPropagation(),i(A.value)},style:{fontWeight:A.value===n?600:400,backgroundColor:A.value===n?"rgba(34, 139, 230, 0.1)":void 0},children:A.label},A.value))})]})]})}),q.jsx(So.HideWhenExpanded,{children:q.jsx(tt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:r})})]}),q.jsx(So.Contents,{children:q.jsxs(tt,{pt:"0.375em",children:[s.length>0&&q.jsx($C,{id:"scene-select",label:"Scene",children:q.jsx(kf,{id:"scene-select",placeholder:"Select scene",data:s,value:o,onChange:a,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),u.length>0&&q.jsx($C,{id:"policy-select",label:"Policy",children:q.jsx(kf,{id:"policy-select",placeholder:"Select policy",data:u,value:d,onChange:f,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),x.length>0&&m.filter(A=>A.config.type==="slider").length>0&&q.jsx(q.Fragment,{children:x.map(A=>{const k=T(A);return k.length===0?null:q.jsx(R7,{label:I7(A),expandByDefault:!0,children:k.map(I=>q.jsx(P7,{command:I,value:v[I.id]??0,onChange:S,disabled:!h},I.id))},A)})}),q.jsx(qf,{my:"xs",mx:"xs"}),q.jsx(tt,{px:"xs",pb:"xs",children:q.jsx(Nc,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:q.jsx(w7,{size:14}),onClick:E,children:"Reset"})})]})})]})}function vf(t,e,n){return Object.keys(t[e]).reduce((r,i)=>(r[i]=`var(--mantine-${n}-${i})`,r),{})}function NC(t,e){return t in e.breakpoints?e.breakpoints[t]:sx(t)}function D7(t){const e=lA(Zm,t),n=vf(e,"fontSizes","font-size"),r=vf(e,"lineHeights","line-height"),i=vf(e,"shadows","shadow"),s=vf(e,"radius","radius"),o=vf(e,"spacing","spacing"),a=Object.keys(e.headings.sizes).reduce((d,f)=>(d[f]={fontSize:`var(--mantine-${f}-font-size)`,lineHeight:`var(--mantine-${f}-line-height)`,fontWeight:`var(--mantine-${f}-font-weight)`},d),{}),u=Object.keys(e.colors).reduce((d,f)=>(d[f]={0:`var(--mantine-color-${f}-0)`,1:`var(--mantine-color-${f}-1)`,2:`var(--mantine-color-${f}-2)`,3:`var(--mantine-color-${f}-3)`,4:`var(--mantine-color-${f}-4)`,5:`var(--mantine-color-${f}-5)`,6:`var(--mantine-color-${f}-6)`,7:`var(--mantine-color-${f}-7)`,8:`var(--mantine-color-${f}-8)`,9:`var(--mantine-color-${f}-9)`,filled:`var(--mantine-color-${f}-filled)`,filledHover:`var(--mantine-color-${f}-filled-hover)`,light:`var(--mantine-color-${f}-light)`,lightHover:`var(--mantine-color-${f}-light-hover)`,lightColor:`var(--mantine-color-${f}-light-color)`,outline:`var(--mantine-color-${f}-outline)`,outlineHover:`var(--mantine-color-${f}-outline-hover)`},d),{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:n,lineHeights:r,shadows:i,radius:s,headings:a,spacing:o,colors:u,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:d=>`(max-width: ${NC(d,e)})`,largerThan:d=>`(min-width: ${NC(d,e)})`}}const k_={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Dc.extend({defaultProps:{radius:"xs"}}),ColorInput:Nb.extend({defaultProps:{radius:"xs"}}),Select:kf.extend({defaultProps:{radius:"sm"}}),Textarea:Ob.extend({defaultProps:{radius:"xs"}}),TextInput:Kb.extend({defaultProps:{radius:"xs"}}),NumberInput:Wb.extend({defaultProps:{radius:"xs"}}),Paper:Ll.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:kc.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:Nc.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};D7(k_);const O$=H.createContext(void 0),z$=()=>{const t=H.useContext(O$);if(!t)throw new Error("useLoading must be used within a LoadingProvider");return t},$7=({children:t})=>{const[e,n]=H.useState(!1),r=H.useRef(0),i=H.useCallback(()=>{r.current+=1,r.current>0&&n(!0)},[]),s=H.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&n(!1)},[]);return q.jsx(O$.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:t})},N7=()=>{const{isLoading:t}=z$();return t?q.jsx("div",{className:"loader-overlay",children:q.jsx("div",{className:"loader-content",children:q.jsx(Ic,{size:64,type:"bars"})})}):null},LC="0.0.10";function L7(){const[t,{open:e,close:n}]=qm(!1);return q.jsxs(q.Fragment,{children:[q.jsx(Xf,{label:`mjswan ${LC}`,children:q.jsx(tt,{style:{position:"absolute",bottom:"1em",left:"1em",cursor:"pointer",zIndex:100},component:"a",onClick:e,children:q.jsx(Rm,{src:"./logo.svg",style:{width:"2.5em",height:"auto"}})})}),q.jsx(ws,{opened:t,onClose:n,size:"md",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:q.jsxs(Im,{gap:"md",align:"center",children:[q.jsx(Rm,{src:"./logo.svg",style:{width:"5em",height:"auto"}}),q.jsx(Na,{size:"xl",fw:700,children:"mjswan"}),q.jsxs(Na,{size:"sm",c:"dimmed",children:["version ",LC]}),q.jsx(qf,{w:"100%"}),q.jsx(Na,{size:"sm",children:"Browser-based MuJoCo Playground with ONNX policies running entirely in the browser."}),q.jsx(Im,{gap:"xs",children:q.jsxs(tt,{pb:"lg",children:[q.jsx(Am,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",q.jsx(Am,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]})})]})})]})}function O7(){const t="/".replace(/\/+$/,"/");let n=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=t.replace(/^\/+|\/+$/g,"");if(r&&(n===r?n="":n.startsWith(`${r}/`)&&(n=n.slice(r.length+1))),!n)return null;const i=n.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function Xw(t){return t.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function z7(t,e){const n=t.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const m=new URL(h,p||window.location.href).toString();r.add(m)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,o=new URL(n,s).toString();i("assets/config.json",o);const u=window.location.pathname.split("/").filter(Boolean);u.length>0&&u[u.length-1]==="index.html"&&u.pop(),u.length>0&&u[u.length-1]===(e??"main")&&u.pop();const d=`/${u.join("/")}${u.length?"/":""}`,f=`${window.location.origin}${d}`;return i("assets/config.json",f),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function U7(t,e){const r=new URLSearchParams(window.location.search).get("config"),i=z7(t,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const o of i)try{const a=await fetch(o,{cache:"no-store"});if(!a.ok)throw new Error(`Failed to fetch ${o}: ${a.status}`);const u=await a.text(),d=u.trim();if((a.headers.get("content-type")||"").includes("text/html")||d.startsWith("<!doctype")||d.startsWith("<html"))throw new Error(`Received HTML from ${o}`);try{return JSON.parse(u)}catch(h){throw new Error(`Invalid JSON from ${o}: ${h instanceof Error?h.message:String(h)}`)}}catch(a){s=a instanceof Error?a:new Error(String(a))}throw s??new Error("Failed to load config.json.")}function OC(t,e){if(!t.scenes.length)return null;if(!e)return t.scenes[0];const n=e.trim().toLowerCase();return t.scenes.find(r=>r.name.toLowerCase()===n)||t.scenes.find(r=>Xw(r.name)===n)||t.scenes[0]}function zC(t,e){if(!t.policies.length)return null;if(!e)return t.policies[0].name;const n=e.trim().toLowerCase();return(t.policies.find(i=>i.name.toLowerCase()===n)||t.policies.find(i=>Xw(i.name)===n))?.name??t.policies[0].name}function rx(t,e,n){const i="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let s=i?`/${i}/`:"/";t&&t!=="main"&&(s+=`${t}/`);const o=new URLSearchParams;e&&o.set("scene",e),n&&o.set("policy",n);const a=s+(o.toString()?"?"+o.toString():"");window.history.replaceState({},"",a)}function F7(){const[t,e]=H.useState(null),[n,r]=H.useState(null),[i,s]=H.useState(null),[o,a]=H.useState(null),[u,d]=H.useState(null),{showLoading:f,hideLoading:h}=z$(),p=H.useMemo(()=>O7(),[]),m=H.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),_=H.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);H.useEffect(()=>{f(),U7("/",p).then(L=>{e(L);const G=L.projects.find(Z=>p===null?Z.id===null:Z.id===p);if(!G)throw new Error(`Project "${p??"(main)"}" not found in config.json.`);r(G);const C=OC(G,m);s(C);const j=C?zC(C,_):null;a(j)}).catch(L=>{console.error("Failed to load config:",L),d(L.message||"Failed to load config."),h()})},[p,m,_,f,h]);const x=H.useMemo(()=>{if(!n||!i)return null;const L=n.id?n.id:"main",G=i.path?i.path:`scene/${Xw(i.name)}/scene.xml`;return`${L}/assets/${G}`.replace(/\/+/g,"/")},[n,i]),y=H.useMemo(()=>!i||!o?null:i.policies.find(L=>L.name===o)??null,[i,o]),v=H.useMemo(()=>!n||!y?.config?null:`${n.id?n.id:"main"}/assets/${y.config}`.replace(/\/+/g,"/"),[n,y]),b=H.useMemo(()=>t?t.projects.map(L=>({value:L.id??"main",label:L.name||(L.id??"Main")})):[],[t]),S=H.useMemo(()=>n?n.scenes.map(L=>({value:L.name,label:L.name})):[],[n]),E=H.useMemo(()=>!i||!i.policies?[]:i.policies.map(L=>({value:L.name,label:L.name})),[i]),T=n?n.id??"main":null,A=i?.name??null,k=H.useCallback(L=>{d(L.message),h()},[h]),I=H.useCallback(()=>{h()},[h]),P=H.useCallback(L=>{if(!t||!L)return;const G=L==="main"?null:L,C=t.projects.find(Y=>(Y.id??"main")===(G??"main"));if(!C)return;f(),r(C);const j=OC(C,null);s(j);const Z=j?.policies?.[0]?.name??null;a(Z),rx(C.id,j?.name??null,Z)},[t,f]),$=H.useCallback(L=>{if(!n||!L)return;const G=n.scenes.find(j=>j.name===L);if(!G)return;f(),s(G);const C=zC(G,null);a(C),rx(n.id,L,C)},[n,f]),X=H.useCallback(L=>{L!==o&&f(),a(L),rx(n?.id??null,i?.name??null,L)},[n,i,o,f]);return u?q.jsx(ux,{theme:k_,defaultColorScheme:"dark",children:q.jsx("div",{className:"app",children:q.jsxs("div",{className:"hud hud-error",children:[q.jsx("h1",{className:"hud-title",children:"mjswan"}),q.jsx("p",{className:"hud-message",children:u})]})})}):!n||!i||!x?null:q.jsx(ux,{theme:k_,defaultColorScheme:"dark",children:q.jsxs("div",{className:"app",children:[q.jsx(N7,{}),q.jsx(L7,{})," ",q.jsx(k7,{projects:b,projectValue:T,projectLabel:n?.name??"mjswan",onProjectChange:P,scenes:S,sceneValue:A,onSceneChange:$,policies:E,policyValue:o,onPolicyChange:X,commandsEnabled:!!v}),q.jsx(g7,{scenePath:x,baseUrl:"/",policyConfigPath:v,onError:k,onReady:I})]})})}function B7(){return q.jsx($7,{children:q.jsx(F7,{})})}const UC=document.getElementById("root");UC&&CN.createRoot(UC).render(q.jsx(Dn.StrictMode,{children:q.jsx(B7,{})}));
6795
+ ${s}`,a=n.createShaderModule({code:o,label:t.name});on("verbose",()=>`[WebGPU] ${t.name} shader code: ${o}`);let u=n.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return ms(t.name),{programInfo:t,computePipeline:u,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(t){let e=typeof t=="number"?t:t.x,n=typeof t=="number"?1:t.y||1,r=typeof t=="number"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=i&&n<=i&&r<=i)return[e,n,r];let s=e*n*r,o=Math.ceil(Math.sqrt(s));if(o>i){if(o=Math.ceil(Math.cbrt(s)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),y$={};Hc(y$,{WebGpuBackend:()=>x$});var TC,CC,AC,x$,r7=Ze(()=>{Bi(),$t(),No(),IP(),hj(),t7(),n7(),TC=(t,e)=>{if(e.length!==t.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${t.length}.`);let n=[];for(let r=0;r<t.length;++r){let i=t[r].dataType;switch(e[r]){case"none":{n.push("");break}case"type":{n.push(`${i}`);break}case"rank":{let s=t[r].dims.length;n.push(`${i};${s}`);break}case"dims":{let s=t[r].dims.join(",");n.push(`${i};${s}`);break}default:throw new Error(`unsupported input dependency: ${e[r]}`)}}return n.join("|")},CC=(t,e,n)=>{let r=t.name;return t.shaderCache?.hint&&(r+="["+t.shaderCache.hint+"]"),r+=":"+n+`:${TC(e,t.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,r},AC=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},x$=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 t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,e){this.env=t;let n=[],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:n},i=s=>e.features.has(s)&&n.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 AC(e.info||await e.requestAdapterInfo()),this.gpuDataManager=DP(this),this.programManager=new v$(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Rw(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},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 t=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ks(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let r=0;r<e.length/2;r++){let i=n[r],s=i.kernelId,o=this.kernels.get(s),a=o.kernelType,u=o.kernelName,d=i.programName,f=i.inputTensorViews,h=i.outputTensorViews,p=e[r*2],m=e[r*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=p);let _=Number(p-this.queryTimeBase),x=Number(m-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(x))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:f.map(y=>({dims:y.dims,dataType:wo(y.dataType)})),outputsMetadata:h.map(y=>({dims:y.dims,dataType:wo(y.dataType)})),kernelId:s,kernelType:a,kernelName:u,programName:d,startTime:_,endTime:x});else{let y="";f.forEach((b,S)=>{y+=`input[${S}]: [${b.dims}] | ${wo(b.dataType)}, `});let v="";h.forEach((b,S)=>{v+=`output[${S}]: [${b.dims}] | ${wo(b.dataType)}, `}),console.log(`[profiling] kernel "${s}|${a}|${u}|${d}" ${y}${v}start time: ${_} ns, execution time: ${x-_} ns`)}Lm("GPU",`${d}::${p}::${m}`)}t.unmap(),this.pendingQueries.delete(t)}),ms()}run(t,e,n,r,i,s){Ks(t.name);let o=[];for(let b=0;b<e.length;++b){let S=e[b].data;if(S===0)continue;let E=this.gpuDataManager.get(S);if(!E)throw new Error(`no GPU data for input: ${S}`);o.push(E)}let{outputs:a,dispatchGroup:u,programUniforms:d}=t.getRunData(e),f=n.length===0?a.map((b,S)=>S):n;if(f.length!==a.length)throw new Error(`Output size ${f.length} must be equal to ${a.length}.`);let h=[],p=[];for(let b=0;b<a.length;++b){if(!Number.isInteger(f[b])||f[b]<-3||f[b]>=s)throw new Error(`Invalid output index: ${f[b]}`);if(f[b]===-3)continue;let S=f[b]===-1,E=f[b]===-2,T=S||E?i(a[b].dataType,a[b].dims):r(f[b],a[b].dataType,a[b].dims);if(h.push(T),T.data===0)continue;let A=this.gpuDataManager.get(T.data);if(!A)throw new Error(`no GPU data for output: ${T.data}`);if(S&&this.temporaryData.push(A),E){let k=this.kernelPersistentData.get(this.currentKernelId);k||(k=[],this.kernelPersistentData.set(this.currentKernelId,k)),k.push(A)}p.push(A)}if(o.length!==e.length||p.length!==h.length){if(p.length===0)return ms(t.name),h;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let m;if(d){let b=0,S=[];d.forEach(k=>{let I=typeof k.data=="number"?[k.data]:k.data;if(I.length===0)return;let P=k.type===10?2:4,$,X;k.type===10?(X=I.length>4?16:I.length>2?8:I.length*P,$=I.length>4?16:P*I.length):(X=I.length<=2?I.length*P:16,$=16),b=Math.ceil(b/X)*X,S.push(b);let L=k.type===10?8:4;b+=I.length>4?Math.ceil(I.length/L)*$:I.length*P});let E=16;b=Math.ceil(b/E)*E;let T=new ArrayBuffer(b);d.forEach((k,I)=>{let P=S[I],$=typeof k.data=="number"?[k.data]:k.data;if(k.type===6)new Int32Array(T,P,$.length).set($);else if(k.type===12)new Uint32Array(T,P,$.length).set($);else if(k.type===10)new Uint16Array(T,P,$.length).set($);else if(k.type===1)new Float32Array(T,P,$.length).set($);else throw new Error(`Unsupported uniform type: ${wo(k.type)}`)});let A=this.gpuDataManager.create(b,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(A.buffer,0,T,0,b),this.gpuDataManager.release(A.id),m={offset:0,size:b,buffer:A.buffer}}let _=this.programManager.normalizeDispatchGroupSize(u),x=_[1]===1&&_[2]===1,y=CC(t,e,x),v=this.programManager.getArtifact(y);if(v||(v=this.programManager.build(t,_),this.programManager.setArtifact(y,v),on("info",()=>`[artifact] key: ${y}, programName: ${t.name}`)),d&&v.uniformVariablesInfo){if(d.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${d.length} in program "${v.programInfo.name}".`);for(let b=0;b<d.length;b++){let S=d[b],E=S.type,T=typeof S.data=="number"?1:S.data.length,[A,k]=v.uniformVariablesInfo[b];if(E!==A||T!==k)throw new Error(`Uniform variable ${b} mismatch: expect type ${A} with size ${k}, got type ${E} with size ${T} in program "${v.programInfo.name}".`)}}if(on("info",()=>`[ProgramManager] run "${t.name}" (key=${y}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let b={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(b),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(b)}return this.programManager.run(v,o,p,_,m),ms(t.name),h}upload(t,e){this.gpuDataManager.upload(t,e)}memcpy(t,e){this.gpuDataManager.memcpy(t,e)}async download(t,e){await this.gpuDataManager.download(t,e)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,e,n,r){let i=g$.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let s={kernelType:t,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(e,s)}releaseKernel(t){let e=this.kernelPersistentData.get(t);if(e){for(let n of e)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,e,n){let r=this.kernels.get(t);if(!r)throw new Error(`kernel not created: ${t}`);let i=r.kernelType,s=r.kernelName,o=r.kernelEntry,a=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${s}" is not allowed to be called recursively`);this.currentKernelId=t,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),on("info",()=>`[WebGPU] Start to run kernel "[${i}] ${s}"...`);let u=this.env.debug;this.temporaryData=[];try{return u&&this.device.pushErrorScope("validation"),o(e,a[1]),0}catch(d){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${s}" failed. ${d}`)),1}finally{u&&n.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${i}] ${s}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,e,n,r){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let s=i.get(e),o=this.gpuDataManager.registerExternalBuffer(n,r,s);return i.set(e,[o,n]),o}unregisterBuffers(t){let e=this.sessionExternalDataMapping.get(t);e&&(e.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let e=this.gpuDataManager.get(t);if(!e)throw new Error(`no GPU data for buffer: ${t}`);return e.buffer}createDownloader(t,e,n){return async()=>{let r=await x_(this,t,e);return Iw(r.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}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(){on("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(){on("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){on("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let r=0;r<n;r++){let i=this.getComputePassEncoder(),s=t[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(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),_$={};Hc(_$,{init:()=>b$});var em,RC,b$,i7=Ze(()=>{$t(),No(),Gt(),fj(),em=class w${constructor(e,n,r,i){this.module=e,this.dataType=n,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 w$(this.module,this.dataType,this.data,e)}},RC=class{constructor(t,e,n){this.module=t,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let r=t.PTR_SIZE,i=n/t.PTR_SIZE,s=r===4?"i32":"i64";this.opKernelContext=Number(t.getValue(r*i++,s));let o=Number(t.getValue(r*i++,s));this.outputCount=Number(t.getValue(r*i++,s)),this.customDataOffset=Number(t.getValue(r*i++,"*")),this.customDataSize=Number(t.getValue(r*i++,s));let a=[];for(let u=0;u<o;u++){let d=Number(t.getValue(r*i++,s)),f=Number(t.getValue(r*i++,"*")),h=Number(t.getValue(r*i++,s)),p=[];for(let m=0;m<h;m++)p.push(Number(t.getValue(r*i++,s)));a.push(new em(t,d,f,p))}this.inputs=a}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(t,e){let n=e?.inputs?.map(o=>typeof o=="number"?this.inputs[o]:o)??this.inputs,r=e?.outputs??[],i=(o,a,u)=>new em(this.module,a,this.output(o,u),u),s=(o,a)=>{let u=Rl(o,a);if(!u)throw new Error(`Unsupported data type: ${o}`);let d=u>0?this.backend.gpuDataManager.create(u).id:0;return new em(this.module,o,d,a)};return this.backend.run(t,n,r,i,s,this.outputCount)}output(t,e){let n=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 o=0;o<e.length;o++)this.module.setValue(s+r*(o+1),e[o],i);return this.module._JsepOutput(this.opKernelContext,t,s)}catch(r){throw new Error(`Failed to generate kernel's output[${t}] 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(n)}}},b$=async(t,e,n,r)=>{let i=e.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let s=(r7(),Vf(y$)).WebGpuBackend,o=new s;await o.initialize(n,r),i("webgpu",[o,a=>o.alloc(Number(a)),a=>o.free(a),(a,u,d,f=!1)=>{if(f)on("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(u)}, size=${Number(d)}`),o.memcpy(Number(a),Number(u));else{on("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(u)}, size=${Number(d)}`);let h=e.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(d));o.upload(Number(u),h)}},async(a,u,d)=>{on("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${u}, size=${d}`),await o.download(Number(a),()=>e.HEAPU8.subarray(Number(u)>>>0,Number(u+d)>>>0))},(a,u,d)=>o.createKernel(a,Number(u),d,e.UTF8ToString(e._JsepGetNodeName(Number(u)))),a=>o.releaseKernel(a),(a,u,d,f)=>{on("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${a}, contextDataOffset=${u}`);let h=new RC(e,o,Number(u));return o.computeKernel(Number(a),h,f)},()=>o.captureBegin(),()=>o.captureEnd(),()=>o.replay()])}else{let s=new kP(n);i("webnn",[s,()=>s.reserveTensorId(),o=>s.releaseTensorId(o),async(o,a,u,d,f)=>s.ensureTensor(o,a,u,d,f),(o,a)=>{s.uploadTensor(o,a)},async(o,a)=>s.downloadTensor(o,a),(o,a)=>s.registerMLContext(o,a),!!n.trace])}}}),IC,Bw,Vw,Ma,PC,Qy,Hm,Hw,Gw,ex,Ww,jw,qw,S$=Ze(()=>{Bi(),uj(),cj(),$t(),Yl(),Mw(),TP(),IC=(t,e)=>{Mn()._OrtInit(t,e)!==0&&vn("Can't initialize onnxruntime.")},Bw=async t=>{IC(t.wasm.numThreads,zm(t.logLevel))},Vw=async(t,e)=>{Mn().asyncInit?.();let n=t.webgpu.adapter;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let r=t.webgpu.powerPreference;if(r!==void 0&&r!=="low-power"&&r!=="high-performance")throw new Error(`Invalid powerPreference setting: "${r}"`);let i=t.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:r,forceFallbackAdapter:i}),!n)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=(i7(),Vf(_$)).init;e==="webgpu"&&await r("webgpu",Mn(),t,n),e==="webnn"&&await r("webnn",Mn(),t)}},Ma=new Map,PC=t=>{let e=Mn(),n=e.stackSave();try{let r=e.PTR_SIZE,i=e.stackAlloc(2*r);e._OrtGetInputOutputCount(t,i,i+r)!==0&&vn("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(n)}},Qy=(t,e)=>{let n=Mn(),r=n.stackSave(),i=0;try{let s=n.PTR_SIZE,o=n.stackAlloc(2*s);n._OrtGetInputOutputMetadata(t,e,o,o+s)!==0&&vn("Can't get session input/output metadata.");let a=Number(n.getValue(o,"*"));i=Number(n.getValue(o+s,"*"));let u=n.HEAP32[i/4];if(u===0)return[a,0];let d=n.HEAPU32[i/4+1],f=[];for(let h=0;h<d;h++){let p=Number(n.getValue(i+8+h*s,"*"));f.push(p!==0?n.UTF8ToString(p):Number(n.getValue(i+8+(h+d)*s,"*")))}return[a,u,f]}finally{n.stackRestore(r),i!==0&&n._OrtFree(i)}},Hm=t=>{let e=Mn(),n=e._malloc(t.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return e.HEAPU8.set(t,n),[n,t.byteLength]},Hw=async(t,e)=>{let n,r,i=Mn();Array.isArray(t)?[n,r]=t:t.buffer===i.HEAPU8.buffer?[n,r]=[t.byteOffset,t.byteLength]:[n,r]=Hm(t);let s=0,o=0,a=0,u=[],d=[],f=[];try{if([o,u]=await MP(e),e?.externalData&&i.mountExternalData){let E=[];for(let T of e.externalData){let A=typeof T=="string"?T:T.path;E.push(Aw(typeof T=="string"?T:T.data).then(k=>{i.mountExternalData(A,k)}))}await Promise.all(E)}for(let E of e?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof E!="string"){let T=E,A=T?.context,k=T?.gpuDevice,I=T?.deviceType,P=T?.powerPreference;A?i.currentContext=A:k?i.currentContext=await i.webnnCreateMLContext(k):i.currentContext=await i.webnnCreateMLContext({deviceType:I,powerPreference:P})}else i.currentContext=await i.webnnCreateMLContext();break}s=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(s),s===0&&vn("Can't create a session."),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(s,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[h,p]=PC(s),m=!!e?.enableGraphCapture,_=[],x=[],y=[],v=[],b=[];for(let E=0;E<h;E++){let[T,A,k]=Qy(s,E);T===0&&vn("Can't get an input name."),d.push(T);let I=i.UTF8ToString(T);_.push(I),y.push(A===0?{name:I,isTensor:!1}:{name:I,isTensor:!0,type:wo(A),shape:k})}for(let E=0;E<p;E++){let[T,A,k]=Qy(s,E+h);T===0&&vn("Can't get an output name."),f.push(T);let I=i.UTF8ToString(T);x.push(I),v.push(A===0?{name:I,isTensor:!1}:{name:I,isTensor:!0,type:wo(A),shape:k});{if(m&&e?.preferredOutputLocation===void 0){b.push("gpu-buffer");continue}let P=typeof e?.preferredOutputLocation=="string"?e.preferredOutputLocation:e?.preferredOutputLocation?.[I]??"cpu",$=i.webnnIsGraphOutput;if(P==="cpu"&&$&&$(s,I)){b.push("ml-tensor-cpu-output");continue}if(P!=="cpu"&&P!=="cpu-pinned"&&P!=="gpu-buffer"&&P!=="ml-tensor")throw new Error(`Not supported preferred output location: ${P}.`);if(m&&P!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${P}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);b.push(P)}}let S=null;return b.some(E=>E==="gpu-buffer"||E==="ml-tensor"||E==="ml-tensor-cpu-output")&&(a=i._OrtCreateBinding(s),a===0&&vn("Can't create IO binding."),S={handle:a,outputPreferredLocations:b,outputPreferredLocationsEncoded:b.map(E=>E==="ml-tensor-cpu-output"?"ml-tensor":E).map(E=>v_(E))}),Ma.set(s,[s,d,f,S,m,!1]),[s,_,x,y,v]}catch(h){throw d.forEach(p=>i._OrtFree(p)),f.forEach(p=>i._OrtFree(p)),a!==0&&i._OrtReleaseBinding(a)!==0&&vn("Can't release IO binding."),s!==0&&i._OrtReleaseSession(s)!==0&&vn("Can't release session."),h}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&vn("Can't release session options."),u.forEach(h=>i._free(h)),i.unmountExternalData?.()}},Gw=t=>{let e=Mn(),n=Ma.get(t);if(!n)throw new Error(`cannot release session. invalid session id: ${t}`);let[r,i,s,o,a]=n;o&&(a&&e._OrtClearBoundOutputs(o.handle)!==0&&vn("Can't clear bound outputs."),e._OrtReleaseBinding(o.handle)!==0&&vn("Can't release IO binding.")),e.jsepOnReleaseSession?.(t),e.webnnOnReleaseSession?.(t),e.webgpuOnReleaseSession?.(t),i.forEach(u=>e._OrtFree(u)),s.forEach(u=>e._OrtFree(u)),e._OrtReleaseSession(r)!==0&&vn("Can't release session."),Ma.delete(t)},ex=async(t,e,n,r,i,s,o=!1)=>{if(!t){e.push(0);return}let a=Mn(),u=a.PTR_SIZE,d=t[0],f=t[1],h=t[3],p=h,m,_;if(d==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(o&&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 v=t[2].gpuBuffer;_=Rl(Al(d),f);{let b=a.jsepRegisterBuffer;if(!b)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');m=b(r,s,v,_)}}else if(h==="ml-tensor"){let v=t[2].mlTensor;_=Rl(Al(d),f);let b=a.webnnRegisterMLTensor;if(!b)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');m=b(r,v,Al(d),f)}else{let v=t[2];if(Array.isArray(v)){_=u*v.length,m=a._malloc(_),n.push(m);for(let b=0;b<v.length;b++){if(typeof v[b]!="string")throw new TypeError(`tensor data at index ${b} is not a string`);a.setValue(m+b*u,us(v[b],n),"*")}}else{let b=a.webnnIsGraphInput,S=a.webnnIsGraphOutput;if(d!=="string"&&b&&S){let E=a.UTF8ToString(i);if(b(r,E)||S(r,E)){let T=Al(d);_=Rl(T,f),p="ml-tensor";let A=a.webnnCreateTemporaryTensor,k=a.webnnUploadTensor;if(!A||!k)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let I=await A(r,T,f);k(I,new Uint8Array(v.buffer,v.byteOffset,v.byteLength)),m=I}else _=v.byteLength,m=a._malloc(_),n.push(m),a.HEAPU8.set(new Uint8Array(v.buffer,v.byteOffset,_),m)}else _=v.byteLength,m=a._malloc(_),n.push(m),a.HEAPU8.set(new Uint8Array(v.buffer,v.byteOffset,_),m)}}let x=a.stackSave(),y=a.stackAlloc(4*f.length);try{f.forEach((b,S)=>a.setValue(y+S*u,b,u===4?"i32":"i64"));let v=a._OrtCreateTensor(Al(d),m,_,y,f.length,v_(p));v===0&&vn(`Can't create tensor for input/output. session=${r}, index=${s}.`),e.push(v)}finally{a.stackRestore(x)}},Ww=async(t,e,n,r,i,s)=>{let o=Mn(),a=o.PTR_SIZE,u=Ma.get(t);if(!u)throw new Error(`cannot run inference. invalid session id: ${t}`);let d=u[0],f=u[1],h=u[2],p=u[3],m=u[4],_=u[5],x=e.length,y=r.length,v=0,b=[],S=[],E=[],T=[],A=[],k=o.stackSave(),I=o.stackAlloc(x*a),P=o.stackAlloc(x*a),$=o.stackAlloc(y*a),X=o.stackAlloc(y*a);try{[v,b]=EP(s),Dl("wasm prepareInputOutputTensor");for(let j=0;j<x;j++)await ex(n[j],S,T,t,f[e[j]],e[j],m);for(let j=0;j<y;j++)await ex(i[j],E,T,t,h[r[j]],x+r[j],m);$l("wasm prepareInputOutputTensor");for(let j=0;j<x;j++)o.setValue(I+j*a,S[j],"*"),o.setValue(P+j*a,f[e[j]],"*");for(let j=0;j<y;j++)o.setValue($+j*a,E[j],"*"),o.setValue(X+j*a,h[r[j]],"*");if(p&&!_){let{handle:j,outputPreferredLocations:Z,outputPreferredLocationsEncoded:Y}=p;if(f.length!==x)throw new Error(`input count from feeds (${x}) is expected to be always equal to model's input count (${f.length}).`);Dl("wasm bindInputsOutputs");for(let V=0;V<x;V++){let K=e[V];await o._OrtBindInput(j,f[K],S[V])!==0&&vn(`Can't bind input[${V}] for session=${t}.`)}for(let V=0;V<y;V++){let K=r[V];i[V]?.[3]?(A.push(E[V]),o._OrtBindOutput(j,h[K],E[V],0)!==0&&vn(`Can't bind pre-allocated output[${V}] for session=${t}.`)):o._OrtBindOutput(j,h[K],0,Y[K])!==0&&vn(`Can't bind output[${V}] to ${Z[V]} for session=${t}.`)}$l("wasm bindInputsOutputs"),Ma.set(t,[d,f,h,p,m,!0])}o.jsepOnRunStart?.(d),o.webnnOnRunStart?.(d);let L;p?L=await o._OrtRunWithBinding(d,p.handle,y,$,v):L=await o._OrtRun(d,P,I,x,X,y,$,v),L!==0&&vn("failed to call OrtRun().");let G=[],C=[];Dl("wasm ProcessOutputTensor");for(let j=0;j<y;j++){let Z=Number(o.getValue($+j*a,"*"));if(Z===E[j]||A.includes(E[j])){G.push(i[j]),Z!==E[j]&&o._OrtReleaseTensor(Z)!==0&&vn("Can't release tensor.");continue}let Y=o.stackSave(),V=o.stackAlloc(4*a),K=!1,re,O=0;try{o._OrtGetTensorData(Z,V,V+a,V+2*a,V+3*a)!==0&&vn(`Can't access output tensor data on index ${j}.`);let B=a===4?"i32":"i64",le=Number(o.getValue(V,B));O=o.getValue(V+a,"*");let pe=o.getValue(V+a*2,"*"),xe=Number(o.getValue(V+a*3,B)),he=[];for(let De=0;De<xe;De++)he.push(Number(o.getValue(pe+De*a,B)));o._OrtFree(pe)!==0&&vn("Can't free memory for tensor dims.");let me=he.reduce((De,Ne)=>De*Ne,1);re=wo(le);let Ce=p?.outputPreferredLocations[r[j]];if(re==="string"){if(Ce==="gpu-buffer"||Ce==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let De=[];for(let Ne=0;Ne<me;Ne++){let He=o.getValue(O+Ne*a,"*"),yt=o.getValue(O+(Ne+1)*a,"*"),Xe=Ne===me-1?void 0:yt-He;De.push(o.UTF8ToString(He,Xe))}G.push([re,he,De,"cpu"])}else if(Ce==="gpu-buffer"&&me>0){let De=o.jsepGetBuffer;if(!De)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ne=De(O),He=Rl(le,me);if(He===void 0||!Tw(re))throw new Error(`Unsupported data type: ${re}`);K=!0,G.push([re,he,{gpuBuffer:Ne,download:o.jsepCreateDownloader(Ne,He,re),dispose:()=>{o._OrtReleaseTensor(Z)!==0&&vn("Can't release tensor.")}},"gpu-buffer"])}else if(Ce==="ml-tensor"&&me>0){let De=o.webnnEnsureTensor,Ne=o.webnnIsGraphInputOutputTypeSupported;if(!De||!Ne)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Rl(le,me)===void 0||!Cw(re))throw new Error(`Unsupported data type: ${re}`);if(!Ne(t,re,!1))throw new Error(`preferredLocation "ml-tensor" for ${re} output is not supported by current WebNN Context.`);let He=await De(t,O,le,he,!1);K=!0,G.push([re,he,{mlTensor:He,download:o.webnnCreateMLTensorDownloader(O,re),dispose:()=>{o.webnnReleaseTensorId(O),o._OrtReleaseTensor(Z)}},"ml-tensor"])}else if(Ce==="ml-tensor-cpu-output"&&me>0){let De=o.webnnCreateMLTensorDownloader(O,re)(),Ne=G.length;K=!0,C.push((async()=>{let He=[Ne,await De];return o.webnnReleaseTensorId(O),o._OrtReleaseTensor(Z),He})()),G.push([re,he,[],"cpu"])}else{let De=Rg(re),Ne=new De(me);new Uint8Array(Ne.buffer,Ne.byteOffset,Ne.byteLength).set(o.HEAPU8.subarray(O,O+Ne.byteLength)),G.push([re,he,Ne,"cpu"])}}finally{o.stackRestore(Y),re==="string"&&O&&o._free(O),K||o._OrtReleaseTensor(Z)}}p&&!m&&(o._OrtClearBoundOutputs(p.handle)!==0&&vn("Can't clear bound outputs."),Ma.set(t,[d,f,h,p,m,!1]));for(let[j,Z]of await Promise.all(C))G[j][2]=Z;return $l("wasm ProcessOutputTensor"),G}finally{o.webnnOnRunEnd?.(d),o.stackRestore(k),S.forEach(L=>o._OrtReleaseTensor(L)),E.forEach(L=>o._OrtReleaseTensor(L)),T.forEach(L=>o._free(L)),v!==0&&o._OrtReleaseRunOptions(v),b.forEach(L=>o._free(L))}},jw=t=>{let e=Mn(),n=Ma.get(t);if(!n)throw new Error("invalid session id");let r=n[0],i=e._OrtEndProfiling(r);i===0&&vn("Can't get an profile file name."),e._OrtFree(i)},qw=t=>{let e=[];for(let n of t){let r=n[2];!Array.isArray(r)&&"buffer"in r&&e.push(r.buffer)}return e}}),Ta,Ai,sc,mf,gf,tm,tx,nm,bl,wl,kC,E$,M$,T$,C$,A$,R$,I$,P$=Ze(()=>{Bi(),S$(),Yl(),Sw(),Ta=()=>!!En.wasm.proxy&&typeof document<"u",sc=!1,mf=!1,gf=!1,nm=new Map,bl=(t,e)=>{let n=nm.get(t);n?n.push(e):nm.set(t,[e])},wl=()=>{if(sc||!mf||gf||!Ai)throw new Error("worker not ready")},kC=t=>{switch(t.data.type){case"init-wasm":sc=!1,t.data.err?(gf=!0,tx[1](t.data.err)):(mf=!0,tx[0]()),tm&&(URL.revokeObjectURL(tm),tm=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=nm.get(t.data.type);t.data.err?e.shift()[1](t.data.err):e.shift()[0](t.data.out);break}}},E$=async()=>{if(!mf){if(sc)throw new Error("multiple calls to 'initWasm()' detected.");if(gf)throw new Error("previous call to 'initWasm()' failed.");if(sc=!0,Ta())return new Promise((t,e)=>{Ai?.terminate(),wP().then(([n,r])=>{try{Ai=r,Ai.onerror=s=>e(s),Ai.onmessage=kC,tx=[t,e];let i={type:"init-wasm",in:En};!i.in.wasm.wasmPaths&&(n||g_)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-CVw3nYo7.wasm",import.meta.url).href}),Ai.postMessage(i),tm=n}catch(i){e(i)}},e)});try{await Ew(En.wasm),await Bw(En),mf=!0}catch(t){throw gf=!0,t}finally{sc=!1}}},M$=async t=>{if(Ta())return wl(),new Promise((e,n)=>{bl("init-ep",[e,n]);let r={type:"init-ep",in:{epName:t,env:En}};Ai.postMessage(r)});await Vw(En,t)},T$=async t=>Ta()?(wl(),new Promise((e,n)=>{bl("copy-from",[e,n]);let r={type:"copy-from",in:{buffer:t}};Ai.postMessage(r,[t.buffer])})):Hm(t),C$=async(t,e)=>{if(Ta()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return wl(),new Promise((n,r)=>{bl("create",[n,r]);let i={type:"create",in:{model:t,options:{...e}}},s=[];t instanceof Uint8Array&&s.push(t.buffer),Ai.postMessage(i,s)})}else return Hw(t,e)},A$=async t=>{if(Ta())return wl(),new Promise((e,n)=>{bl("release",[e,n]);let r={type:"release",in:t};Ai.postMessage(r)});Gw(t)},R$=async(t,e,n,r,i,s)=>{if(Ta()){if(n.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return wl(),new Promise((o,a)=>{bl("run",[o,a]);let u=n,d={type:"run",in:{sessionId:t,inputIndices:e,inputs:u,outputIndices:r,options:s}};Ai.postMessage(d,qw(u))})}else return Ww(t,e,n,r,i,s)},I$=async t=>{if(Ta())return wl(),new Promise((e,n)=>{bl("end-profiling",[e,n]);let r={type:"end-profiling",in:t};Ai.postMessage(r)});jw(t)}}),nx,DC,k$,s7=Ze(()=>{Bi(),P$(),$t(),ww(),TP(),nx=(t,e)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[t.type,t.dims,{mlTensor:t.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${t.location} for ${e()}`)}},DC=t=>{switch(t[3]){case"cpu":return new ti(t[0],t[2],t[1]);case"gpu-buffer":{let e=t[0];if(!Tw(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=t[2];return ti.fromGpuBuffer(n,{dataType:e,dims:t[1],download:r,dispose:i})}case"ml-tensor":{let e=t[0];if(!Cw(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=t[2];return ti.fromMLTensor(n,{dataType:e,dims:t[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${t[3]}`)}},k$=class{async fetchModelAndCopyToWasmMemory(t){return T$(await Aw(t))}async loadModel(t,e){Ks();let n;typeof t=="string"?n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await C$(n,e),ms()}async dispose(){return A$(this.sessionId)}async run(t,e,n){Ks();let r=[],i=[];Object.entries(t).forEach(h=>{let p=h[0],m=h[1],_=this.inputNames.indexOf(p);if(_===-1)throw new Error(`invalid input '${p}'`);r.push(m),i.push(_)});let s=[],o=[];Object.entries(e).forEach(h=>{let p=h[0],m=h[1],_=this.outputNames.indexOf(p);if(_===-1)throw new Error(`invalid output '${p}'`);s.push(m),o.push(_)});let a=r.map((h,p)=>nx(h,()=>`input "${this.inputNames[i[p]]}"`)),u=s.map((h,p)=>h?nx(h,()=>`output "${this.outputNames[o[p]]}"`):null),d=await R$(this.sessionId,i,a,o,u,n),f={};for(let h=0;h<d.length;h++)f[this.outputNames[o[h]]]=s[h]??DC(d[h]);return ms(),f}startProfiling(){}endProfiling(){I$(this.sessionId)}}}),D$={};Hc(D$,{OnnxruntimeWebAssemblyBackend:()=>P_,initializeFlags:()=>I_,wasmBackend:()=>$$});var I_,P_,$$,o7=Ze(()=>{Bi(),P$(),s7(),I_=()=>{(typeof En.wasm.initTimeout!="number"||En.wasm.initTimeout<0)&&(En.wasm.initTimeout=0);let t=En.wasm.simd;if(typeof t!="boolean"&&t!==void 0&&t!=="fixed"&&t!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${t}". Reset it to \`false\` and ignore SIMD feature checking.`),En.wasm.simd=!1),typeof En.wasm.proxy!="boolean"&&(En.wasm.proxy=!1),typeof En.wasm.trace!="boolean"&&(En.wasm.trace=!1),typeof En.wasm.numThreads!="number"||!Number.isInteger(En.wasm.numThreads)||En.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)En.wasm.numThreads=1;else{let e=typeof navigator>"u"?WW("node:os").cpus().length:navigator.hardwareConcurrency;En.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},P_=class{async init(t){I_(),await E$(),await M$(t)}async createInferenceSessionHandler(t,e){let n=new k$;return await n.loadModel(t,e),n}},$$=new P_});Bi();Bi();Bi();var a7="1.24.2";{let t=(o7(),Vf(D$)).wasmBackend;lc("webgpu",t,5),lc("webnn",t,5),lc("cpu",t,10),lc("wasm",t,10)}Object.defineProperty(En.versions,"web",{value:a7,enumerable:!0});class l7{constructor(e,n={}){this.config=e,this.options=n,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)}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 n of Object.values(this.obsGroups))for(const r of n)r.reset&&r.reset(e);if(e){for(const[n,r]of Object.entries(this.historyConfig))if(r.steps>1){const i=this.buildFrame(this.obsGroups[n]??[],e),s=this.historyBuffers[n];for(let o=0;o<r.steps;o++)s.set(i,o*i.length)}}}update(e){this.policyModule?.update();for(const n of Object.values(this.obsGroups))for(const r of n)r.update&&r.update(e)}collectObservationsByKey(e){this.update(e);const n={};for(const[r,i]of Object.entries(this.obsGroups)){const s=this.historyConfig[r];if(s&&s.steps>1){const o=this.buildFrame(i,e),a=this.historyBuffers[r];for(let u=a.length-1;u>=o.length;u--)a[u]=a[u-o.length];a.set(o,0),n[r]=new Float32Array(a)}else n[r]=this.buildFrame(i,e)}return n}collectObservations(e){const n=this.collectObservationsByKey(e);if(this.defaultObsKey&&n[this.defaultObsKey])return n[this.defaultObsKey];const r=Object.keys(n)[0];return r?n[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(n=>({...n}));const e=Object.keys(this.obsLayouts)[0];return e?this.obsLayouts[e].map(n=>({...n})):[]}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)}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 n=this.options.policyModules??{},r=this.config.policy_module,i=r?n[r]:n.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??{},n=this.config.obs_config??{};this.obsGroups={},this.obsLayouts={},this.obsSizes={},this.historyConfig={},this.historyBuffers={},this.defaultObsKey=null;for(const[r,i]of Object.entries(n)){if(Array.isArray(i)){const s=i.map(o=>{const a=e[o.name];if(!a)throw new Error(`Unknown observation type: ${o.name}`);return new a(this,o)});this.registerGroup(r,s,i);continue}if(i&&typeof i=="object"){const s=i;if(Array.isArray(s.components)){const o=s.components.map(d=>{const f=e[d.name];if(!f)throw new Error(`Unknown observation type: ${d.name}`);const h={...d,history_steps:1};return new f(this,h)}),a=Math.max(1,Math.floor(s.history_steps??1)),u=!!s.interleaved;this.registerGroup(r,o,s.components,{steps:a,interleaved:u})}}}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,n,r,i){this.obsGroups[e]=n,this.obsLayouts[e]=n.map((o,a)=>({name:r[a]?.name??`obs_${a}`,size:o.size}));const s=this.obsLayouts[e].reduce((o,a)=>o+a.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,n){const r=e.reduce((o,a)=>o+a.size,0),i=new Float32Array(r);let s=0;for(const o of e){const a=o.compute(n),u=a instanceof Float32Array?a:Float32Array.from(a);if(u.length!==o.size)throw new Error(`Observation size mismatch: expected ${o.size}, got ${u.length}`);i.set(u,s),s+=u.length}return i}normalizeArray(e,n,r){const i=new Float32Array(n);for(let s=0;s<n;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}}En.wasm.proxy=!1;En.wasm.numThreads=1;class u7{constructor(e){if(!e?.path)throw new Error("OnnxModule requires a path.");this.config=e,this.session=null;const n=e.meta?.in_keys??["policy"],r=e.meta?.out_keys??["action"];this.inKeys=n.map(i=>Array.isArray(i)?i.join(","):i),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 n=await e.arrayBuffer();this.session=await bw.create(n,{executionProviders:["wasm"],graphOptimizationLevel:"all"})}initInput(){return this.isRecurrent?{is_init:new ti("bool",[!0],[1]),adapt_hx:new ti("float32",new Float32Array(128),[1,128])}:{}}async runInference(e){if(!this.session)throw new Error("OnnxModule not initialized.");const n={};for(let o=0;o<this.inKeys.length;o++){const a=this.inKeys[o],u=this.session.inputNames[o];if(!u||!e[a])throw new Error(`Missing ONNX input for key: ${a}`);n[u]=e[a]}const r=await this.session.run(n),i={};for(let o=0;o<this.outKeys.length;o++){const a=this.outKeys[o],u=this.session.outputNames[o];u&&r[u]&&(i[a]=r[u])}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]}}class c7{constructor(e,n,r,i){this.mujoco=e,this.mjModel=n,this.mjData=r;const s=this.getJointNames(n);this.qposAdr=[],this.qvelAdr=[],this.jointIndices=[],this.ctrlAdr=null;for(const o of i){const a=s.indexOf(o);if(a<0)throw new Error(`Joint "${o}" not found in MuJoCo model`);this.qposAdr.push(n.jnt_qposadr[a]),this.qvelAdr.push(n.jnt_dofadr[a]),this.jointIndices.push(a)}this.numActions=i.length,this.ctrlAdr=this.buildCtrlAdr()}build(){const e=this.mjData.qpos,n=this.mjData.qvel,r=new Float32Array(this.numActions),i=new Float32Array(this.numActions);for(let d=0;d<this.numActions;d++)r[d]=e[this.qposAdr[d]],i[d]=n[this.qvelAdr[d]];const s=new Float32Array([e[0],e[1],e[2]]),o=new Float32Array([e[3],e[4],e[5],e[6]]),a=new Float32Array([n[0],n[1],n[2]]),u=new Float32Array([n[3],n[4],n[5]]);return{jointPos:r,jointVel:i,rootPos:s,rootQuat:o,rootLinVel:a,rootAngVel:u}}getControlMapping(){return this.ctrlAdr?{ctrlAdr:this.ctrlAdr.slice(),qposAdr:this.qposAdr.slice(),qvelAdr:this.qvelAdr.slice()}:null}buildCtrlAdr(){if(this.mjModel.nu<=0)return null;const e=this.mujoco.mjtTrn?.mjTRN_JOINT?.value,n=[];for(let i=0;i<this.mjModel.nu;i++){const s=this.mjModel.actuator_trntype[i];e===void 0||s===e?n.push(this.mjModel.actuator_trnid[2*i]):n.push(-1)}const r=[];for(const i of this.jointIndices){const s=n.findIndex(o=>o===i);if(s<0)return null;r.push(s)}return r}getJointNames(e){const n=new Uint8Array(e.names),r=new TextDecoder,i=[];for(let s=0;s<e.njnt;s++){let o=e.name_jntadr[s],a=o;for(;a<n.length&&n[a]!==0;)a++;let u=r.decode(n.subarray(o,a));!u&&s===0&&(u="floating_base_joint"),i.push(u)}return i}}class N${constructor(e){this.config=e,this.context=null}init(e){this.context=e}reset(){}update(){}getContext(){return{}}}class d7{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 n=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(n)],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 f7 extends N${constructor(e){super(e),this.tracking=null}async init(e){await super.init(e);const n=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:n};this.tracking=new d7(r)}reset(e){this.tracking?.reset(e)}update(){this.tracking?.advance()}getContext(){return{tracking:this.tracking}}}class h7{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 n=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(n)],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 p7 extends N${constructor(e){super(e),this.locomotion=null}async init(e){await super.init(e);const n=this.config.policy_joint_names??[],r={...this.config.tracking,policy_joint_names:n};this.locomotion=new h7(r)}reset(e){this.locomotion?.reset(e)}update(){this.locomotion?.advance()}getContext(){return{tracking:this.locomotion}}}class m7{constructor(e,n,r={}){this.render=()=>{if(this.controls.update(),this.mjModel&&this.mjData&&this.bodies){rW(this.camera,this.lights);for(const[a,u]of this.lastSimState.bodies){const d=this.bodies[a];d&&(d.position.copy(u.position),d.quaternion.copy(u.quaternion),d.updateWorldMatrix(!0,!1))}nW(this.mujoco,this.mjData,this.lights),this.mujocoRoot&&this.mujocoRoot.cylinders&&uW({cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}this.renderer.render(this.scene,this.camera)},this.onWindowResize=()=>{const{width:a,height:u}=this.getSize();this.camera.aspect=a/u,this.camera.updateProjectionMatrix(),this.renderer.setSize(a,u)},this.mujoco=e,this.container=n,this.baseUrl=r.baseUrl||"/";const i="/working";try{this.mujoco.FS.mkdir(i)}catch(a){a&&typeof a=="object"&&"code"in a&&a.code!=="EEXIST"&&console.warn("Failed to create /working directory:",a)}try{this.mujoco.FS.mount(this.mujoco.MEMFS,{root:"."},i)}catch(a){a&&typeof a=="object"&&"code"in a&&a.code!=="EEXIST"&&a.code!=="EBUSY"&&console.warn("Failed to mount MEMFS at /working:",a)}const{width:s,height:o}=this.getSize();this.scene=new I8,this.scene.name="scene",this.scene.background=new Ot(.15,.25,.35),this.camera=new ei(45,s/o,.001,1e3),this.camera.name="PerspectiveCamera",this.camera.position.set(2,1.7,1.7),this.scene.add(this.camera),this.renderer=new $G({antialias:!0}),this.renderer.xr.enabled=!0,this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(s,o),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=_I,this.renderer.outputColorSpace=Ul,this.renderer.toneMapping=bI,this.renderer.toneMappingExposure=1,this.container.appendChild(this.renderer.domElement),this.controls=new LG(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:cW()},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.sceneCacheManager=m_.getInstance(this.mujoco),this.resourceTracker=new yW,this.memoryMonitor=new xW}async loadEnvironment(e,n=null){await this.stop();const r=performance.now();if(this.initializeCommands(),this.sceneCacheManager.has(e)){await this.restoreFromCache(e);const i=performance.now()-r;this.memoryMonitor.logCacheOperation("hit",e,{elapsedMs:i})}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.resourceTracker.startTracking(this.mujoco),await vW(this.mujoco,e,this.baseUrl),await this.loadScene(e),await this.captureAndCacheResources(e);await this.loadPolicyConfig(n),this.running=!0,this.startLoop()}initializeCommands(){const e=$i();e.clear(),e.setResetCallback(()=>this.resetSimulation())}initializeCommandsFromConfig(e){$i().registerCommandsFromConfig(e),console.log("[mjswanRuntime] Commands loaded from policy config:",Object.keys(e))}resetSimulation(){if(this.resetSimulationState(),this.policyRunner&&this.policyStateBuilder){const e=this.policyStateBuilder.build();this.policyRunner.reset(e)}console.log("[mjswanRuntime] Simulation reset")}async loadScene(e){this.loadingScene&&await this.loadingScene,this.loadingScene=(async()=>{const n=this.scene.getObjectByName("MuJoCo Root");n&&this.scene.remove(n);const r={mjModel:this.mjModel,mjData:this.mjData,scene:this.scene};if([this.mjModel,this.mjData,this.bodies,this.lights]=await gW(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),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=new Q3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls})),this.loadingScene=null})(),await this.loadingScene}async startLoop(){return this.loopPromise?this.loopPromise:(this.running=!0,this.loopPromise=this.mainLoop(),this.loopPromise)}async stop(){this.running=!1;const e=this.loopPromise;e&&await e,this.loopPromise=null}async mainLoop(){for(;this.running;){const e=performance.now();if(this.mjModel&&this.mjData){if(this.policyRunner&&this.policyStateBuilder){const s=this.policyStateBuilder.build(),o=this.policyRunner.collectObservationsByKey(s);if(await this.runOnnxInference(o),this.policyDebugCounter%60===0){const a="policy"in o?"policy":"observation"in o?"observation":Object.keys(o)[0],u=a?o[a]:null,d=u?Array.from(u.slice(0,8)):[];console.log("[PolicyRunner] obs",{key:a,size:u?u.length:0,sample:d})}this.policyDebugCounter+=1}this.executeSimulationSteps(),this.updateCachedState()}const n=(performance.now()-e)/1e3,r=this.timestep*this.decimation,i=Math.max(0,r-n);i>0&&await new Promise(s=>setTimeout(s,i*1e3))}this.loopPromise=null}async loadPolicyConfig(e){const n=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;const r=$i();if(r.clear(),r.setResetCallback(()=>this.resetSimulation()),!!e){if(!this.mjModel||!this.mjData){console.warn("Policy config loaded before MuJoCo model is ready.");return}e!==n&&this.resetSimulationState();try{const{config:i}=await this.fetchPolicyConfig(e);if(i.commands&&typeof i.commands=="object"&&this.initializeCommandsFromConfig(i.commands),!i.policy_joint_names||i.policy_joint_names.length===0)throw new Error("Policy config missing policy_joint_names.");const s=new l7(i,{policyModules:{tracking:f7,locomotion:p7},observations:BW});await s.init({mujoco:this.mujoco,mjModel:this.mjModel,mjData:this.mjData}),this.policyRunner=s,this.policyStateBuilder=new c7(this.mujoco,this.mjModel,this.mjData,s.getPolicyJointNames());const o=this.policyStateBuilder.build();if(this.policyRunner.reset(o),this.policyControl=this.buildPolicyControl(i,s,this.policyStateBuilder),i.onnx?.path){const a=this.resolvePolicyAssetPath(e,i.onnx.path),u=this.resolveAssetUrl(a),d={...i.onnx,path:u},f=new u7(d);await f.init(),this.onnxModule=f,this.onnxInputDict=f.initInput()}console.log("[PolicyRunner] config loaded",{obsSize:s.getObservationSize(),obsLayout:s.getObservationLayout(),pdEnabled:this.policyControl!==null})}catch(i){console.warn("Failed to load policy config:",i)}}}async fetchPolicyConfig(e){const n=this.resolveAssetUrl(e),r=await fetch(n,{cache:"no-store"});if(!r.ok)throw new Error(`Failed to fetch policy config: ${r.status}`);return{config:await r.json(),resolvedUrl:n}}resolveAssetUrl(e){if(/^[a-z]+:\/\//i.test(e))return e;const n=(this.baseUrl||"/").replace(/\/+$/,"/"),r=new URL(n,window.location.origin+"/").toString();return new URL(e.replace(/^\/+/,""),r).toString()}resolvePolicyAssetPath(e,n){const r=e.replace(/\\/g,"/"),i=r.lastIndexOf("/");return i>=0?`${r.slice(0,i+1)}${n}`.replace(/\/+/g,"/"):n}buildPolicyControl(e,n,r){const i=e.control_type??"joint_position";if(i!=="joint_position"&&i!=="torque")return console.warn(`[PolicyRunner] Unsupported control_type: ${i}`),null;const s=r.getControlMapping();if(!s)return console.warn("[PolicyRunner] Failed to build control mapping."),null;const o=s.qposAdr.length,a=this.normalizeControlArray(e.action_scale,o,1),u=n.getDefaultJointPos(),d=this.normalizeControlArray(e.stiffness,o,0),f=this.normalizeControlArray(e.damping,o,0);return{controlType:i,...s,actionScale:a,defaultJointPos:u,kp:d,kd:f}}normalizeControlArray(e,n,r){const i=new Float32Array(n);if(typeof e=="number")return i.fill(e),i;if(Array.isArray(e)){for(let s=0;s<n;s++)i[s]=typeof e[s]=="number"?e[s]:r;return i}return i.fill(r),i}resetSimulationState(){!this.mjModel||!this.mjData||(this.mujoco.mj_resetData(this.mjModel,this.mjData),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{controlType:e,ctrlAdr:n,qposAdr:r,qvelAdr:i,actionScale:s,defaultJointPos:o,kp:a,kd:u}=this.policyControl,d=n.length,f=this.policyRunner?.getLastActions()??new Float32Array(d),h=this.mjData.ctrl;if(h.fill(0),e==="joint_position")for(let p=0;p<d;p++){const m=o[p]+s[p]*f[p],_=this.mjData.qpos[r[p]],x=this.mjData.qvel[i[p]],y=a[p]*(m-_)+u[p]*(0-x),v=n[p];v>=0&&(h[v]=y)}else if(e==="torque")for(let p=0;p<d;p++){const m=n[p];m>=0&&(h[m]=s[p]*f[p])}}async runOnnxInference(e){if(!(!this.onnxModule||!this.policyRunner||this.onnxInferencing)){this.onnxInferencing=!0;try{this.onnxInputDict||(this.onnxInputDict=this.onnxModule.initInput());const n={...this.onnxInputDict};for(const[u,d]of Object.entries(e))n[u]=new ti("float32",d,[1,d.length]);for(const u of this.onnxModule.inKeys)if(!n[u]){console.warn("[PolicyRunner] Missing ONNX input:",{key:u,available:Object.keys(n)});return}const[r,i]=await this.onnxModule.runInference(n);Object.keys(i).length>0&&(this.onnxInputDict={...this.onnxInputDict,...i});const s=r.action??r.policy??null;if(!s)return;const o=s.data,a=ArrayBuffer.isView(o)?new Float32Array(o):Float32Array.from(o);if(this.policyControl&&a.length!==this.policyControl.ctrlAdr.length){console.warn("[PolicyRunner] Action size mismatch:",{expected:this.policyControl.ctrlAdr.length,got:a.length});return}this.policyRunner.setLastActions(a)}catch(n){console.warn("[PolicyRunner] ONNX inference failed:",n)}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 n=e.bodyID;for(let p=0;p<this.mjModel.nbody;p++)this.bodies[p]&&(Ff(this.mjData.xpos,p,this.bodies[p].position),p_(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=Z3(r),s=this.dragStateManager.worldHit.clone(),o=Z3(s),a=new Ee(this.mjData.xpos[n*3+0],this.mjData.xpos[n*3+1],this.mjData.xpos[n*3+2]),u=new Ee(o.x-a.x,o.y-a.y,o.z-a.z),d=new Ee(i.x,i.y,i.z),f=new Ee().crossVectors(u,d),h=n*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]=f.x,this.mjData.xfrc_applied[h+4]=f.y,this.mjData.xfrc_applied[h+5]=f.z}updateCachedState(){if(!(!this.mjModel||!this.mjData||!this.bodies)){for(let e=0;e<this.mjModel.nbody;e++)if(this.bodies[e]){this.lastSimState.bodies.has(e)||this.lastSimState.bodies.set(e,{position:new Ee,quaternion:new Di});const n=this.lastSimState.bodies.get(e);Ff(this.mjData.xpos,e,n.position),p_(this.mjData.xquat,e,n.quaternion)}this.mujocoRoot&&this.mujocoRoot.cylinders&&lW(this.mjModel,this.mjData,{cylinders:this.mujocoRoot.cylinders,spheres:this.mujocoRoot.spheres},this.lastSimState.tendons)}}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.bodies=null,this.lights=[],this.mujocoRoot=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(n=>this.disposeMaterial(n)):this.disposeMaterial(e.material))});this.scene.children.length>0;)this.scene.remove(this.scene.children[0])}disposeMaterial(e){const n=e;n.map&&n.map.dispose(),n.aoMap&&n.aoMap.dispose(),n.emissiveMap&&n.emissiveMap.dispose(),n.metalnessMap&&n.metalnessMap.dispose(),n.normalMap&&n.normalMap.dispose(),n.roughnessMap&&n.roughnessMap.dispose(),e.dispose()}getSize(){const e=this.container.clientWidth||window.innerWidth,n=this.container.clientHeight||window.innerHeight;return{width:Math.max(1,e),height:Math.max(1,n)}}async restoreFromCache(e){const n=this.sceneCacheManager.get(e);if(!n)throw new Error(`Scene ${e} not found in cache`);const r=this.scene.getObjectByName("MuJoCo Root");r&&this.scene.remove(r),this.mjModel=n.mjModel,this.mjData=n.mjData,this.bodies=n.bodies,this.lights=n.lights,this.mujocoRoot=n.mujocoRoot,this.scene.add(this.mujocoRoot),this.mujoco.mj_forward(this.mjModel,this.mjData),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=new Q3({scene:this.scene,renderer:this.renderer,camera:this.camera,container:this.container,controls:this.controls}))}async captureAndCacheResources(e){const n=this.resourceTracker.stopTracking(this.mujoco);if(!this.mjModel||!this.mjData||!this.bodies||!this.mujocoRoot){console.warn("[SceneCache] Cannot cache scene: missing resources");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,fsFiles:n,estimatedMemoryBytes:r});const i=this.sceneCacheManager.getMetrics();this.memoryMonitor.logCacheOperation("load",e,{memoryMB:r/1048576,totalScenes:i.totalScenes,totalMemoryMB:i.totalMemoryBytes/1048576})}}const g7=({scenePath:t,baseUrl:e,policyConfigPath:n,onStatusChange:r,onError:i,onReady:s})=>{const o=H.useRef(null),a=H.useRef(null),u=H.useRef(null);return H.useEffect(()=>{let d=!1;const f=p=>{r?.(p)};return(async()=>{if(f("Loading MuJoCo..."),!u.current){const y=await import("/assets/mujoco/mujoco_wasm.js".replace(/\/+/g,"/"));u.current=await y.default()}if(d)return;const p=o.current;if(!p)throw new Error("Failed to find viewer container.");const m=u.current;if(!m)throw new Error("MuJoCo not loaded.");a.current||(a.current=new m7(m,p,{baseUrl:e})),f("Loading scene assets..."),await a.current.loadEnvironment(t,n??null),!d&&(f("Running simulation"),s?.())})().catch(p=>{d||(console.error("Failed to initialize MuJoCo viewer:",p),i?.(p instanceof Error?p:new Error(String(p))),f("Failed to load scene"))}),()=>{d=!0,a.current?.dispose(),a.current=null}},[t,e,n,r,i,s]),q.jsx("div",{ref:o,className:"viewer"})};var v7={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 Ig=(t,e,n,r)=>{const i=H.forwardRef(({color:s="currentColor",size:o=24,stroke:a=2,title:u,className:d,children:f,...h},p)=>H.createElement("svg",{ref:p,...v7[t],width:o,height:o,className:["tabler-icon",`tabler-icon-${e}`,d].join(" "),strokeWidth:a,stroke:s,...h},[u&&H.createElement("title",{key:"svg-title"},u),...r.map(([m,_])=>H.createElement(m,_)),...Array.isArray(f)?f:[f]]));return i.displayName=`${n}`,i};const y7=[["path",{d:"M6 9l6 6l6 -6",key:"svg-0"}]],L$=Ig("outline","chevron-down","ChevronDown",y7);const x7=[["path",{d:"M6 15l6 -6l6 6",key:"svg-0"}]],_7=Ig("outline","chevron-up","ChevronUp",x7);const b7=[["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"}]],w7=Ig("outline","refresh","Refresh",b7);const S7=[["path",{d:"M6 6a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v4a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2l0 -4",key:"svg-0"}],["path",{d:"M12 2v2",key:"svg-1"}],["path",{d:"M9 12v9",key:"svg-2"}],["path",{d:"M15 12v9",key:"svg-3"}],["path",{d:"M5 16l4 -2",key:"svg-4"}],["path",{d:"M15 14l4 2",key:"svg-5"}],["path",{d:"M9 18h6",key:"svg-6"}],["path",{d:"M10 8v.01",key:"svg-7"}],["path",{d:"M14 8v.01",key:"svg-8"}]],E7=Ig("outline","robot","Robot",S7),M7={move:"touchmove",end:"touchend"},T7={move:"mousemove",end:"mouseup"};function C7(t){return t.type==="touchmove"}function A7(t){return t.type==="mousemove"}const eh=Dn.createContext(null);function So({children:t,width:e}){const n=Dn.useRef(null),[r,{toggle:i}]=qm(!0),[s,o]=Dn.useState(800),a=Dn.useRef({dragging:!1,startPosX:0,startPosY:0,startClientX:0,startClientY:0}),u=Dn.useRef({}),d=(m,_,x)=>Math.abs(m+_/2)<Math.abs(m-x+_/2)?m:m-x,f=15;function h(m,_){const x=n.current;if(x===null)return[m,_];const y=x.parentElement;if(y===null)return[m,_];let v=m,b=_;return v=Math.min(v,y.clientWidth-x.clientWidth-f),v=Math.max(v,f),b=Math.min(b,y.clientHeight-x.clientHeight-f),b=Math.max(b,f),x.style.top=`${b.toString()}px`,x.style.left=`${v.toString()}px`,[d(v,x.clientWidth,y.clientWidth),d(b,x.clientHeight,y.clientHeight)]}Dn.useEffect(()=>{const m=n.current;if(m===null)return;const _=m.parentElement;if(_===null)return;const x=new ResizeObserver(()=>{u.current.x===void 0&&(u.current.x=d(m.offsetLeft,m.clientWidth,_.clientWidth)),u.current.y===void 0&&(u.current.y=d(m.offsetTop,m.clientHeight,_.clientHeight));const y=_.clientHeight-f*2;s!==y&&o(y);let v=u.current.x,b=u.current.y;for(;v<0;)v+=_.clientWidth;for(;b<0;)b+=_.clientHeight;h(v,b)});return x.observe(m),x.observe(_),()=>{x.disconnect()}});const p=m=>{const _=a.current,x=n.current;if(!x)return;m.type=="touchstart"?(m=m,_.startClientX=m.touches[0].clientX,_.startClientY=m.touches[0].clientY):(m=m,_.startClientX=m.clientX,_.startClientY=m.clientY),_.startPosX=x.offsetLeft,_.startPosY=x.offsetTop;const y=m.type=="touchstart"?M7:T7;function v(b){let S=0,E=0;if(C7(b)?(b=b,S=b.touches[0].clientX-_.startClientX,E=b.touches[0].clientY-_.startClientY):A7(b)&&(b=b,S=b.clientX-_.startClientX,E=b.clientY-_.startClientY),Math.abs(S)<=3&&Math.abs(E)<=3)return;_.dragging=!0;const T=_.startPosX+S,A=_.startPosY+E;[u.current.x,u.current.y]=h(T,A)}window.addEventListener(y.move,v),window.addEventListener(y.end,()=>{m.type=="touchstart"&&(_.dragging=!1),window.removeEventListener(y.move,v)},{once:!0})};return q.jsx(eh.Provider,{value:{wrapperRef:n,expanded:r,width:e,maxHeight:s,toggleExpanded:i,dragHandler:p,dragInfo:a},children:q.jsx(Ll,{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:n,children:t})})}So.Handle=function({children:e}){const n=Dn.useContext(eh);return q.jsx(q.Fragment,{children:q.jsx(tt,{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=n.dragInfo.current;if(r.dragging){r.dragging=!1;return}n.toggleExpanded()},onTouchStart:r=>{n.dragHandler(r)},onMouseDown:r=>{n.dragHandler(r)},children:e})})};So.Contents=function({children:e}){const n=Dn.useContext(eh);return q.jsxs(bm,{in:n.expanded,children:[q.jsx(qf,{mx:"xs"}),q.jsx(ql.Autosize,{mah:n.maxHeight,children:q.jsx(tt,{style:{width:n.width},children:e})})]})};So.HideWhenCollapsed=function({children:e}){return Dn.useContext(eh)?.expanded??!0?e:null};So.HideWhenExpanded=function({children:e}){return Dn.useContext(eh)?.expanded??!0?null:e};function $C({id:t,label:e,children:n}){return q.jsx(tt,{pb:"0.5em",px:"xs",children:q.jsxs(hb,{align:"center",children:[q.jsx(tt,{pr:"xs",style:{width:"7.25em",flexShrink:0,position:"relative"},children:q.jsx(Na,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"100%",boxSizing:"content-box"},children:q.jsx("label",{htmlFor:t,children:e})})}),q.jsx(tt,{style:{flexGrow:1},children:n})]})})}function R7({label:t,expandByDefault:e=!0,children:n}){const[r,{toggle:i}]=qm(e),s=r?_7:L$;return q.jsxs(Ll,{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:[q.jsxs(Ll,{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:[t,q.jsx(s,{style:{width:"0.9em",height:"0.9em",strokeWidth:3,top:"0.1em",position:"relative",marginLeft:"0.25em",marginRight:"-0.1em",opacity:.5}})]}),q.jsx(bm,{in:r,children:q.jsx(tt,{pt:"1em",children:n})}),q.jsx(bm,{in:!r,children:q.jsx(tt,{p:"xs"})})]})}function I7(t){return t.split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function P7({command:t,value:e,onChange:n,disabled:r}){const i=t.config;return q.jsxs(tt,{pb:"0.5em",px:"xs",style:{display:"flex",alignItems:"center"},children:[q.jsx(Na,{c:"dimmed",style:{fontSize:"0.875em",fontWeight:450,lineHeight:"1.375em",letterSpacing:"-0.75px",width:"50%",flexShrink:0},children:i.label}),q.jsx(tt,{style:{width:"50%"},children:q.jsx(Xb,{value:e,onChange:s=>n(t.id,s),min:i.min,max:i.max,step:i.step,size:"xs",disabled:r,styles:{root:{padding:"0"},track:{height:4},thumb:{width:12,height:12}}})})]})}function k7(t){const{projects:e,projectValue:n,projectLabel:r,onProjectChange:i,scenes:s,sceneValue:o,onSceneChange:a,policies:u,policyValue:d,onPolicyChange:f,commandsEnabled:h=!1,onReset:p}=t,[m,_]=H.useState([]),[x,y]=H.useState([]),[v,b]=H.useState({});H.useEffect(()=>{const A=$i(),k=()=>{_(A.getCommands()),y(A.getCommandGroups()),b(A.getValues())};return k(),A.addEventListener(k),()=>{A.removeEventListener(k)}},[]);const S=H.useCallback((A,k)=>{$i().setValue(A,k),b(P=>({...P,[A]:k}))},[]),E=H.useCallback(()=>{$i().triggerButton("_system:reset"),p&&p()},[p]),T=A=>m.filter(k=>k.groupName===A&&k.config.type==="slider");return!e.length&&!s.length&&!u.length?null:q.jsxs(So,{width:"20em",children:[q.jsxs(So.Handle,{children:[q.jsx("div",{style:{width:"1.1em"}}),q.jsx(E7,{color:"#228be6",style:{position:"absolute",width:"1.25em",height:"1.25em"}}),q.jsx(So.HideWhenCollapsed,{children:q.jsxs(tt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px",display:"flex",alignItems:"center",gap:"0.5em"},pt:"0.1em",children:[q.jsx("span",{style:{flexGrow:1},children:r}),e.length>1&&q.jsxs(Fr,{position:"bottom-start",offset:5,children:[q.jsx(Fr.Target,{children:q.jsx(tt,{onClick:A=>A.stopPropagation(),style:{cursor:"pointer",display:"flex",alignItems:"center"},children:q.jsx(L$,{size:16})})}),q.jsx(Fr.Dropdown,{onClick:A=>A.stopPropagation(),children:e.map(A=>q.jsx(Fr.Item,{onClick:k=>{k.stopPropagation(),i(A.value)},style:{fontWeight:A.value===n?600:400,backgroundColor:A.value===n?"rgba(34, 139, 230, 0.1)":void 0},children:A.label},A.value))})]})]})}),q.jsx(So.HideWhenExpanded,{children:q.jsx(tt,{px:"xs",style:{flexGrow:1,letterSpacing:"-0.5px"},pt:"0.1em",children:r})})]}),q.jsx(So.Contents,{children:q.jsxs(tt,{pt:"0.375em",children:[s.length>0&&q.jsx($C,{id:"scene-select",label:"Scene",children:q.jsx(kf,{id:"scene-select",placeholder:"Select scene",data:s,value:o,onChange:a,size:"xs",radius:"xs",searchable:!0,clearable:!1,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),u.length>0&&q.jsx($C,{id:"policy-select",label:"Policy",children:q.jsx(kf,{id:"policy-select",placeholder:"Select policy",data:u,value:d,onChange:f,size:"xs",radius:"xs",searchable:!0,clearable:!0,styles:{input:{minHeight:"1.625rem",height:"1.625rem",padding:"0.5em"}},comboboxProps:{zIndex:1e3}})}),x.length>0&&m.filter(A=>A.config.type==="slider").length>0&&q.jsx(q.Fragment,{children:x.map(A=>{const k=T(A);return k.length===0?null:q.jsx(R7,{label:I7(A),expandByDefault:!0,children:k.map(I=>q.jsx(P7,{command:I,value:v[I.id]??0,onChange:S,disabled:!h},I.id))},A)})}),q.jsx(qf,{my:"xs",mx:"xs"}),q.jsx(tt,{px:"xs",pb:"xs",children:q.jsx(Nc,{variant:"light",color:"red",size:"xs",fullWidth:!0,leftSection:q.jsx(w7,{size:14}),onClick:E,children:"Reset"})})]})})]})}function vf(t,e,n){return Object.keys(t[e]).reduce((r,i)=>(r[i]=`var(--mantine-${n}-${i})`,r),{})}function NC(t,e){return t in e.breakpoints?e.breakpoints[t]:sx(t)}function D7(t){const e=lA(Zm,t),n=vf(e,"fontSizes","font-size"),r=vf(e,"lineHeights","line-height"),i=vf(e,"shadows","shadow"),s=vf(e,"radius","radius"),o=vf(e,"spacing","spacing"),a=Object.keys(e.headings.sizes).reduce((d,f)=>(d[f]={fontSize:`var(--mantine-${f}-font-size)`,lineHeight:`var(--mantine-${f}-line-height)`,fontWeight:`var(--mantine-${f}-font-weight)`},d),{}),u=Object.keys(e.colors).reduce((d,f)=>(d[f]={0:`var(--mantine-color-${f}-0)`,1:`var(--mantine-color-${f}-1)`,2:`var(--mantine-color-${f}-2)`,3:`var(--mantine-color-${f}-3)`,4:`var(--mantine-color-${f}-4)`,5:`var(--mantine-color-${f}-5)`,6:`var(--mantine-color-${f}-6)`,7:`var(--mantine-color-${f}-7)`,8:`var(--mantine-color-${f}-8)`,9:`var(--mantine-color-${f}-9)`,filled:`var(--mantine-color-${f}-filled)`,filledHover:`var(--mantine-color-${f}-filled-hover)`,light:`var(--mantine-color-${f}-light)`,lightHover:`var(--mantine-color-${f}-light-hover)`,lightColor:`var(--mantine-color-${f}-light-color)`,outline:`var(--mantine-color-${f}-outline)`,outlineHover:`var(--mantine-color-${f}-outline-hover)`},d),{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:n,lineHeights:r,shadows:i,radius:s,headings:a,spacing:o,colors:u,rtlSelector:'[dir="rtl"] &',darkSelector:'[data-mantine-color-scheme="dark"] &',lightSelector:'[data-mantine-color-scheme="light"] &',smallerThan:d=>`(max-width: ${NC(d,e)})`,largerThan:d=>`(min-width: ${NC(d,e)})`}}const k_={fontFamily:"Inter",autoContrast:!0,components:{Checkbox:Dc.extend({defaultProps:{radius:"xs"}}),ColorInput:Nb.extend({defaultProps:{radius:"xs"}}),Select:kf.extend({defaultProps:{radius:"sm"}}),Textarea:Ob.extend({defaultProps:{radius:"xs"}}),TextInput:Kb.extend({defaultProps:{radius:"xs"}}),NumberInput:Wb.extend({defaultProps:{radius:"xs"}}),Paper:Ll.extend({defaultProps:{radius:"xs",shadow:"0"}}),ActionIcon:kc.extend({defaultProps:{variant:"subtle",color:"gray",radius:"xs"}}),Button:Nc.extend({defaultProps:{radius:"xs",styles:{label:{fontWeight:450}}}})}};D7(k_);const O$=H.createContext(void 0),z$=()=>{const t=H.useContext(O$);if(!t)throw new Error("useLoading must be used within a LoadingProvider");return t},$7=({children:t})=>{const[e,n]=H.useState(!1),r=H.useRef(0),i=H.useCallback(()=>{r.current+=1,r.current>0&&n(!0)},[]),s=H.useCallback(()=>{r.current=Math.max(0,r.current-1),r.current===0&&n(!1)},[]);return q.jsx(O$.Provider,{value:{isLoading:e,showLoading:i,hideLoading:s},children:t})},N7=()=>{const{isLoading:t}=z$();return t?q.jsx("div",{className:"loader-overlay",children:q.jsx("div",{className:"loader-content",children:q.jsx(Ic,{size:64,type:"bars"})})}):null},LC="0.0.13";function L7(){const[t,{open:e,close:n}]=qm(!1);return q.jsxs(q.Fragment,{children:[q.jsx(Xf,{label:`mjswan ${LC}`,children:q.jsx(tt,{style:{position:"absolute",bottom:"1em",left:"1em",cursor:"pointer",zIndex:100},component:"a",onClick:e,children:q.jsx(Rm,{src:"./logo.svg",style:{width:"2.5em",height:"auto"}})})}),q.jsx(ws,{opened:t,onClose:n,size:"md",title:null,centered:!0,styles:{body:{textAlign:"center"}},children:q.jsxs(Im,{gap:"md",align:"center",children:[q.jsx(Rm,{src:"./logo.svg",style:{width:"5em",height:"auto"}}),q.jsx(Na,{size:"xl",fw:700,children:"mjswan"}),q.jsxs(Na,{size:"sm",c:"dimmed",children:["version ",LC]}),q.jsx(qf,{w:"100%"}),q.jsx(Na,{size:"sm",children:"Browser-based MuJoCo Playground with ONNX policies running entirely in the browser."}),q.jsx(Im,{gap:"xs",children:q.jsxs(tt,{pb:"lg",children:[q.jsx(Am,{href:"https://github.com/ttktjmt/mjswan",target:"_blank",style:{fontWeight:"600"},children:"GitHub"}),"  •  ",q.jsx(Am,{href:"https://mjswan.readthedocs.io",target:"_blank",style:{fontWeight:"600"},children:"Documentation"})]})})]})})]})}function O7(){const t="/".replace(/\/+$/,"/");let n=window.location.pathname.replace(/^\/+|\/+$/g,"");const r=t.replace(/^\/+|\/+$/g,"");if(r&&(n===r?n="":n.startsWith(`${r}/`)&&(n=n.slice(r.length+1))),!n)return null;const i=n.split("/")[0];return i==="main"||i.includes(".")||i==="assets"?null:i}function Xw(t){return t.toLowerCase().replace(/ /g,"_").replace(/-/g,"_")}function z7(t,e){const n=t.replace(/\/+$/,"/"),r=new Set,i=(h,p)=>{if(h)try{const m=new URL(h,p||window.location.href).toString();r.add(m)}catch{r.add(h.replace(/\/+/g,"/"))}},s=`${window.location.origin}/`,o=new URL(n,s).toString();i("assets/config.json",o);const u=window.location.pathname.split("/").filter(Boolean);u.length>0&&u[u.length-1]==="index.html"&&u.pop(),u.length>0&&u[u.length-1]===(e??"main")&&u.pop();const d=`/${u.join("/")}${u.length?"/":""}`,f=`${window.location.origin}${d}`;return i("assets/config.json",f),i("assets/config.json"),i("../assets/config.json"),i("../../assets/config.json"),Array.from(r)}async function U7(t,e){const r=new URLSearchParams(window.location.search).get("config"),i=z7(t,e);if(r)try{i.unshift(new URL(r,window.location.href).toString())}catch{i.unshift(r)}let s=null;for(const o of i)try{const a=await fetch(o,{cache:"no-store"});if(!a.ok)throw new Error(`Failed to fetch ${o}: ${a.status}`);const u=await a.text(),d=u.trim();if((a.headers.get("content-type")||"").includes("text/html")||d.startsWith("<!doctype")||d.startsWith("<html"))throw new Error(`Received HTML from ${o}`);try{return JSON.parse(u)}catch(h){throw new Error(`Invalid JSON from ${o}: ${h instanceof Error?h.message:String(h)}`)}}catch(a){s=a instanceof Error?a:new Error(String(a))}throw s??new Error("Failed to load config.json.")}function OC(t,e){if(!t.scenes.length)return null;if(!e)return t.scenes[0];const n=e.trim().toLowerCase();return t.scenes.find(r=>r.name.toLowerCase()===n)||t.scenes.find(r=>Xw(r.name)===n)||t.scenes[0]}function zC(t,e){if(!t.policies.length)return null;if(!e)return t.policies[0].name;const n=e.trim().toLowerCase();return(t.policies.find(i=>i.name.toLowerCase()===n)||t.policies.find(i=>Xw(i.name)===n))?.name??t.policies[0].name}function rx(t,e,n){const i="/".replace(/\/+$/,"/").replace(/^\//g,"").replace(/\/+$/g,"");let s=i?`/${i}/`:"/";t&&t!=="main"&&(s+=`${t}/`);const o=new URLSearchParams;e&&o.set("scene",e),n&&o.set("policy",n);const a=s+(o.toString()?"?"+o.toString():"");window.history.replaceState({},"",a)}function F7(){const[t,e]=H.useState(null),[n,r]=H.useState(null),[i,s]=H.useState(null),[o,a]=H.useState(null),[u,d]=H.useState(null),{showLoading:f,hideLoading:h}=z$(),p=H.useMemo(()=>O7(),[]),m=H.useMemo(()=>new URLSearchParams(window.location.search).get("scene"),[]),_=H.useMemo(()=>new URLSearchParams(window.location.search).get("policy"),[]);H.useEffect(()=>{f(),U7("/",p).then(L=>{e(L);const G=L.projects.find(Z=>p===null?Z.id===null:Z.id===p);if(!G)throw new Error(`Project "${p??"(main)"}" not found in config.json.`);r(G);const C=OC(G,m);s(C);const j=C?zC(C,_):null;a(j)}).catch(L=>{console.error("Failed to load config:",L),d(L.message||"Failed to load config."),h()})},[p,m,_,f,h]);const x=H.useMemo(()=>{if(!n||!i)return null;const L=n.id?n.id:"main",G=i.path?i.path:`scene/${Xw(i.name)}/scene.xml`;return`${L}/assets/${G}`.replace(/\/+/g,"/")},[n,i]),y=H.useMemo(()=>!i||!o?null:i.policies.find(L=>L.name===o)??null,[i,o]),v=H.useMemo(()=>!n||!y?.config?null:`${n.id?n.id:"main"}/assets/${y.config}`.replace(/\/+/g,"/"),[n,y]),b=H.useMemo(()=>t?t.projects.map(L=>({value:L.id??"main",label:L.name||(L.id??"Main")})):[],[t]),S=H.useMemo(()=>n?n.scenes.map(L=>({value:L.name,label:L.name})):[],[n]),E=H.useMemo(()=>!i||!i.policies?[]:i.policies.map(L=>({value:L.name,label:L.name})),[i]),T=n?n.id??"main":null,A=i?.name??null,k=H.useCallback(L=>{d(L.message),h()},[h]),I=H.useCallback(()=>{h()},[h]),P=H.useCallback(L=>{if(!t||!L)return;const G=L==="main"?null:L,C=t.projects.find(Y=>(Y.id??"main")===(G??"main"));if(!C)return;f(),r(C);const j=OC(C,null);s(j);const Z=j?.policies?.[0]?.name??null;a(Z),rx(C.id,j?.name??null,Z)},[t,f]),$=H.useCallback(L=>{if(!n||!L)return;const G=n.scenes.find(j=>j.name===L);if(!G)return;f(),s(G);const C=zC(G,null);a(C),rx(n.id,L,C)},[n,f]),X=H.useCallback(L=>{L!==o&&f(),a(L),rx(n?.id??null,i?.name??null,L)},[n,i,o,f]);return u?q.jsx(ux,{theme:k_,defaultColorScheme:"dark",children:q.jsx("div",{className:"app",children:q.jsxs("div",{className:"hud hud-error",children:[q.jsx("h1",{className:"hud-title",children:"mjswan"}),q.jsx("p",{className:"hud-message",children:u})]})})}):!n||!i||!x?null:q.jsx(ux,{theme:k_,defaultColorScheme:"dark",children:q.jsxs("div",{className:"app",children:[q.jsx(N7,{}),q.jsx(L7,{})," ",q.jsx(k7,{projects:b,projectValue:T,projectLabel:n?.name??"mjswan",onProjectChange:P,scenes:S,sceneValue:A,onSceneChange:$,policies:E,policyValue:o,onPolicyChange:X,commandsEnabled:!!v}),q.jsx(g7,{scenePath:x,baseUrl:"/",policyConfigPath:v,onError:k,onReady:I})]})})}function B7(){return q.jsx($7,{children:q.jsx(F7,{})})}const UC=document.getElementById("root");UC&&CN.createRoot(UC).render(q.jsx(Dn.StrictMode,{children:q.jsx(B7,{})}));
package/dist/index.html CHANGED
@@ -12,7 +12,7 @@
12
12
  <link rel="manifest" href="manifest.json" />
13
13
  <title>mjswan</title>
14
14
  <script src="coi-serviceworker.js"></script>
15
- <script type="module" crossorigin src="/assets/index-D06ezVv2.js"></script>
15
+ <script type="module" crossorigin src="/assets/index-CpXSFkA7.js"></script>
16
16
  <link rel="stylesheet" crossorigin href="/assets/index-D_DiXcjN.css">
17
17
  </head>
18
18
  <body>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mjswan",
3
3
  "type": "module",
4
- "version": "0.0.10",
4
+ "version": "0.0.13",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/ttktjmt/mjswan.git"