Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: expose BitmapFont measureText API for precise editor bounds

esengine7be1c55f4adc
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 441185118..574a420a6 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function n(e,n){return t().fetch(e,n)}async function s(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,n){return t().createCanvas(e,n)}function a(){return t().now()}function l(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,n)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((n,s)=>{d().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{d().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,g=null;function x(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function y(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,g=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:g}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}let _=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return h(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},v=4294967295,b=4294967295;function S(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=S("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),C=S("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),T=S("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),M=S("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A={Static:0,Kinematic:1,Dynamic:2};let E=0;function R(e,t){const n=++E;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function B(e,t){const n=I(),s=n.get(e);if(s)return s;const r=R(e,t);return n.set(e,r),k(e,t,!1),r}function F(e){const t=I(),n=t.get(e);if(n)return n;const s=R(e,{});return t.set(e,s),k(e,{},!0),s}function U(e){return I().get(e)}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const z=W("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),$=W("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),L=W("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),H=W("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=W("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=W("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=W("Parent",{entity:0}),X=W("Children",{entities:[]}),V=W("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),G=W("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:z,WorldTransform:$,Sprite:L,Camera:H,Canvas:O,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:G,RigidBody:P,BoxCollider:C,CircleCollider:T,CapsuleCollider:M};let J=0;function K(e,t){const n=++J;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Q(e){return{_type:"res",_resource:e}}class Z{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ee{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new Z(this.get(e),t=>this.set(e,t))}}const te=K({delta:0,elapsed:0,frameCount:0},"Time");function ne(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class se{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ne(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class re{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class oe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new re(this,null);return this.spawned_.push(e),e}entity(e){return new re(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ie;exports.Schedule=void 0,(ie=exports.Schedule||(exports.Schedule={}))[ie.Startup=0]="Startup",ie[ie.First=1]="First",ie[ie.PreUpdate=2]="PreUpdate",ie[ie.Update=3]="Update",ie[ie.PostUpdate=4]="PostUpdate",ie[ie.Last=5]="Last",ie[ie.FixedPreUpdate=10]="FixedPreUpdate",ie[ie.FixedUpdate=11]="FixedUpdate",ie[ie.FixedPostUpdate=12]="FixedPostUpdate";let ae=0;function le(e,t,n){const s=++ae;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function ce(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ue{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof oe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new se(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new oe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class de{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const he=K(new de,"Input");class pe{constructor(e){this.target_=e??null}build(e){const n=new de;e.insertResource(he,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,le([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new pe;function me(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:me(e)}}return t}class ge{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return D(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,me(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!D(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var xe,ye,_e;exports.TextAlign=void 0,(xe=exports.TextAlign||(exports.TextAlign={}))[xe.Left=0]="Left",xe[xe.Center=1]="Center",xe[xe.Right=2]="Right",exports.TextVerticalAlign=void 0,(ye=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ye.Top=0]="Top",ye[ye.Middle=1]="Middle",ye[ye.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_e=exports.TextOverflow||(exports.TextOverflow={}))[_e.Visible=0]="Visible",_e[_e.Clip=1]="Clip",_e[_e.Ellipsis=2]="Ellipsis";const we=B("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class ve{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<p||s.height<f){const e=Math.max(s.width,this.nextPowerOf2(p)),t=Math.max(s.height,this.nextPowerOf2(f));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),x=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${x}, ${y})`,r&&e.overflow===exports.TextOverflow.Clip&&(n.save(),n.beginPath(),n.rect(0,0,p,f),n.clip());const _=l.length*c;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let v=w;for(const t of l){let s;switch(e.align){case exports.TextAlign.Left:s=u;break;case exports.TextAlign.Center:s=p/2;break;case exports.TextAlign.Right:s=p-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===exports.TextOverflow.Clip&&n.restore();const b=n.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(p,f,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const be=B("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Se{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new ve(t),s=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,we));const e=s.getEntitiesWithComponents([we]);for(const t of e){const e=s.get(t,we);if(!e.dirty)continue;s.has(t,L)||s.insert(t,L,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,be)?s.get(t,be):null,o=n.renderForEntity(t,e,r),i=s.get(t,L);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,L,i),e.dirty=!1}}))}}const Pe=new Se,Ce=B("UIMask",{enabled:!0});function Te(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Me(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),p=t-s*o,f=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,x]=m(d,p),[y,_]=m(h,f),w=Math.min(g,y),v=Math.max(g,y),b=Math.min(x,_),S=Math.max(x,_);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Ae(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],x=e[14],y=e[15],_=s*l-r*a,w=s*c-o*a,v=s*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=d*g-h*m,T=d*x-p*m,M=d*y-f*m,A=h*x-p*g,E=h*y-f*g,R=p*y-f*x;let I=_*R-w*E+v*A+b*M-S*T+P*C;return 0===I||(I=1/I,n[0]=(l*R-c*E+u*A)*I,n[1]=(o*E-r*R-i*A)*I,n[2]=(g*P-x*S+y*b)*I,n[3]=(p*S-h*P-f*b)*I,n[4]=(c*M-a*R-u*T)*I,n[5]=(s*R-o*M+i*T)*I,n[6]=(x*v-m*P-y*w)*I,n[7]=(d*P-p*v+f*w)*I,n[8]=(a*E-l*M+u*C)*I,n[9]=(r*M-s*E-i*C)*I,n[10]=(m*S-g*v+y*_)*I,n[11]=(h*v-d*S-f*_)*I,n[12]=(l*T-a*A-c*C)*I,n[13]=(s*A-r*T+o*C)*I,n[14]=(g*w-m*b-x*_)*I,n[15]=(d*b-h*w+p*_)*I),n}function Ee(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Re(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function Ie(e,t,n,s,r,o,i){if(!e.has(t,be)||!e.has(t,$))return null;const a=e.get(t,be),l=e.get(t,$),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Me(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function Be(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ce]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Ce).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,j);){const e=t.get(s,j);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=Ie(t,n,r,o,i,a,l);e&&(s=Te(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=Ie(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Fe{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Be(e.wasmModule,e.world))}}const Ue=new Fe,ke=B("Interactable",{enabled:!0}),We=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var De;exports.ButtonState=void 0,(De=exports.ButtonState||(exports.ButtonState={}))[De.Normal=0]="Normal",De[De.Hovered=1]="Hovered",De[De.Pressed=2]="Pressed",De[De.Disabled=3]="Disabled";const ze=B("Button",{state:exports.ButtonState.Normal,transition:null});class $e{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Le=K(new $e,"UIEvents"),He=K({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),Oe=new Float32Array(16);class Ne{build(e){const t=e.world,n=new $e;e.insertResource(Le,n);let s=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(he),Q(He)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([We]);for(const e of i){const n=t.get(e,We);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Ae(o.viewProjection,Oe);const u=Ee(l,c,Oe,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([ke,be,$]);let h=null,p=-1/0;for(const e of d){t.has(e,We)||t.insert(e,We);if(!t.get(e,ke).enabled)continue;const n=t.get(e,$),s=t.get(e,be),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Re(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,L)&&(n=t.get(e,L).layer),n>=p&&(p=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,We)){t.get(s,We).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,We).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,We);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,We)){const e=t.get(r,We);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,le([],()=>{const e=t.getEntitiesWithComponents([ze]);for(const n of e){if(t.has(n,ke)||t.insert(n,ke,{enabled:!0}),!t.has(n,We))continue;const e=t.get(n,We),s=t.get(n,ze),r=t.get(n,ke),o=s.state;if(r.enabled?e.pressed?s.state=exports.ButtonState.Pressed:e.hovered?s.state=exports.ButtonState.Hovered:s.state=exports.ButtonState.Normal:s.state=exports.ButtonState.Disabled,o!==s.state&&s.transition&&t.has(n,L)){const e=t.get(n,L),r=s.transition;switch(s.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(n,L,e)}}},{name:"ButtonSystem"}))}}const je=new Ne,Xe=F("ScreenSpace");function Ve(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,p=t-o,f=e+s,m=t+o}else h=l+n.x,p=u+n.y,f=c+s.x,m=d+s.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function Ge(e,t,n,s,r,o){if(!e.has(t,be))return;const i=e.get(t,be),a=Ve(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,z,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ge(e,t,a.rect,a.centerX,a.centerY,!1)}class Ye{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(He)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Xe,be,z]);for(const e of o)Ge(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const qe=new Ye,Je=B("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Ke{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=i(512,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();function p(){if(null===a||!n.valid(a))return;const t=n.get(a,Je);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(Le).emit(a,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function f(e){if(a===e)return;m();const t=n.get(e,Je);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==a&&n.valid(a)&&n.has(a,Je)){const e=n.get(a,Je);e.focused=!1,e.dirty=!0}a=null,h.blur()}function g(){c=!0,u=0}function x(e,i,a,l){(r.width<a||r.height<l)&&(r.width=Ze(Math.max(r.width,a)),r.height=Ze(Math.max(r.height,l))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Qe(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=Qe(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*f,s=f}else t=m+o.measureText(e).width,n=(l-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,l),x=new Uint8Array(g.data.buffer),y=t.getResourceManager(),_=t._malloc(x.length);t.HEAPU8.set(x,_);const w=s.get(e);void 0!==w&&y.releaseTexture(w);const v=y.createTexture(a,l,_,x.length,1,!0);s.set(e,v),t._free(_);const b=n.get(e,L);b.texture=v,b.size.x=a,b.size.y=l,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,L,b)}h.addEventListener("input",()=>{l||null===a||p()}),h.addEventListener("compositionstart",()=>{l=!0}),h.addEventListener("compositionend",()=>{l=!1,p()}),h.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const s=n.get(a,Je);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Le).emit(a,"submit"),void m()}}),h.addEventListener("blur",()=>{if(null!==a&&n.valid(a)&&n.has(a,Je)){const e=n.get(a,Je);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Le)],e=>{const t=n.getEntitiesWithComponents([Je,ke]);for(const e of t){if(!n.has(e,We))continue;if(n.get(e,We).justPressed)return void f(e)}if(null!==a){const e=n.getEntitiesWithComponents([ke]);for(const t of e){if(n.has(t,Je))continue;if(!n.has(t,We))continue;if(n.get(t,We).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,c=!c,null!==a&&n.valid(a)&&n.has(a,Je)))){n.get(a,Je).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Je)||(o.releaseTexture(t),s.delete(e));const i=n.getEntitiesWithComponents([Je,be]);for(const e of i){const t=n.get(e,Je);if(!t.dirty)continue;const s=n.get(e,be),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,L)||n.insert(e,L,{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Qe(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function Ze(e){let t=1;for(;t<e;)t*=2;return t}const et=new Ke;var tt;function nt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(tt=exports.BlendMode||(exports.BlendMode={}))[tt.Normal=0]="Normal",tt[tt.Additive=1]="Additive",tt[tt.Multiply=2]="Multiply",tt[tt.Screen=3]="Screen",tt[tt.PremultipliedAlpha=4]="PremultipliedAlpha";let st=null,rt=null,ot=1;const it=new Map;function at(e){st=e,rt=e.getResourceManager(),xt()}function lt(){0!==ht&&st&&(st._free(ht),ht=0),it.clear(),ot=1,dt=!1,rt=null,st=null}function ct(){if(!rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rt}const ut={createShader:(e,t)=>ct().createShader(e,t),releaseShader(e){e>0&&ct().releaseShader(e)},create(e){const t=ot++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return it.set(t,n),t},get:e=>it.get(e),setUniform(e,t,n){const s=it.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=it.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=it.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=it.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const n=it.get(e);n&&(n.depthTest=t)},getShader(e){const t=it.get(e);return t?.shader??0},release(e){it.delete(e)},isValid:e=>it.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=it.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ot++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return it.set(n,s),n},toAssetData(e,t){const n=it.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=it.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let dt=!1,ht=0;const pt=4096,ft=new Map;let mt=null;function gt(e){const t=(0===ht&&st&&(ht=st._malloc(pt)),ht);if(0===t||!st)return{ptr:0,count:0};let n=0,s=0;const r=st.HEAPU8,o=st.HEAPU32,i=st.HEAPF32;for(const[a,l]of e){if(n+128>pt)break;let e=ft.get(a);e||(mt||(mt=new TextEncoder),e=mt.encode(a),ft.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function xt(){if(!st||dt)return;st.materialDataProvider=(e,t,n,s,r)=>{const o=it.get(e);if(!o)return st.HEAPU32[t>>2]=0,st.HEAPU32[n>>2]=0,st.HEAPU32[s>>2]=0,void(st.HEAPU32[r>>2]=0);st.HEAPU32[t>>2]=o.shader,st.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=gt(o.uniforms);st.HEAPU32[s>>2]=i,st.HEAPU32[r>>2]=a},dt=!0}const yt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class _t{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ut.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ut.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const n=await r(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),a=await this.shaderLoader_.load(i);return{handle:ut.createFromAsset(s,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function wt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,Y,{value:s.name});for(const n of s.components)bt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function vt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,Y,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}bt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function bt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,z,s);break;case"Sprite":e.insert(t,L,s);break;case"Camera":e.insert(t,H,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,we,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,G,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,be,n);break}case"UIMask":e.insert(t,Ce,s);break;case"Interactable":e.insert(t,ke,s);break;case"Button":e.insert(t,ze,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,C,s);break;case"CircleCollider":e.insert(t,T,s);break;case"CapsuleCollider":e.insert(t,M,s);break;default:{const r=U(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}class St{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Pt{constructor(e){this.textureCache_=new St,this.shaderCache_=new St,this.jsonCache_=new St,this.textCache_=new St,this.binaryCache_=new St,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new St,this.prefabCache_=new St,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=i(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new _t(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return vt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:i}=this.parseEsShader(n);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return ut.createShader(s,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await r(t);return JSON.parse(n)}const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):r(t)}const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):s(t)}const r=await n(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ct=K(null,"Assets");class Tt{build(e){const t=e.wasmModule;t?e.insertResource(Ct,new Pt(t)):console.warn("AssetPlugin: No WASM module available")}}const Mt=new Tt;let At=null,Et=0,Rt=0,It=0;const Bt=new Float32Array(256);function Ft(e){At=e,Et=At._malloc(64),Rt=At._malloc(64),It=At._malloc(1024)}function Ut(){At&&(Et&&(At._free(Et),Et=0),Rt&&(At._free(Rt),Rt=0),It&&(At._free(It),It=0)),At=null}function kt(){if(!At)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return At}const Wt={r:1,g:1,b:1,a:1},Dt={begin(e){const t=kt();t.HEAPF32.set(e,Et/4),t.draw_begin(Et)},end(){kt().draw_end()},line(e,t,n,s=1){kt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){kt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){kt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){kt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){kt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Wt){kt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Wt){kt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){kt().draw_setLayer(e)},setDepth(e){kt().draw_setDepth(e)},getDrawCallCount:()=>At?At.draw_getDrawCallCount():0,getPrimitiveCount:()=>At?At.draw_getPrimitiveCount():0,setBlendMode(e){kt().draw_setBlendMode(e)},setDepthTest(e){kt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=kt();s.HEAPF32.set(n,Rt/4),s.draw_mesh(e,t,Rt)},drawMeshWithMaterial(e,t,n){const s=kt(),r=ut.get(t);if(!r)return;if(Dt.setBlendMode(r.blendMode),Dt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Dt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Rt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=$t(e);if(!(n<0)){if(nt(t))Bt[o++]=10,Bt[o++]=n,Bt[o++]=t.slot??i++,Bt[o++]=t.textureId;else if("number"==typeof t)Bt[o++]=1,Bt[o++]=n,Bt[o++]=t;else if(Array.isArray(t)){Bt[o++]=t.length,Bt[o++]=n;for(let e=0;e<t.length;e++)Bt[o++]=t[e]}else"w"in t?(Bt[o++]=4,Bt[o++]=n,Bt[o++]=t.x,Bt[o++]=t.y,Bt[o++]=t.z,Bt[o++]=t.w):"z"in t?(Bt[o++]=3,Bt[o++]=n,Bt[o++]=t.x,Bt[o++]=t.y,Bt[o++]=t.z):(Bt[o++]=2,Bt[o++]=n,Bt[o++]=t.x,Bt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Bt.subarray(0,o),It/4),s.draw_meshWithUniforms(e,r.shader,Rt,It,o)):s.draw_mesh(e,r.shader,Rt)}},zt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function $t(e){return zt[e]??-1}var Lt;exports.DataType=void 0,(Lt=exports.DataType||(exports.DataType={}))[Lt.Float=1]="Float",Lt[Lt.Float2=2]="Float2",Lt[Lt.Float3=3]="Float3",Lt[Lt.Float4=4]="Float4",Lt[Lt.Int=5]="Int",Lt[Lt.Int2=6]="Int2",Lt[Lt.Int3=7]="Int3",Lt[Lt.Int4=8]="Int4";let Ht=null,Ot=0,Nt=0,jt=0;function Xt(e){Ht=e,Ot=Ht._malloc(262144),Nt=Ht._malloc(65536),jt=Ht._malloc(256)}function Vt(){Ht&&(Ot&&Ht._free(Ot),Nt&&Ht._free(Nt),jt&&Ht._free(jt),Ot=0,Nt=0,jt=0),Ht=null}function Gt(){if(!Ht)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ht}const Yt={create(e){const t=Gt(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ot/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,jt,r).set(o),t.geometry_init(n,Ot,s,jt,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Nt,s).set(e.indices),t.geometry_setIndices16(n,Nt,s)}else{new Uint32Array(t.HEAPU8.buffer,Nt,s).set(e.indices),t.geometry_setIndices32(n,Nt,s)}}return n},updateVertices(e,t,n=0){const s=Gt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Ot/4),s.geometry_updateVertices(e,Ot,r,n)},release(e){e>0&&Gt().geometry_release(e)},isValid:e=>!(!Ht||e<=0)&&Ht.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Yt.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Yt.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Yt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let qt=null;function Jt(e){qt=e}function Kt(){qt&&Zt.isInitialized()&&Zt.shutdown(),qt=null}function Qt(){if(!qt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return qt}const Zt={init:(e,t)=>Qt().postprocess_init(e,t),shutdown(){Qt().postprocess_shutdown()},resize(e,t){Qt().postprocess_resize(e,t)},addPass:(e,t)=>Qt().postprocess_addPass(e,t),removePass(e){Qt().postprocess_removePass(e)},setEnabled(e,t){Qt().postprocess_setPassEnabled(e,t)},isEnabled:e=>Qt().postprocess_isPassEnabled(e),setUniform(e,t,n){Qt().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Qt().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Qt().postprocess_begin()},end(){Qt().postprocess_end()},getPassCount:()=>Qt().postprocess_getPassCount(),isInitialized:()=>!!qt&&qt.postprocess_isInitialized(),setBypass(e){Qt().postprocess_setBypass(e)},isBypassed:()=>!qt||qt.postprocess_isBypassed(),createBlur:()=>ut.createShader(en,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>ut.createShader(en,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>ut.createShader(en,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>ut.createShader(en,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},en="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var tn;exports.RenderStage=void 0,(tn=exports.RenderStage||(exports.RenderStage={}))[tn.Background=0]="Background",tn[tn.Opaque=1]="Opaque",tn[tn.Transparent=2]="Transparent",tn[tn.Overlay=3]="Overlay";let nn=null,sn=0;function rn(e){nn=e,sn=nn._malloc(64)}function on(){nn&&sn&&(nn._free(sn),sn=0),nn=null}const an={init(e,t){nn?.renderer_init(e,t)},resize(e,t){nn?.renderer_resize(e,t)},begin(e,t){nn&&sn&&(nn.HEAPF32.set(e,sn/4),nn.renderer_begin(sn,t??0))},flush(){nn?.renderer_flush()},end(){nn?.renderer_end()},submitSprites(e){nn&&nn.renderer_submitSprites(e._cpp)},submitBitmapText(e){nn&&nn.renderer_submitBitmapText(e._cpp)},submitSpine(e){nn&&nn.renderer_submitSpine?.(e._cpp)},setStage(e){nn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>nn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){nn?.renderer_releaseTarget(e)},getTargetTexture:e=>nn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>nn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){nn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){nn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){nn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){nn?.renderer_clearBuffers(e)},getStats:()=>nn?{drawCalls:nn.renderer_getDrawCalls(),triangles:nn.renderer_getTriangles(),sprites:nn.renderer_getSprites(),text:nn.renderer_getText(),spine:nn.renderer_getSpine?.()??0,meshes:nn.renderer_getMeshes(),culled:nn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ln=null;function cn(e){ln=e}function un(){ln=null}const dn={enable(){ln?.gl_enableErrorCheck(!0)},disable(){ln?.gl_enableErrorCheck(!1)},check:e=>ln?.gl_checkErrors(e)??0,diagnose(){ln?.renderer_diagnose()}},hn=new Map;function pn(e){hn.delete(e)}class fn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(an.resize(s,r),Zt.isInitialized()&&Zt.getPassCount()>0&&Zt.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),an.setViewport(0,0,s,r),an.clearBuffers(3),an.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),an.submitSprites(t),an.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):an.submitSpine(t),an.flush(),this.executeDrawCallbacks(n,o),an.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;an.setViewport(s.x,s.y,s.w,s.h),an.setScissor(s.x,s.y,s.w,s.h,!0),an.clearBuffers(r),an.setScissor(0,0,0,0,!1),an.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),an.submitSprites(t),an.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):an.submitSpine(t),an.flush(),this.executeDrawCallbacks(n,o),an.end()}executeDrawCallbacks(e,t){const n=hn;if(n.size>0){Dt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Dt.end();for(const e of s)pn(e)}}}class mn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ge,this.resources_=new ee;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new mn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ue(this.world_,this.resources_),this.resources_.insert(te,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,un(),on(),Kt(),Vt(),lt(),Ut()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(te);t.delta=e,t.elapsed+=e,t.frameCount++}}const gn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function xn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function yn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=xn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=wn(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=bn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const p=Pn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Cn(u,p),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const _n=new Float32Array(16);function wn(e,t,n,s,r,o){const i=_n;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const vn=new Float32Array(16);function bn(e,t,n,s){const r=vn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Sn=new Float32Array(16);function Pn(e,t,n){const s=Sn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function Cn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function Tn(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Tn(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Mn(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Mn(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}async function An(e,t){if(t)return t();return(0,(await import(e)).default)()}const En=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Rn=K(null,"PhysicsAPI");function In(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Bn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Fn{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(En,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=An(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,le([Q(te)],a=>{const l=i.getEntitiesWithComponents([P,z,$]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,P),l=i.get(r,$);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=In(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Un(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===A.Kinematic){const e=In(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,z);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,$)){const n=e.world.get(t.entity,$),s=In(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),p=c-s}}u.position.x=d,u.position.y=h;const f=Bn(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,z,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(En,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Rn,kn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Un(e,t,n){const s=e.world;if(s.has(n,C)){const e=s.get(n,C);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,T)){const e=s.get(n,T);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,M)){const e=s.get(n,M);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class kn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(kn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Wn(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Dn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function zn(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,x=l*h,y=l*p,_=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(x+_))*r,(m+b)*r,(g-v)*r,0,(m-b)*o,(1-(f+_))*o,(y+w)*o,0,(g+v)*i,(y-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function $n(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Wn(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let l={},c=null;if(r&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),l=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const p=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Dn(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const s=m+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Wn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new Fn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=Wn(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),d=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=ut.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=ut.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=wt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,L);r&&(r.texture=n[s.data.texture]||0,e.insert(t,L,r))}}}(e.world,n,a,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,V);o&&(o.font=r,e.insert(t,V,o))}}}(e.world,n,u,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,L);n&&(n.material=r,e.insert(t,L,n))}else if("SpineAnimation"===s.type){const n=e.get(t,G);n&&(n.material=r,e.insert(t,G,n))}}}}(e.world,n,d,h),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(c,n,l,h);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,G)?c.get(o,G):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,$)){const e=zn(c.get(o,$),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=s.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),p=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,p);const f=n.HEAPU32[d>>2],m=n.HEAPU32[p>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),x=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(x),t.renderer_submitTriangles(y,r,_,o,f,m,h),t._free(y),t._free(_),n._free(c),n._free(u),n._free(d),n._free(p)}h&&t._free(h)}})}(e,t,r,c,s)}}class Ln{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Hn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=an.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:an.getTargetTexture(n),width:e.width,height:e.height}},release(e){an.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(an.releaseRenderTarget(e._handle),Hn.create({width:t,height:n,depth:!0})),begin(e,t){an.begin(t,e._handle)},end(){an.end()},getDepthTexture:e=>an.getTargetDepthTexture(e._handle)};let On=!1;_||(_=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await l(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=mn,exports.AssetPlugin=Tt,exports.AssetServer=Pt,exports.Assets=Ct,exports.AsyncCache=St,exports.BitmapText=V,exports.BodyType=A,exports.BoxCollider=C,exports.Button=ze,exports.Camera=H,exports.Canvas=O,exports.CapsuleCollider=M,exports.Children=X,exports.CircleCollider=T,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=oe,exports.Draw=Dt,exports.EntityCommands=re,exports.GLDebug=dn,exports.Geometry=Yt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=b,exports.INVALID_TEXTURE=v,exports.Input=he,exports.InputPlugin=pe,exports.InputState=de,exports.Interactable=ke,exports.LocalTransform=z,exports.Material=ut,exports.MaterialLoader=_t,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=j,exports.Physics=kn,exports.PhysicsEvents=En,exports.PhysicsPlugin=Fn,exports.PostProcess=Zt,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await n(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Ln(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.__spineInitPromise;if(o){r=(await o).controller.raw}await $n(this.app_,this.app_.wasmModule,t,s,r),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([H]);for(const s of n){if(e.get(s,H).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,z,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,H,i)}}},exports.Query=function(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{ne(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)},exports.QueryInstance=se,exports.RenderPipeline=fn,exports.RenderTexture=Hn,exports.Renderer=an,exports.Res=Q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ScreenSpace=Xe,exports.ShaderSources=yt,exports.SpineAnimation=G,exports.Sprite=L,exports.SystemRunner=ue,exports.Text=we,exports.TextInput=Je,exports.TextInputPlugin=Ke,exports.TextPlugin=Se,exports.TextRenderer=ve,exports.Time=te,exports.UICameraInfo=He,exports.UIEventQueue=$e,exports.UIEvents=Le,exports.UIInteraction=We,exports.UIInteractionPlugin=Ne,exports.UILayoutPlugin=Ye,exports.UIMask=Ce,exports.UIMaskPlugin=Fe,exports.UIRect=be,exports.Velocity=N,exports.WebAssetProvider=Ln,exports.World=ge,exports.WorldTransform=$,exports.addStartupSystem=function(e){ce().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ce().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ce().push({schedule:e,system:t})},exports.assetPlugin=Mt,exports.clearDrawCallbacks=function(){hn.clear()},exports.clearUserComponents=function(){I().clear()},exports.color=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),exports.computeUIRectLayout=Ve,exports.createMaskProcessor=Be,exports.createWebApp=function(e,t){const n=mn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ft(e),at(e),Xt(e),Jt(e),rn(e),cn(e);const r=new fn;n.pipeline_=r;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,r){const o=yn(e,s,t,r),i=n.getResource(He);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(He,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;an.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;an.resize(t,n),Zt.isInitialized()&&Zt.getPassCount()>0&&!Zt.isBypassed()&&Zt.resize(t,n);const d=yn(e,s,t,n);if(l(t,n),0===d.length)r.render({registry:{_cpp:s},viewProjection:gn,width:t,height:n,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),c=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}an.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(exports.Schedule.First,c),n.addSystemToSchedule(exports.Schedule.Last,u),n.addPlugin(Mt),n.addPlugin(fe),n.addPlugin(Pe),n.addPlugin(Ue),n.addPlugin(qe),n.addPlugin(je),n.addPlugin(et),n},exports.defineComponent=B,exports.defineResource=K,exports.defineSystem=le,exports.defineTag=F,exports.findEntityByName=function(e,t){const n=e.getEntitiesWithComponents([Y]);for(const s of n){const n=e.get(s,Y);if(n&&n.value===t)return s}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}},exports.getComponentDefaults=function(e){const t=q[e];if(t)return{...t._default};const n=U(e);return n?{...n._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=U,exports.initDrawAPI=Ft,exports.initGLDebugAPI=cn,exports.initGeometryAPI=Xt,exports.initMaterialAPI=at,exports.initPostProcessAPI=Jt,exports.initRendererAPI=rn,exports.inputPlugin=fe,exports.instantiatePrefab=async function(e,t,n){const{entities:s,rootId:r}=await Tn(t,n?.overrides??[],n),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components}))},i=await vt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}},exports.intersectRects=Te,exports.invertMatrix4=Ae,exports.isBuiltinComponent=D,exports.isEditor=function(){return On},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!On},exports.isTextureRef=nt,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=bt,exports.loadPhysicsModule=An,exports.loadRuntimeScene=$n,exports.loadSceneData=wt,exports.loadSceneWithAssets=vt,exports.platformFetch=n,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,n){return t().instantiateWasm(e,n)},exports.platformReadFile=s,exports.platformReadTextFile=r,exports.pointInWorldRect=Re,exports.quat=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s}),exports.registerDrawCallback=function(e,t){hn.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const n=e.getResource(Ct);n&&n.registerEmbeddedAssets(t)},exports.registerMaterialCallback=xt,exports.screenToWorld=Ee,exports.setEditorMode=function(e){On=e},exports.shutdownDrawAPI=Ut,exports.shutdownGLDebugAPI=un,exports.shutdownGeometryAPI=Vt,exports.shutdownMaterialAPI=lt,exports.shutdownPostProcessAPI=Kt,exports.shutdownRendererAPI=on,exports.textInputPlugin=et,exports.textPlugin=Pe,exports.uiInteractionPlugin=je,exports.uiLayoutPlugin=qe,exports.uiMaskPlugin=Ue,exports.unregisterDrawCallback=pn,exports.updateCameraAspectRatio=function(e,t){const n=e.getEntitiesWithComponents([H]);for(const s of n){const n=e.get(s,H);n&&(n.aspectRatio=t,e.insert(s,H,n))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),exports.vec4=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),exports.worldRectToScreen=Me,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=d();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=y,exports.wxLoadImage=x,exports.wxLoadImagePixels=async function(e){return y(await x(e))},exports.wxReadFile=h,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((n,s)=>{d().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}async function s(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function n(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function l(e,t){return new Promise((s,r)=>{const n=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===n?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,r={};if(e.header)for(const t of Object.keys(e.header))r[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:r,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{r(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function c(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}let u=null;function d(){return u||(u=wx.getFileSystemManager()),u}function h(e){return new Promise((t,s)=>{d().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function p(e,t="utf-8"){return new Promise((s,r)=>{d().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{r(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function f(e){return new Promise(t=>{d().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}let m=null,g=null;function x(e){return new Promise((t,s)=>{const r=wx.createImage();r.onload=()=>t(r),r.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),r.src=e})}function y(e){const{width:t,height:s}=e,{ctx:r}=function(e,t){return m||(m=wx.createCanvas(),m.width=e,m.height=t,g=m.getContext("2d")),(m.width<e||m.height<t)&&(m.width=Math.max(m.width,e),m.height=Math.max(m.height,t)),{canvas:m,ctx:g}}(t,s);r.clearRect(0,0,t,s),r.drawImage(e,0,0);const n=r.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(n.data.buffer)}}let _=!1;const w=new class{constructor(){this.name="wechat"}async fetch(e,t){return l(e,t)}async readFile(e){return h(e)}async readTextFile(e){return p(e)}async fileExists(e){return f(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return c(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const s=t.touches[0];s&&e.onPointerDown(0,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},b=4294967295,v=4294967295;function S(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=S("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),T=S("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=S("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),A=S("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E={Static:0,Kinematic:1,Dynamic:2};let M=0;function R(e,t){const s=++M;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function B(e,t){const s=I(),r=s.get(e);if(r)return r;const n=R(e,t);return s.set(e,n),k(e,t,!1),n}function U(e){const t=I(),s=t.get(e);if(s)return s;const r=R(e,{});return t.set(e,r),k(e,{},!0),r}function F(e){return I().get(e)}function k(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function W(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function D(e){return!0===e._builtin}const $=W("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),z=W("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),L=W("Sprite",{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),O=W("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),H=W("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),N=W("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),j=W("Parent",{entity:0}),X=W("Children",{entities:[]}),V=W("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:v}),G=W("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),Y={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:$,WorldTransform:z,Sprite:L,Camera:O,Canvas:H,Velocity:N,Parent:j,Children:X,BitmapText:V,SpineAnimation:G,RigidBody:P,BoxCollider:T,CircleCollider:C,CapsuleCollider:A};let J=0;function K(e,t){const s=++J;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Q(e){return{_type:"res",_resource:e}}class Z{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ee{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new Z(this.get(e),t=>this.set(e,t))}}const te=K({delta:0,elapsed:0,frameCount:0},"Time");function se(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class re{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>se(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,r=this.world_.getEntitiesWithComponents(this.allRequired_),n=s.length,o=e.length>0,i=t.length>0,a=new Array(n+1);let l=null,c=[];try{for(const u of r){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<n;e++)a[e+1]=this.world_.get(u,s[e]);if(o){for(let t=0;t<e.length;t++){const r=e[t];c.push({component:s[r],data:a[r+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class ne{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=D(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class oe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ne(this,null);return this.spawned_.push(e),e}entity(e){return new ne(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var ie;exports.Schedule=void 0,(ie=exports.Schedule||(exports.Schedule={}))[ie.Startup=0]="Startup",ie[ie.First=1]="First",ie[ie.PreUpdate=2]="PreUpdate",ie[ie.Update=3]="Update",ie[ie.PostUpdate=4]="PostUpdate",ie[ie.Last=5]="Last",ie[ie.FixedPreUpdate=10]="FixedPreUpdate",ie[ie.FixedUpdate=11]="FixedUpdate",ie[ie.FixedPostUpdate=12]="FixedPostUpdate";let ae=0;function le(e,t,s){const r=++ae;return{_id:Symbol(`System_${r}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${r}`}}function ce(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class ue{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof oe&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new re(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new oe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class de{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const he=K(new de,"Input");class pe{constructor(e){this.target_=e??null}build(e){const s=new de;e.insertResource(he,s),t().bindInputEvents({onKeyDown(e){s.keysDown.has(e)||s.keysPressed.add(e),s.keysDown.add(e)},onKeyUp(e){s.keysDown.delete(e),s.keysReleased.add(e)},onPointerMove(e,t){s.mouseX=e,s.mouseY=t},onPointerDown(e,t,r){s.mouseX=t,s.mouseY=r,s.mouseButtons.add(e),s.mouseButtonsPressed.add(e)},onPointerUp(e){s.mouseButtons.delete(e),s.mouseButtonsReleased.add(e)},onWheel(e,t){s.scrollDeltaX+=e,s.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(exports.Schedule.Last,le([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const fe=new pe;function me(e){const t={};for(const s of Object.keys(e)){const r=e[s];if(null==r||"object"!=typeof r||Array.isArray(r))t[s]=r;else{const e=r;t[s]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:me(e)}}return t}class ge{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){D(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,s){const r={};if(null!=s&&"object"==typeof s)for(const[e,t]of Object.entries(s))void 0!==t&&(r[e]=t);const n={...t._default,...r};if(this.cppRegistry_){const s=`add${t._cppName}`,r=this.cppRegistry_[s];r?.call(this.cppRegistry_,e,me(n))}return n}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const s=`get${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const s=`has${t._cppName}`;return this.cppRegistry_[s].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const s=`remove${t._cppName}`;this.cppRegistry_[s].call(this.cppRegistry_,e)}insertScript(e,t,s){const r=t.create(s);return this.getStorage(t).set(e,r),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,s=1/0;for(const r of e)if(!D(r)){const e=this.tsStorage_.get(r._id),n=e?e.size:0;n<s&&(s=n,t=e??null)}const r=[],n=t?t.keys():this.entities_;for(const t of n){let s=!0;for(const r of e)if(!this.has(t,r)){s=!1;break}s&&r.push(t)}return r}}var xe,ye,_e;exports.TextAlign=void 0,(xe=exports.TextAlign||(exports.TextAlign={}))[xe.Left=0]="Left",xe[xe.Center=1]="Center",xe[xe.Right=2]="Right",exports.TextVerticalAlign=void 0,(ye=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ye.Top=0]="Top",ye[ye.Middle=1]="Middle",ye[ye.Bottom=2]="Bottom",exports.TextOverflow=void 0,(_e=exports.TextOverflow||(exports.TextOverflow={}))[_e.Visible=0]="Visible",_e[_e.Clip=1]="Clip",_e[_e.Ellipsis=2]="Ellipsis";const we=B("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2,dirty:!0});class be{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,r=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const n=t&&t.size.x>0&&t.size.y>0,o=n?t.size.x:0,i=n?t.size.y:0,a=e.wordWrap&&n;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=n?Math.ceil(o):d+2*u,f=n?Math.ceil(i):h+2*u;if(n&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(r.width<p||r.height<f){const e=Math.max(r.width,this.nextPowerOf2(p)),t=Math.max(r.height,this.nextPowerOf2(f));r.width=e,r.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),x=Math.round(255*e.color.b),y=e.color.a;s.clearRect(0,0,r.width,r.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${x}, ${y})`,n&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const _=l.length*c;let w;if(n)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-_)/2;break;case exports.TextVerticalAlign.Bottom:w=f-_-u;break;default:w=u}else w=u;let b=w;for(const t of l){let r;switch(e.align){case exports.TextAlign.Left:r=u;break;case exports.TextAlign.Center:r=p/2;break;case exports.TextAlign.Right:r=p-u;break;default:r=u}s.fillText(t,r,b),b+=c}n&&e.overflow===exports.TextOverflow.Clip&&s.restore();const v=s.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const r=this.cache.get(e);if(r){this.module.getResourceManager().releaseTexture(r.textureHandle)}const n=this.renderText(t,s);return this.cache.set(e,n),n}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,r]of this.cache)e(s)||(t.releaseTexture(r.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),r=[];for(const e of s){if(!e){r.push("");continue}let s="";for(const n of e){const e=s+n;this.ctx.measureText(e).width>t&&s?(r.push(s),s=n):s=e}s&&r.push(s)}return r.length>0?r:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),r=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,r)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const ve=B("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Se{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new be(t),r=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{s.cleanupOrphaned(e=>r.valid(e)&&r.has(e,we));const e=r.getEntitiesWithComponents([we]);for(const t of e){const e=r.get(t,we);if(!e.dirty)continue;r.has(t,L)||r.insert(t,L,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const n=r.has(t,ve)?r.get(t,ve):null,o=s.renderForEntity(t,e,n),i=r.get(t,L);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,r.insert(t,L,i),e.dirty=!1}}))}}const Pe=new Se,Te=B("UIMask",{enabled:!0});function Ce(e,t){const s=Math.max(e.x,t.x),r=Math.max(e.y,t.y),n=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:r,w:Math.max(0,n-s),h:Math.max(0,o-r)}}function Ae(e,t,s,r,n,o,i,a,l,c,u){const d=e-s*n,h=e+s*(1-n),p=t-r*o,f=t+r*(1-o);function m(e,t){const s=i[0]*e+i[4]*t+i[12],r=i[1]*e+i[5]*t+i[13],n=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/n)+.5)*c,l+(.5*(r/n)+.5)*u]}const[g,x]=m(d,p),[y,_]=m(h,f),w=Math.min(g,y),b=Math.max(g,y),v=Math.min(x,_),S=Math.max(x,_);return{x:Math.round(w),y:Math.round(v),w:Math.round(b-w),h:Math.round(S-v)}}function Ee(e,t){const s=t??new Float32Array(16),r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],x=e[14],y=e[15],_=r*l-n*a,w=r*c-o*a,b=r*u-i*a,v=n*c-o*l,S=n*u-i*l,P=o*u-i*c,T=d*g-h*m,C=d*x-p*m,A=d*y-f*m,E=h*x-p*g,M=h*y-f*g,R=p*y-f*x;let I=_*R-w*M+b*E+v*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*M+u*E)*I,s[1]=(o*M-n*R-i*E)*I,s[2]=(g*P-x*S+y*v)*I,s[3]=(p*S-h*P-f*v)*I,s[4]=(c*A-a*R-u*C)*I,s[5]=(r*R-o*A+i*C)*I,s[6]=(x*b-m*P-y*w)*I,s[7]=(d*P-p*b+f*w)*I,s[8]=(a*M-l*A+u*T)*I,s[9]=(n*A-r*M-i*T)*I,s[10]=(m*S-g*b+y*_)*I,s[11]=(h*b-d*S-f*_)*I,s[12]=(l*C-a*E-c*T)*I,s[13]=(r*E-n*C+o*T)*I,s[14]=(g*w-m*v-x*_)*I,s[15]=(d*v-h*w+p*_)*I),s}function Me(e,t,s,r,n,o,i){const a=(e-r)/o*2-1,l=(t-n)/i*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function Re(e,t,s,r,n,o,i,a){return e>=s-n*i&&e<=s+n*(1-i)&&t>=r-o*a&&t<=r+o*(1-a)}function Ie(e,t,s,r,n,o,i){if(!e.has(t,ve)||!e.has(t,z))return null;const a=e.get(t,ve),l=e.get(t,z),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Ae(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,s,r,n,o,i)}function Be(e,t){return(s,r,n,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Te]);if(0!==l.length)try{!function(e,t,s,r,n,o,i,a,l){const c=new Set;for(const e of r){t.get(e,Te).enabled&&c.add(e)}const u=[];for(const e of r){if(!c.has(e))continue;let s=!0,r=e;for(;t.has(r,j);){const e=t.get(r,j);if(c.has(e.entity)){s=!1;break}r=e.entity}s&&u.push(e)}function d(r,u){const h=e.getChildEntities(s,r);for(const s of h){let r=u;if(c.has(s)){const e=Ie(t,s,n,o,i,a,l);e&&(r=Ce(u,e))}e.renderer_setEntityClipRect(s,r.x,r.y,r.w,r.h),d(s,r)}}for(const e of u){const s=Ie(t,e,n,o,i,a,l);s&&d(e,s)}}(e,t,s,l,r,n,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Ue{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Be(e.wasmModule,e.world))}}const Fe=new Ue,ke=B("Interactable",{enabled:!0}),We=B("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var De;exports.ButtonState=void 0,(De=exports.ButtonState||(exports.ButtonState={}))[De.Normal=0]="Normal",De[De.Hovered=1]="Hovered",De[De.Pressed=2]="Pressed",De[De.Disabled=3]="Disabled";const $e=B("Button",{state:exports.ButtonState.Normal,transition:null});class ze{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const Le=K(new ze,"UIEvents"),Oe=K({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),He=new Float32Array(16);class Ne{build(e){const t=e.world,s=new ze;e.insertResource(Le,s);let r=null,n=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(he),Q(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([We]);for(const e of i){const s=t.get(e,We);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Ee(o.viewProjection,He);const u=Me(l,c,He,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([ke,ve,z]);let h=null,p=-1/0;for(const e of d){t.has(e,We)||t.insert(e,We);if(!t.get(e,ke).enabled)continue;const s=t.get(e,z),r=t.get(e,ve),n=r.size.x*s.scale.x,o=r.size.y*s.scale.y;if(Re(u.x,u.y,s.position.x,s.position.y,n,o,r.pivot.x,r.pivot.y)){let s=0;t.has(e,L)&&(s=t.get(e,L).layer),s>=p&&(p=s,h=e)}}if(r!==h){if(null!==r&&t.valid(r)&&t.has(r,We)){t.get(r,We).hovered=!1,s.emit(r,"hover_exit")}if(null!==h){t.get(h,We).hovered=!0,s.emit(h,"hover_enter")}r=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,We);e.pressed=!0,e.justPressed=!0,n=h,s.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==n){if(t.valid(n)&&t.has(n,We)){const e=t.get(n,We);e.pressed=!1,e.justReleased=!0,s.emit(n,"release"),n===r&&s.emit(n,"click")}n=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,le([],()=>{const e=t.getEntitiesWithComponents([$e]);for(const s of e){if(t.has(s,ke)||t.insert(s,ke,{enabled:!0}),!t.has(s,We))continue;const e=t.get(s,We),r=t.get(s,$e),n=t.get(s,ke),o=r.state;if(n.enabled?e.pressed?r.state=exports.ButtonState.Pressed:e.hovered?r.state=exports.ButtonState.Hovered:r.state=exports.ButtonState.Normal:r.state=exports.ButtonState.Disabled,o!==r.state&&r.transition&&t.has(s,L)){const e=t.get(s,L),n=r.transition;switch(r.state){case exports.ButtonState.Normal:e.color={...n.normalColor};break;case exports.ButtonState.Hovered:e.color={...n.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...n.pressedColor};break;case exports.ButtonState.Disabled:e.color={...n.disabledColor}}t.insert(s,L,e)}}},{name:"ButtonSystem"}))}}const je=new Ne,Xe=U("ScreenSpace");function Ve(e,t,s,r,n,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,m;if(l===c&&u===d){const e=l+s.x,t=u+s.y,r=.5*n.x,o=.5*n.y;h=e-r,p=t-o,f=e+r,m=t+o}else h=l+s.x,p=u+s.y,f=c+r.x,m=d+r.y;return{centerX:.5*(h+f),centerY:.5*(p+m),width:f-h,height:m-p,rect:{left:h,bottom:p,right:f,top:m}}}function Ge(e,t,s,r,n,o){if(!e.has(t,ve))return;const i=e.get(t,ve),a=Ve(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,$);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-r,l.position.y=a.centerY-n),e.insert(t,$,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&Ge(e,t,a.rect,a.centerX,a.centerY,!1)}class Ye{build(e){const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Oe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},r=.5*(s.left+s.right),n=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([Xe,ve,$]);for(const e of o)Ge(t,e,s,r,n,!0)},{name:"UILayoutSystem"}))}}const qe=new Ye,Je=B("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class Ke{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,r=new Map,n=i(512,64),o=n.getContext("2d",{willReadFrequently:!0});let a=null,l=!1,c=!0,u=0,d=0;const h=function(){const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();function p(){if(null===a||!s.valid(a))return;const t=s.get(a,Je);if(t.readOnly)return;let r=h.value;if(t.maxLength>0&&r.length>t.maxLength&&(r=r.substring(0,t.maxLength),h.value=r),r!==t.value){t.value=r;e.getResource(Le).emit(a,"change")}t.cursorPos=h.selectionStart??r.length,t.dirty=!0,g()}function f(e){if(a===e)return;m();const t=s.get(e,Je);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==a&&s.valid(a)&&s.has(a,Je)){const e=s.get(a,Je);e.focused=!1,e.dirty=!0}a=null,h.blur()}function g(){c=!0,u=0}function x(e,i,a,l){(n.width<a||n.height<l)&&(n.width=Ze(Math.max(n.width,a)),n.height=Ze(Math.max(n.height,l))),o.clearRect(0,0,n.width,n.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,l),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,l),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=Qe(o,h,a-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=f}else{const e=(l-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&c){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,r;if(i.multiline){const e=Qe(o,i.value.substring(0,i.cursorPos),a-2*m),n=e.length>0?e[e.length-1]:"";t=m+o.measureText(n).width,s=m+(e.length-1)*f,r=f}else t=m+o.measureText(e).width,s=(l-i.fontSize)/2,r=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,r)}o.restore();const g=o.getImageData(0,0,a,l),x=new Uint8Array(g.data.buffer),y=t.getResourceManager(),_=t._malloc(x.length);t.HEAPU8.set(x,_);const w=r.get(e);void 0!==w&&y.releaseTexture(w);const b=y.createTexture(a,l,_,x.length,1,!0);r.set(e,b),t._free(_);const v=s.get(e,L);v.texture=b,v.size.x=a,v.size.y=l,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},s.insert(e,L,v)}h.addEventListener("input",()=>{l||null===a||p()}),h.addEventListener("compositionstart",()=>{l=!0}),h.addEventListener("compositionend",()=>{l=!1,p()}),h.addEventListener("keydown",t=>{if(null===a)return;if("Escape"===t.key)return void m();const r=s.get(a,Je);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(Le).emit(a,"submit"),void m()}}),h.addEventListener("blur",()=>{if(null!==a&&s.valid(a)&&s.has(a,Je)){const e=s.get(a,Je);e.focused=!1,e.dirty=!0}a=null}),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([Q(Le)],e=>{const t=s.getEntitiesWithComponents([Je,ke]);for(const e of t){if(!s.has(e,We))continue;if(s.get(e,We).justPressed)return void f(e)}if(null!==a){const e=s.getEntitiesWithComponents([ke]);for(const t of e){if(s.has(t,Je))continue;if(!s.has(t,We))continue;if(s.get(t,We).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,le([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),n=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=n,u>=.5&&(u-=.5,c=!c,null!==a&&s.valid(a)&&s.has(a,Je)))){s.get(a,Je).dirty=!0}const o=t.getResourceManager();for(const[e,t]of r)s.valid(e)&&s.has(e,Je)||(o.releaseTexture(t),r.delete(e));const i=s.getEntitiesWithComponents([Je,ve]);for(const e of i){const t=s.get(e,Je);if(!t.dirty)continue;const r=s.get(e,ve),n=Math.ceil(r.size.x),o=Math.ceil(r.size.y);n<=0||o<=0||(s.has(e,L)||s.insert(e,L,{texture:b,color:{r:1,g:1,b:1,a:1},size:{x:n,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),x(e,t,n,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Qe(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const r=t.split("\n"),n=[];for(const t of r){if(!t){n.push("");continue}let r="";for(const o of t){const t=r+o;e.measureText(t).width>s&&r?(n.push(r),r=o):r=t}r&&n.push(r)}return n.length>0?n:[""]}function Ze(e){let t=1;for(;t<e;)t*=2;return t}const et=new Ke;var tt;function st(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(tt=exports.BlendMode||(exports.BlendMode={}))[tt.Normal=0]="Normal",tt[tt.Additive=1]="Additive",tt[tt.Multiply=2]="Multiply",tt[tt.Screen=3]="Screen",tt[tt.PremultipliedAlpha=4]="PremultipliedAlpha";let rt=null,nt=null,ot=1;const it=new Map;function at(e){rt=e,nt=e.getResourceManager(),xt()}function lt(){0!==ht&&rt&&(rt._free(ht),ht=0),it.clear(),ot=1,dt=!1,nt=null,rt=null}function ct(){if(!nt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return nt}const ut={createShader:(e,t)=>ct().createShader(e,t),releaseShader(e){e>0&&ct().releaseShader(e)},create(e){const t=ot++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,r]of Object.entries(e.uniforms))s.uniforms.set(t,r);return it.set(t,s),t},get:e=>it.get(e),setUniform(e,t,s){const r=it.get(e);r&&r.uniforms.set(t,s)},getUniform(e,t){const s=it.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=it.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=it.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=it.get(e);s&&(s.depthTest=t)},getShader(e){const t=it.get(e);return t?.shader??0},release(e){it.delete(e)},isValid:e=>it.has(e),createFromAsset(e,t){const s={};for(const[t,r]of Object.entries(e.properties))if("number"==typeof r)s[t]=r;else if("object"==typeof r&&null!==r){const e=r;"a"in e?s[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?s[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(s[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:s,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=it.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ot++,r={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return it.set(s,r),s},toAssetData(e,t){const s=it.get(e);if(!s)return null;const r={};for(const[e,t]of s.uniforms)r[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:r}},getUniforms(e){const t=it.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let dt=!1,ht=0;const pt=4096,ft=new Map;let mt=null;function gt(e){const t=(0===ht&&rt&&(ht=rt._malloc(pt)),ht);if(0===t||!rt)return{ptr:0,count:0};let s=0,r=0;const n=rt.HEAPU8,o=rt.HEAPU32,i=rt.HEAPF32;for(const[a,l]of e){if(s+128>pt)break;let e=ft.get(a);e||(mt||(mt=new TextEncoder),e=mt.encode(a),ft.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+s>>2]=c,s+=4,n.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;r++}return{ptr:t,count:r}}function xt(){if(!rt||dt)return;rt.materialDataProvider=(e,t,s,r,n)=>{const o=it.get(e);if(!o)return rt.HEAPU32[t>>2]=0,rt.HEAPU32[s>>2]=0,rt.HEAPU32[r>>2]=0,void(rt.HEAPU32[n>>2]=0);rt.HEAPU32[t>>2]=o.shader,rt.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=gt(o.uniforms);rt.HEAPU32[r>>2]=i,rt.HEAPU32[n>>2]=a},dt=!0}const yt={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class _t{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const s=this.pending_.get(e);if(s)return s;const r=this.loadInternal(e);this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(ut.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())ut.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await n(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const r=JSON.parse(s);if("material"!==r.type)throw new Error(`Invalid material file type: ${r.type}`);const i=this.resolveShaderPath(e,r.shader),a=await this.shaderLoader_.load(i);return{handle:ut.createFromAsset(r,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function wt(e,t){const s=new Map;for(const r of t.entities){const t=e.spawn();s.set(r.id,t),e.insert(t,Y,{value:r.name});for(const s of r.components)vt(e,t,s)}for(const r of t.entities)if(null!==r.parent){const t=s.get(r.id),n=s.get(r.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return s}async function bt(e,t,s){const r=new Map,n=s?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();r.set(i.id,t),e.insert(t,Y,{value:i.name});for(const r of i.components){if("Sprite"===r.type&&n){const e=r.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,r=t.startsWith("data:")?t:s?.assetBaseUrl?`${s.assetBaseUrl}/${t}`:`/${t}`;try{const s=await n.loadTexture(r);e.texture=s.handle,o.set(t,r)}catch(t){console.warn(`Failed to load texture: ${r}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===r.type&&n){const e=r.data;if("string"==typeof e.font&&e.font)try{const t=await n.loadBitmapFont(e.font,s?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===r.type&&n){const e=r.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await n.loadSpine(t,o,s?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await n.loadMaterial(e.material,s?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}vt(e,t,r)}}for(const s of t.entities)if(null!==s.parent){const t=r.get(s.id),n=r.get(s.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}function vt(e,t,s){const r=s.data;switch(s.type){case"LocalTransform":e.insert(t,$,r);break;case"Sprite":e.insert(t,L,r);break;case"Camera":e.insert(t,O,r);break;case"Canvas":e.insert(t,H,r);break;case"Text":e.insert(t,we,r);break;case"BitmapText":e.insert(t,V,r);break;case"SpineAnimation":e.insert(t,G,r);break;case"UIRect":{const s=r;s.anchor&&!s.anchorMin&&(s.anchorMin={...s.anchor},s.anchorMax={...s.anchor},delete s.anchor),e.insert(t,ve,s);break}case"UIMask":e.insert(t,Te,r);break;case"Interactable":e.insert(t,ke,r);break;case"Button":e.insert(t,$e,r);break;case"RigidBody":e.insert(t,P,r);break;case"BoxCollider":e.insert(t,T,r);break;case"CircleCollider":e.insert(t,C,r);break;case"CapsuleCollider":e.insert(t,A,r);break;default:{const n=F(s.type);n?e.insert(t,n,r):console.warn(`Unknown component type: ${s.type}`);break}}}class St{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const s=this.cache_.get(e);if(void 0!==s)return s;const r=this.pending_.get(e);if(r)return r;const n=t();this.pending_.set(e,n);try{const t=await n;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class Pt{constructor(e){this.textureCache_=new St,this.shaderCache_=new St,this.jsonCache_=new St,this.textCache_=new St,this.binaryCache_=new St,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new St,this.prefabCache_=new St,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=i(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new _t(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const r=this.textureCacheKey(e,s),n=this.textureCache_.get(r);n&&(t.releaseTexture(n.handle),this.textureCache_.delete(r))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}async loadSpine(e,t,s){const r=`${e}:${t}`;if(this.loadedSpines_.has(r))return{success:!0};try{const n=this.resolveUrl(t,s),o=await this.fetchText(n);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,r=this.resolveUrl(t,s);try{const e=await this.loadTextureRaw(r);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(r),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(s):this.loadFntFile(s))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),r="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!r)throw new Error("Invalid bmfont asset: no fnt file specified");const n=s?`${s}/${r}`:r;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const r=s[1],n=e.substring(0,e.lastIndexOf("/")),o=n?`${n}/${r}`:r,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return bt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},s=[];if(e.textures)for(const r of e.textures)s.push(this.loadTexture(r).then(e=>{t.textures.set(r,e)}));if(e.materials)for(const r of e.materials)s.push(this.loadMaterial(r).then(e=>{t.materials.set(r,e)}));if(e.spine)for(const r of e.spine){const e=`${r.skeleton}:${r.atlas}`;s.push(this.loadSpine(r.skeleton,r.atlas,r.baseUrl).then(s=>{t.spine.set(e,s)}))}if(e.json)for(const r of e.json)s.push(this.loadJson(r).then(e=>{t.json.set(r,e)}));if(e.text)for(const r of e.text)s.push(this.loadText(r).then(e=>{t.text.set(r,e)}));if(e.binary)for(const r of e.binary)s.push(this.loadBinary(r).then(e=>{t.binary.set(r,e)}));return await Promise.all(s),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups)){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const r of e)switch(r.type){case"texture":s.push(this.loadTexture(r.path).then(e=>{t.textures.set(r.path,e)}));break;case"material":s.push(this.loadMaterial(r.path).then(e=>{t.materials.set(r.path,e)}));break;case"json":s.push(this.loadJson(r.path).then(e=>{t.json.set(r.path,e)}));break;case"text":s.push(this.loadText(r.path).then(e=>{t.text.set(r.path,e)}));break;default:s.push(this.loadBinary(r.path).then(e=>{t.binary.set(r.path,e)}))}return await Promise.all(s),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,r=this.embedded_.get(s);if(this.embeddedOnly_&&!r)throw new Error(`Asset not embedded: ${e}`);const n=r??s;return new Promise((s,r)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>r(new Error(`Failed to load image: ${e}`)),o.src=n})}createTextureFromImage(e,t){const{width:s,height:r}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,s,r,t):this.createTextureFallback(e,s,r,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,r,n){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,r),width:s,height:r}}createTextureFallback(e,t,s,r){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,r);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const r=255/s;e[t]=Math.min(255,Math.round(e[t]*r)),e[t+1]=Math.min(255,Math.round(e[t+1]*r)),e[t+2]=Math.min(255,Math.round(e[t+2]*r))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:r,fragment:n}=this.parseEsShader(t);if(!r||!n)throw new Error(`Invalid shader format: ${e}`);return ut.createShader(r,n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const r=await n(t);if(!r)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(r);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return ut.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await n(t);return JSON.parse(r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch JSON: ${e} (${r.status})`);return r.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch text: ${e} (${r.status})`);return r.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const r=s.split("/").filter(e=>e);let n="";for(const e of r){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Tt=K(null,"Assets");class Ct{build(e){const t=e.wasmModule;t?e.insertResource(Tt,new Pt(t)):console.warn("AssetPlugin: No WASM module available")}}const At=new Ct;async function Et(e,t,s){const{entities:r,rootId:n}=await Mt(t,s?.overrides??[],s),o={version:t.version,name:t.name,entities:r.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components}))},i=await bt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(n);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}async function Mt(e,t,s,r){const n=new Map;let o;if(void 0===r){o=0;for(const t of e.entities)t.nestedPrefab||(n.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=r;for(const t of e.entities)t.nestedPrefab||n.set(t.prefabEntityId,o++)}const i=[];for(const r of e.entities){if(r.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${r.nestedPrefab.prefabPath}`);const e=await s.assetServer.loadPrefab(r.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Mt(e,r.nestedPrefab.overrides,s,o);n.set(r.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==r.parent?n.get(r.parent)??null:null),i.push(...t.entities);continue}const a=n.get(r.prefabEntityId),l=r.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:r.prefabEntityId,name:r.name,parent:l?null:null!==r.parent?n.get(r.parent)??null:null,children:r.children.map(e=>n.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(r.components)),visible:r.visible};Rt(c,t),i.push(c)}const a=n.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Rt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class It{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=await this.assetServer_.loadPrefab(e,t?.baseUrl);return Et(this.world_,s,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Bt=K(null,"Prefabs");class Ut{build(e){const t=e.getResource(Tt);t?e.insertResource(Bt,new It(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const Ft=new Ut;let kt=null,Wt=0,Dt=0,$t=0;const zt=new Float32Array(256);function Lt(e){kt=e,Wt=kt._malloc(64),Dt=kt._malloc(64),$t=kt._malloc(1024)}function Ot(){kt&&(Wt&&(kt._free(Wt),Wt=0),Dt&&(kt._free(Dt),Dt=0),$t&&(kt._free($t),$t=0)),kt=null}function Ht(){if(!kt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return kt}const Nt={r:1,g:1,b:1,a:1},jt={begin(e){const t=Ht();t.HEAPF32.set(e,Wt/4),t.draw_begin(Wt)},end(){Ht().draw_end()},line(e,t,s,r=1){Ht().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},rect(e,t,s,r=!0){Ht().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},rectOutline(e,t,s,r=1){Ht().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,r)},circle(e,t,s,r=!0,n=32){Ht().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,r,n)},circleOutline(e,t,s,r=1,n=32){Ht().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,r,n)},texture(e,t,s,r=Nt){Ht().draw_texture(e.x,e.y,t.x,t.y,s,r.r,r.g,r.b,r.a)},textureRotated(e,t,s,r,n=Nt){Ht().draw_textureRotated(e.x,e.y,t.x,t.y,s,r,n.r,n.g,n.b,n.a)},setLayer(e){Ht().draw_setLayer(e)},setDepth(e){Ht().draw_setDepth(e)},getDrawCallCount:()=>kt?kt.draw_getDrawCallCount():0,getPrimitiveCount:()=>kt?kt.draw_getPrimitiveCount():0,setBlendMode(e){Ht().draw_setBlendMode(e)},setDepthTest(e){Ht().draw_setDepthTest(e)},drawMesh(e,t,s){const r=Ht();r.HEAPF32.set(s,Dt/4),r.draw_mesh(e,t,Dt)},drawMeshWithMaterial(e,t,s){const r=Ht(),n=ut.get(t);if(!n)return;if(jt.setBlendMode(n.blendMode),jt.setDepthTest(n.depthTest),0===n.uniforms.size)return void jt.drawMesh(e,n.shader,s);r.HEAPF32.set(s,Dt/4);let o=0,i=0;for(const[e,t]of n.uniforms){const s=Vt(e);if(!(s<0)){if(st(t))zt[o++]=10,zt[o++]=s,zt[o++]=t.slot??i++,zt[o++]=t.textureId;else if("number"==typeof t)zt[o++]=1,zt[o++]=s,zt[o++]=t;else if(Array.isArray(t)){zt[o++]=t.length,zt[o++]=s;for(let e=0;e<t.length;e++)zt[o++]=t[e]}else"w"in t?(zt[o++]=4,zt[o++]=s,zt[o++]=t.x,zt[o++]=t.y,zt[o++]=t.z,zt[o++]=t.w):"z"in t?(zt[o++]=3,zt[o++]=s,zt[o++]=t.x,zt[o++]=t.y,zt[o++]=t.z):(zt[o++]=2,zt[o++]=s,zt[o++]=t.x,zt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(r.HEAPF32.set(zt.subarray(0,o),$t/4),r.draw_meshWithUniforms(e,n.shader,Dt,$t,o)):r.draw_mesh(e,n.shader,Dt)}},Xt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Vt(e){return Xt[e]??-1}var Gt;exports.DataType=void 0,(Gt=exports.DataType||(exports.DataType={}))[Gt.Float=1]="Float",Gt[Gt.Float2=2]="Float2",Gt[Gt.Float3=3]="Float3",Gt[Gt.Float4=4]="Float4",Gt[Gt.Int=5]="Int",Gt[Gt.Int2=6]="Int2",Gt[Gt.Int3=7]="Int3",Gt[Gt.Int4=8]="Int4";let Yt=null,qt=0,Jt=0,Kt=0;function Qt(e){Yt=e,qt=Yt._malloc(262144),Jt=Yt._malloc(65536),Kt=Yt._malloc(256)}function Zt(){Yt&&(qt&&Yt._free(qt),Jt&&Yt._free(Jt),Kt&&Yt._free(Kt),qt=0,Jt=0,Kt=0),Yt=null}function es(){if(!Yt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Yt}const ts={create(e){const t=es(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const r=e.vertices.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);t.HEAPF32.set(e.vertices,qt/4);const n=e.layout.length,o=new Int32Array(n);for(let t=0;t<n;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Kt,n).set(o),t.geometry_init(s,qt,r,Kt,n,e.dynamic??!1),e.indices){const r=e.indices.length;if(4*r>65536)throw new Error(`Index data too large: ${r} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Jt,r).set(e.indices),t.geometry_setIndices16(s,Jt,r)}else{new Uint32Array(t.HEAPU8.buffer,Jt,r).set(e.indices),t.geometry_setIndices32(s,Jt,r)}}return s},updateVertices(e,t,s=0){const r=es(),n=t.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);r.HEAPF32.set(t,qt/4),r.geometry_updateVertices(e,qt,n,s)},release(e){e>0&&es().geometry_release(e)},isValid:e=>!(!Yt||e<=0)&&Yt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,r=t/2;return ts.create({vertices:new Float32Array([-s,-r,0,0,s,-r,1,0,s,r,1,1,-s,r,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],r=[];s.push(0,0,.5,.5);for(let r=0;r<=t;r++){const n=r/t*Math.PI*2,o=Math.cos(n)*e,i=Math.sin(n)*e,a=(Math.cos(n)+1)/2,l=(Math.sin(n)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)r.push(0,e,e+1);return ts.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,r=-1/0,n=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),r=Math.max(r,o.x),n=Math.max(n,o.y);const o=[];for(const i of e){const e=(i.x-t)/(r-t),a=(i.y-s)/(n-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return ts.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let ss=null;function rs(e){ss=e}function ns(){ss&&is.isInitialized()&&is.shutdown(),ss=null}function os(){if(!ss)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ss}const is={init:(e,t)=>os().postprocess_init(e,t),shutdown(){os().postprocess_shutdown()},resize(e,t){os().postprocess_resize(e,t)},addPass:(e,t)=>os().postprocess_addPass(e,t),removePass(e){os().postprocess_removePass(e)},setEnabled(e,t){os().postprocess_setPassEnabled(e,t)},isEnabled:e=>os().postprocess_isPassEnabled(e),setUniform(e,t,s){os().postprocess_setUniformFloat(e,t,s)},setUniformVec4(e,t,s){os().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)},begin(){os().postprocess_begin()},end(){os().postprocess_end()},getPassCount:()=>os().postprocess_getPassCount(),isInitialized:()=>!!ss&&ss.postprocess_isInitialized(),setBypass(e){os().postprocess_setBypass(e)},isBypassed:()=>!ss||ss.postprocess_isBypassed(),createBlur:()=>ut.createShader(as,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>ut.createShader(as,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>ut.createShader(as,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>ut.createShader(as,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},as="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ls;exports.RenderStage=void 0,(ls=exports.RenderStage||(exports.RenderStage={}))[ls.Background=0]="Background",ls[ls.Opaque=1]="Opaque",ls[ls.Transparent=2]="Transparent",ls[ls.Overlay=3]="Overlay";let cs=null,us=0;function ds(e){cs=e,us=cs._malloc(64)}function hs(){cs&&us&&(cs._free(us),us=0),cs=null}const ps={init(e,t){cs?.renderer_init(e,t)},resize(e,t){cs?.renderer_resize(e,t)},begin(e,t){cs&&us&&(cs.HEAPF32.set(e,us/4),cs.renderer_begin(us,t??0))},flush(){cs?.renderer_flush()},end(){cs?.renderer_end()},submitSprites(e){cs&&cs.renderer_submitSprites(e._cpp)},submitBitmapText(e){cs&&cs.renderer_submitBitmapText(e._cpp)},submitSpine(e){cs&&cs.renderer_submitSpine?.(e._cpp)},setStage(e){cs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>cs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){cs?.renderer_releaseTarget(e)},getTargetTexture:e=>cs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>cs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,r){cs?.renderer_setClearColor?.(e,t,s,r)},setViewport(e,t,s,r){cs?.renderer_setViewport(e,t,s,r)},setScissor(e,t,s,r,n){cs?.renderer_setScissor(e,t,s,r,n)},clearBuffers(e){cs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,r)=>cs?cs.getResourceManager().measureBitmapText(e,t,s,r):{width:0,height:0},getStats:()=>cs?{drawCalls:cs.renderer_getDrawCalls(),triangles:cs.renderer_getTriangles(),sprites:cs.renderer_getSprites(),text:cs.renderer_getText(),spine:cs.renderer_getSpine?.()??0,meshes:cs.renderer_getMeshes(),culled:cs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let fs=null;function ms(e){fs=e}function gs(){fs=null}const xs={enable(){fs?.gl_enableErrorCheck(!0)},disable(){fs?.gl_enableErrorCheck(!1)},check:e=>fs?.gl_checkErrors(e)??0,diagnose(){fs?.renderer_diagnose()}},ys=new Map;function _s(e){ys.delete(e)}class ws{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:s,width:r,height:n,elapsed:o}=e;r===this.lastWidth_&&n===this.lastHeight_||(ps.resize(r,n),is.isInitialized()&&is.getPassCount()>0&&is.resize(r,n),this.lastWidth_=r,this.lastHeight_=n),ps.setViewport(0,0,r,n),ps.clearBuffers(3),ps.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,r,n),ps.submitSprites(t),ps.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ps.submitSpine(t),ps.flush(),this.executeDrawCallbacks(s,o),ps.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:r,clearFlags:n,elapsed:o}=e;ps.setViewport(r.x,r.y,r.w,r.h),ps.setScissor(r.x,r.y,r.w,r.h,!0),ps.clearBuffers(n),ps.setScissor(0,0,0,0,!1),ps.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,r.x,r.y,r.w,r.h),ps.submitSprites(t),ps.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):ps.submitSpine(t),ps.flush(),this.executeDrawCallbacks(s,o),ps.end()}executeDrawCallbacks(e,t){const s=ys;if(s.size>0){jt.begin(e);const r=[];for(const[e,n]of s.entries())try{n(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),r.push(e)}jt.end();for(const e of r)_s(e)}}}class bs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=t/1e3;for(this.updateTime(s),this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate);this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ge,this.resources_=new ee;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ue(this.world_,this.resources_),this.resources_.insert(te,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,gs(),hs(),ns(),Zt(),lt(),Ot()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(te);t.delta=e,t.elapsed+=e,t.frameCount++}}const vs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ss(e,t,s,r,n){const o=e*t/s,i=e;switch(r){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=n;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Ps(e,t,s,r){if(0===s||0===r)return[];const n=e.registry_getCameraEntities(t);if(0===n.length)return[];const o=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),i=[];for(const e of n){const n=t.getCamera(e),a=t.getLocalTransform(e),l={x:n.viewportX,y:n.viewportY,w:n.viewportW,h:n.viewportH},c=l.w*s/(l.h*r);let u,d=0,h=0;if(1===n.projectionType){if(h=n.orthoSize,o){h=Ss(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=Cs(-d,d,-h,h,-n.farPlane,n.farPlane)}else u=Es(n.fov*Math.PI/180,c,n.nearPlane,n.farPlane);const p=Rs(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Is(u,p),viewportRect:l,clearFlags:n.clearFlags,priority:n.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Ts=new Float32Array(16);function Cs(e,t,s,r,n,o){const i=Ts;i.fill(0);const a=t-e,l=r-s,c=o-n;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(r+s)/l,i[14]=-(o+n)/c,i[15]=1,i}const As=new Float32Array(16);function Es(e,t,s,r){const n=As;n.fill(0);const o=1/Math.tan(e/2),i=s-r;return n[0]=o/t,n[5]=o,n[10]=(r+s)/i,n[11]=-1,n[14]=2*r*s/i,n}const Ms=new Float32Array(16);function Rs(e,t,s){const r=Ms;return r[0]=1,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=1,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=1,r[11]=0,r[12]=-e,r[13]=-t,r[14]=-s,r[15]=1,r}function Is(e,t){const s=new Float32Array(16);for(let r=0;r<4;r++)for(let n=0;n<4;n++)s[4*n+r]=e[0+r]*t[4*n+0]+e[4+r]*t[4*n+1]+e[8+r]*t[4*n+2]+e[12+r]*t[4*n+3];return s}async function Bs(e,t){if(t)return t();return(0,(await import(e)).default)()}const Us=K({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Fs=K(null,"PhysicsAPI");function ks(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ws(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Ds{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Us,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,r=Bs(this.wasmUrl_,this.factory_).then(r=>{r._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const n=function(e){const t=e.world.getEntitiesWithComponents([H]);for(const s of t){const t=e.world.get(s,H);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/n,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,le([Q(te)],a=>{const l=i.getEntitiesWithComponents([P,$,z]),c=new Set;for(const n of l){c.add(n);const a=i.get(n,P),l=i.get(n,z);if(t.has(n)){const e=s.get(n);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(r._physics_updateBodyProperties(n,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=ks(l.rotation);r._physics_createBody(n,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),$s(e,r,n),t.add(n),s.set(n,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===E.Kinematic){const e=ks(l.rotation);r._physics_setBodyTransform(n,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(r._physics_destroyBody(e),t.delete(e),s.delete(e));r._physics_step(a.delta),function(e,t,s){const r=t._physics_getDynamicBodyCount();if(0===r)return;const n=t._physics_getDynamicBodyTransforms(),o=n>>2;for(let n=0;n<r;n++){const r=o+4*n,i=t.HEAPU32[r],a=t.HEAPF32[r+1]*s,l=t.HEAPF32[r+2]*s,c=t.HEAPF32[r+3];if(!e.world.valid(i))continue;const u=e.world.get(i,$);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,j)){const t=e.world.get(i,j);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,z)){const s=e.world.get(t.entity,z),r=ks(s.rotation),n=a-s.position.x,o=l-s.position.y,i=Math.cos(-r),u=Math.sin(-r);d=(n*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(n*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=c-r}}u.position.x=d,u.position.y=h;const f=Ws(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,$,u)}}(e,r,n),function(e,t,s){t._physics_collectEvents();const r=[],n=t._physics_getCollisionEnterCount();if(n>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<n;o++){const n=e+6*o;r.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1],normalX:t.HEAPF32[n+2],normalY:t.HEAPF32[n+3],contactX:t.HEAPF32[n+4]*s,contactY:t.HEAPF32[n+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const r=e+2*s;o.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const r=e+2*s;a.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const r=e+2*s;c.push({sensorEntity:t.HEAPU32[r],visitorEntity:t.HEAPU32[r+1]})}}e.insertResource(Us,{collisionEnters:r,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,r,n)},{name:"PhysicsSystem"})),e.__physicsModule=r,e.insertResource(Fs,zs._fromModule(r)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=r}}function $s(e,t,s){const r=e.world;if(r.has(s,T)){const e=r.get(s,T);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(s,C)){const e=r.get(s,C);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(r.has(s,A)){const e=r.get(s,A);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class zs{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(zs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Ls(e,t,s=!0){const r=e.getResourceManager(),n=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,n);const o=r.createTexture(t.width,t.height,n,t.pixels.length,1,s);return e._free(n),o}function Os(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function Hs(e,t,s,r){const n=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(r?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,x=l*h,y=l*p,_=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(x+_))*n,(m+v)*n,(g-b)*n,0,(m-v)*o,(1-(f+_))*o,(y+w)*o,0,(g+b)*i,(y-w)*i,(1-(f+x))*i,0,e.position.x,e.position.y,e.position.z,1])}async function Ns(e,t,s,r,n,o,i){const a=await async function(e,t,s){const r={};for(const n of t.entities)for(const t of n.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const n=t.data.texture;if(void 0!==r[n])continue;try{r[n]=Ls(e,await s.loadPixels(n))}catch{r[n]=0}}return r}(t,s,r);!function(e,t,s){if(!t.textureMetadata)return;const r=e.getResourceManager();for(const e in t.textureMetadata){const n=s[e];if(n&&n>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;r.setTextureMetadata(n,e.left,e.right,e.top,e.bottom)}}}}(t,s,a);let l={},c=null;if(n&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(n),l=await async function(e,t,s,r,n){const o={};for(const i of r.entities)for(const r of i.components){if("SpineAnimation"!==r.type||!r.data)continue;const i=r.data.skeletonPath,a=r.data.atlasPath;if(!i||!a)continue;const l=n.resolvePath(i),c=n.resolvePath(a);try{const r=n.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=n.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=n.readText(i),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,r,r.length,u);if(t._free(d),p<0)continue;o[i]=p;const f=Os(r),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<f.length;t++){const r=m+"/"+f[t];try{const o=n.loadPixelsRaw?await n.loadPixelsRaw(r):await n.loadPixels(r),i=Ls(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,n,c,s,r)),o){new Ds("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,s){const r={};for(const n of t.entities)for(const t of n.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const n=t.data.font;if(void 0===r[n])try{let t,o;if(n.endsWith(".bmfont")){const e=JSON.parse(s.readText(n)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){r[n]=0;continue}const a=n.substring(0,n.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=s.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=s.readText(n),o=n.substring(0,n.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){r[n]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(a):await s.loadPixels(a),c=Ls(e,l,!1),u=e.getResourceManager();r[n]=u.loadBitmapFont(t,c,l.width,l.height)}catch{r[n]=0}}return r}(t,s,r),d=function(e,t){const s={},r={};for(const n of e.entities)for(const e of n.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const n=e.data.material;if(void 0===s[n])try{const e=JSON.parse(t.readText(n));if(!e.vertexSource||!e.fragmentSource){s[n]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=r[o];i||(i=ut.createShader(e.vertexSource,e.fragmentSource),r[o]=i),s[n]=ut.createFromAsset(e,i)}catch{s[n]=0}}return s}(s,r),h=wt(e.world,s);if(function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components)if("Sprite"===r.type&&r.data.texture&&"string"==typeof r.data.texture){const n=e.get(t,L);n&&(n.texture=s[r.data.texture]||0,e.insert(t,L,n))}}}(e.world,s,a,h),function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components){if("BitmapText"!==r.type||!r.data.font||"string"!=typeof r.data.font)continue;const n=s[r.data.font]||0;if(!n)continue;const o=e.get(t,V);o&&(o.font=n,e.insert(t,V,o))}}}(e.world,s,u,h),function(e,t,s,r){for(const n of t.entities){const t=r.get(n.id);if(void 0!==t)for(const r of n.components){if(!r.data||"string"!=typeof r.data.material||!r.data.material)continue;const n=s[r.data.material]||0;if(n)if("Sprite"===r.type){const s=e.get(t,L);s&&(s.material=n,e.insert(t,L,s))}else if("SpineAnimation"===r.type){const s=e.get(t,G);s&&(s.material=n,e.insert(t,G,s))}}}}(e.world,s,d,h),n&&c){const r=function(e,t,s,r){const n={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=r.get(o.id);void 0!==l&&(n[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return n}(c,s,l,h);!function(e,t,s,r,n){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in n){const o=Number(e),i=n[e],a=c.has(o,G)?c.get(o,G):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&r.update(i,l*d);let h=0;if(c.has(o,z)){const e=Hs(c.get(o,z),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=r.getMeshBatchCount(i);for(let e=0;e<p;e++){const n=r.getMeshBatchVertexCount(i,e),o=r.getMeshBatchIndexCount(i,e);if(!n||!o)continue;const a=8*n*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);r.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*n),x=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),_=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,_,o).set(x),t.renderer_submitTriangles(y,n,_,o,f,m,h),t._free(y),t._free(_),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,n,c,r)}}class js{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,r=new Set;for(const n of e.entities)for(const e of n.components)if(e.data){if("SpineAnimation"===e.type){const r=e.data.skeletonPath,n=e.data.atlasPath;r&&(r.endsWith(".skel")?s.add(r):t.add(r)),n&&t.add(n)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(r.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const n=[];for(const e of t)n.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of s)n.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(n);const o=[];for(const e of r){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const s=JSON.parse(t),r="label-atlas"===s.type?s.generatedFnt:s.fntFile;if(r){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${r}`:r;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),r=await s.blob(),n=await createImageBitmap(r),o=new OffscreenCanvas(n.width,n.height).getContext("2d");o.drawImage(n,0,0);const i=o.getImageData(0,0,n.width,n.height);return n.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Xs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=ps.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:ps.getTargetTexture(s),width:e.width,height:e.height}},release(e){ps.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(ps.releaseRenderTarget(e._handle),Xs.create({width:t,height:s,depth:!0})),begin(e,t){ps.begin(t,e._handle)},end(){ps.end()},getDepthTexture:e=>ps.getTargetDepthTexture(e._handle)};let Vs=!1;_||(_=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),r={method:t?.method??"GET",headers:t?.headers,body:t?.body},n=await l(s,r);return{ok:n.ok,status:n.status,statusText:n.statusText,headers:new Headers(n.headers),json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return c(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?s[r++]=n:n<2048?(s[r++]=192|n>>6,s[r++]=128|63&n):n>=55296&&n<=56319?(n=e.charCodeAt(++t)-56320+(n-55296<<10)+65536,s[r++]=240|n>>18,s[r++]=128|n>>12&63,s[r++]=128|n>>6&63,s[r++]=128|63&n):(s[r++]=224|n>>12,s[r++]=128|n>>6&63,s[r++]=128|63&n)}return s.subarray(0,r)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const r=t[e];if(r<128)s+=String.fromCharCode(r),e++;else if(192==(224&r))s+=String.fromCharCode((31&r)<<6|63&t[e+1]),e+=2;else if(224==(240&r))s+=String.fromCharCode((15&r)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const n=((7&r)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(n>>10),56320+(1023&n)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=w,exports.App=bs,exports.AssetPlugin=Ct,exports.AssetServer=Pt,exports.Assets=Tt,exports.AsyncCache=St,exports.BitmapText=V,exports.BodyType=E,exports.BoxCollider=T,exports.Button=$e,exports.Camera=O,exports.Canvas=H,exports.CapsuleCollider=A,exports.Children=X,exports.CircleCollider=C,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=oe,exports.Draw=jt,exports.EntityCommands=ne,exports.GLDebug=xs,exports.Geometry=ts,exports.INVALID_ENTITY=0,exports.INVALID_FONT=v,exports.INVALID_TEXTURE=b,exports.Input=he,exports.InputPlugin=pe,exports.InputState=de,exports.Interactable=ke,exports.LocalTransform=$,exports.Material=ut,exports.MaterialLoader=_t,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=Y,exports.Parent=j,exports.Physics=zs,exports.PhysicsEvents=Us,exports.PhysicsPlugin=Ds,exports.PostProcess=is,exports.PrefabServer=It,exports.Prefabs=Bt,exports.PrefabsPlugin=Ut,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),r=new js(this.baseUrl_);await r.prefetch(t);let n=null;const o=this.app_.__spineInitPromise;if(o){n=(await o).controller.raw}await Ns(this.app_,this.app_.wasmModule,t,r,n),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([O]);for(const r of s){if(e.get(r,O).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1920/1080;const r=e.getEntitiesWithComponents([H]);for(const n of r){const r=e.get(n,H);if(r.designResolution){const e=r.pixelsPerUnit||100;t=r.designResolution.y/2/e,s=r.designResolution.x/r.designResolution.y;break}}const n=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(n,$,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(n,O,i)}}},exports.Query=function(...e){return function(e,t=[],s=[]){const r=[];return e.forEach((e,t)=>{se(e)&&r.push(t)}),{_type:"query",_components:e,_mutIndices:r,_with:t,_without:s}}(e)},exports.QueryInstance=re,exports.RenderPipeline=ws,exports.RenderTexture=Xs,exports.Renderer=ps,exports.Res=Q,exports.ResMut=function(e){return{_type:"res_mut",_resource:e}},exports.RigidBody=P,exports.ScreenSpace=Xe,exports.ShaderSources=yt,exports.SpineAnimation=G,exports.Sprite=L,exports.SystemRunner=ue,exports.Text=we,exports.TextInput=Je,exports.TextInputPlugin=Ke,exports.TextPlugin=Se,exports.TextRenderer=be,exports.Time=te,exports.UICameraInfo=Oe,exports.UIEventQueue=ze,exports.UIEvents=Le,exports.UIInteraction=We,exports.UIInteractionPlugin=Ne,exports.UILayoutPlugin=Ye,exports.UIMask=Te,exports.UIMaskPlugin=Ue,exports.UIRect=ve,exports.Velocity=N,exports.WebAssetProvider=js,exports.World=ge,exports.WorldTransform=z,exports.addStartupSystem=function(e){ce().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){ce().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){ce().push({schedule:e,system:t})},exports.assetPlugin=At,exports.clearDrawCallbacks=function(){ys.clear()},exports.clearUserComponents=function(){I().clear()},exports.color=(e=1,t=1,s=1,r=1)=>({r:e,g:t,b:s,a:r}),exports.computeUIRectLayout=Ve,exports.createMaskProcessor=Be,exports.createWebApp=function(e,t){const s=bs.new(),r=new e.Registry;s.connectCpp(r,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Lt(e),at(e),Qt(e),rs(e),ds(e),ms(e);const n=new ws;s.pipeline_=n;let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function l(t,n){const o=Ps(e,r,t,n),i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*n),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*n),i.screenW=t,i.screenH=n,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();l(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:s}=i();if(0===t||0===s)return;const c=e.registry_getCanvasEntity(r);if(c>=0){const e=r.getCanvas(c).backgroundColor;ps.setClearColor(e.x,e.y,e.z,e.w)}const u=(a()-o)/1e3;ps.resize(t,s),is.isInitialized()&&is.getPassCount()>0&&!is.isBypassed()&&is.resize(t,s);const d=Ps(e,r,t,s);if(l(t,s),0===d.length)n.render({registry:{_cpp:r},viewProjection:vs,width:t,height:s,elapsed:u});else{for(const e of d){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*s),l=Math.round(o.w*t),c=Math.round(o.h*s);n.renderCamera({registry:{_cpp:r},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:u})}ps.setViewport(0,0,t,s)}}};return s.addSystemToSchedule(exports.Schedule.First,c),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(At),s.addPlugin(Ft),s.addPlugin(fe),s.addPlugin(Pe),s.addPlugin(Fe),s.addPlugin(qe),s.addPlugin(je),s.addPlugin(et),s},exports.defineComponent=B,exports.defineResource=K,exports.defineSystem=le,exports.defineTag=U,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([Y]);for(const r of s){const s=e.get(r,Y);if(s&&s.value===t)return r}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getComponentDefaults=function(e){const t=q[e];if(t)return{...t._default};const s=F(e);return s?{...s._default}:null},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=F,exports.initDrawAPI=Lt,exports.initGLDebugAPI=ms,exports.initGeometryAPI=Qt,exports.initMaterialAPI=at,exports.initPostProcessAPI=rs,exports.initRendererAPI=ds,exports.inputPlugin=fe,exports.instantiatePrefab=Et,exports.intersectRects=Ce,exports.invertMatrix4=Ee,exports.isBuiltinComponent=D,exports.isEditor=function(){return Vs},exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Vs},exports.isTextureRef=st,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=vt,exports.loadPhysicsModule=Bs,exports.loadRuntimeScene=Ns,exports.loadSceneData=wt,exports.loadSceneWithAssets=bt,exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=n,exports.pointInWorldRect=Re,exports.prefabsPlugin=Ft,exports.quat=(e=1,t=0,s=0,r=0)=>({w:e,x:t,y:s,z:r}),exports.registerDrawCallback=function(e,t){ys.set(e,t)},exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Tt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=xt,exports.screenToWorld=Me,exports.setEditorMode=function(e){Vs=e},exports.shutdownDrawAPI=Ot,exports.shutdownGLDebugAPI=gs,exports.shutdownGeometryAPI=Zt,exports.shutdownMaterialAPI=lt,exports.shutdownPostProcessAPI=ns,exports.shutdownRendererAPI=hs,exports.textInputPlugin=et,exports.textPlugin=Pe,exports.uiInteractionPlugin=je,exports.uiLayoutPlugin=qe,exports.uiMaskPlugin=Fe,exports.unregisterDrawCallback=_s,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);s&&(s.aspectRatio=t,e.insert(r,O,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,r=1)=>({x:e,y:t,z:s,w:r}),exports.worldRectToScreen=Ae,exports.wxFileExists=f,exports.wxFileExistsSync=function(e){const t=d();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=y,exports.wxLoadImage=x,exports.wxLoadImagePixels=async function(e){return y(await x(e))},exports.wxReadFile=h,exports.wxReadTextFile=p,exports.wxWriteFile=function(e,t){return new Promise((s,r)=>{d().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{r(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
//# sourceMappingURL=index.wechat.cjs.js.map
diff --git a/desktop/public/sdk/cjs/index.wechat.js b/desktop/public/sdk/cjs/index.wechat.js
index 76e0cecc5..fa19d70b8 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let m=null;function g(){return m||(m=wx.getFileSystemManager()),m}function y(e){return new Promise((t,n)=>{g().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function _(e,t="utf-8"){return new Promise((n,s)=>{g().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{g().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=g();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,s)=>{g().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,S=null;function P(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function C(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return v||(v=wx.createCanvas(),v.width=e,v.height=t,S=v.getContext("2d")),(v.width<e||v.height<t)&&(v.width=Math.max(v.width,e),v.height=Math.max(v.height,t)),{canvas:v,ctx:S}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function E(e){return C(await P(e))}let T=!1;const M=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return _(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,F=4294967295,U=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),I=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),k=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),W=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const $=z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),D=z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let j=0;function N(e,t){const n=++j;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function V(e,t){const n=X(),s=n.get(e);if(s)return s;const r=N(e,t);return n.set(e,r),J(e,t,!1),r}function Y(e){const t=X(),n=t.get(e);if(n)return n;const s=N(e,{});return t.set(e,s),J(e,{},!0),s}function G(e){return X().get(e)}function q(){X().clear()}function J(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=K("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ee=K("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),te=K("Sprite",{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),ne=K("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),se=K("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),re=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),oe=K("Parent",{entity:0}),ie=K("Children",{entities:[]}),ae=K("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F}),le=K("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ce={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:se,Velocity:re,Parent:oe,Children:ie,BitmapText:ae,SpineAnimation:le,RigidBody:$,BoxCollider:D,CircleCollider:L,CapsuleCollider:H};function he(e){const t=ue[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let de=0;function fe(e,t){const n=++de;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function pe(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ge{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ye{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new ge(this.get(e),t=>this.set(e,t))}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return{_type:"mut",_component:e}}function xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function be(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{xe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Se(){return{_type:"commands"}}class Pe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=Q(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Pe(this,null);return this.spawned_.push(e),e}entity(e){return new Pe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ee;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Ee||(Ee={}));let Te=0;function Me(e,t,n){const s=++Te;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Ae().push({schedule:Ee.Update,system:e})}function Fe(e){Ae().push({schedule:Ee.Startup,system:e})}function Ue(e,t){Ae().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ce&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=fe(new Ie,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ee.Last,Me([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ze=new We;function $e(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:$e(e)}}return t}class De{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return Q(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){Q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,$e(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!Q(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Le,He,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Le||(Le={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(He||(He={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const je=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Le.Left,verticalAlign:He.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2,dirty:!0});class Ne{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Oe.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===Oe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case He.Top:x=u;break;case He.Middle:x=(p-w)/2;break;case He.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case Le.Left:s=u;break;case Le.Center:s=f/2;break;case Le.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===Oe.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Le.Left:return"left";case Le.Center:return"center";case Le.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Xe=V("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ne(t),s=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,je));const e=s.getEntitiesWithComponents([je]);for(const t of e){const e=s.get(t,je);if(!e.dirty)continue;s.has(t,te)||s.insert(t,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,Xe)?s.get(t,Xe):null,o=n.renderForEntity(t,e,r),i=s.get(t,te);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,te,i),e.dirty=!1}}))}}const Ye=new Ve,Ge=V("UIMask",{enabled:!0});function qe(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Je(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(h,f),[_,w]=m(d,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(S-v)}}function Ke(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=h*g-d*m,E=h*y-f*m,T=h*_-p*m,M=d*y-f*g,A=d*_-p*g,R=f*_-p*y;let F=w*R-x*A+b*M+v*T-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*M)*F,n[1]=(o*A-r*R-i*M)*F,n[2]=(g*P-y*S+_*v)*F,n[3]=(f*S-d*P-p*v)*F,n[4]=(c*T-a*R-u*E)*F,n[5]=(s*R-o*T+i*E)*F,n[6]=(y*b-m*P-_*x)*F,n[7]=(h*P-f*b+p*x)*F,n[8]=(a*A-l*T+u*C)*F,n[9]=(r*T-s*A-i*C)*F,n[10]=(m*S-g*b+_*w)*F,n[11]=(d*b-h*S-p*w)*F,n[12]=(l*E-a*M-c*C)*F,n[13]=(s*M-r*E+o*C)*F,n[14]=(g*x-m*v-y*w)*F,n[15]=(h*v-d*x+f*w)*F),n}function Qe(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function Ze(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function et(e,t,n,s,r,o,i){if(!e.has(t,Xe)||!e.has(t,ee))return null;const a=e.get(t,Xe),l=e.get(t,ee),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Je(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function tt(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ge]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Ge).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,oe);){const e=t.get(s,oe);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=et(t,n,r,o,i,a,l);e&&(s=qe(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=et(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class nt{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(tt(e.wasmModule,e.world))}}const st=new nt,rt=V("Interactable",{enabled:!0}),ot=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var it;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(it||(it={}));const at=V("Button",{state:it.Normal,transition:null});class lt{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const ct=fe(new lt,"UIEvents"),ut=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),ht=new Float32Array(16);class dt{build(e){const t=e.world,n=new lt;e.insertResource(ct,n);let s=null,r=null;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ke),pe(ut)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([ot]);for(const e of i){const n=t.get(e,ot);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Ke(o.viewProjection,ht);const u=Qe(l,c,ht,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([rt,Xe,ee]);let d=null,f=-1/0;for(const e of h){t.has(e,ot)||t.insert(e,ot);if(!t.get(e,rt).enabled)continue;const n=t.get(e,ee),s=t.get(e,Xe),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ze(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,te)&&(n=t.get(e,te).layer),n>=f&&(f=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,ot)){t.get(s,ot).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,ot).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,ot);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ot)){const e=t.get(r,ot);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ee.Update,Me([],()=>{const e=t.getEntitiesWithComponents([at]);for(const n of e){if(t.has(n,rt)||t.insert(n,rt,{enabled:!0}),!t.has(n,ot))continue;const e=t.get(n,ot),s=t.get(n,at),r=t.get(n,rt),o=s.state;if(r.enabled?e.pressed?s.state=it.Pressed:e.hovered?s.state=it.Hovered:s.state=it.Normal:s.state=it.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case it.Normal:e.color={...r.normalColor};break;case it.Hovered:e.color={...r.hoveredColor};break;case it.Pressed:e.color={...r.pressedColor};break;case it.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const ft=new dt,pt=Y("ScreenSpace");function mt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function gt(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=mt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,Z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,Z,l),!e.has(t,ie))return;const c=e.get(t,ie);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&gt(e,t,a.rect,a.centerX,a.centerY,!1)}class yt{build(e){const t=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ut)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([pt,Xe,Z]);for(const e of o)gt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const _t=new yt,wt=V("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class xt{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=h(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=function(){const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,wt);if(t.readOnly)return;let s=d.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),d.value=s),s!==t.value){t.value=s;e.getResource(ct).emit(i,"change")}t.cursorPos=d.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;m();const t=n.get(e,wt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function m(){if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null,d.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=vt(Math.max(r.width,a)),r.height=vt(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=bt(o,d,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(d,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=bt(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,te);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,te,v)}d.addEventListener("input",()=>{a||null===i||f()}),d.addEventListener("compositionstart",()=>{a=!0}),d.addEventListener("compositionend",()=>{a=!1,f()}),d.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void m();const s=n.get(i,wt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ct).emit(i,"submit"),void m()}}),d.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ct)],e=>{const t=n.getEntitiesWithComponents([wt,rt]);for(const e of t){if(!n.has(e,ot))continue;if(n.get(e,ot).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([rt]);for(const t of e){if(n.has(t,wt))continue;if(!n.has(t,ot))continue;if(n.get(t,ot).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,wt)))){n.get(i,wt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,wt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([wt,Xe]);for(const e of a){const t=n.get(e,wt);if(!t.dirty)continue;const s=n.get(e,Xe),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,te)||n.insert(e,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function bt(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function vt(e){let t=1;for(;t<e;)t*=2;return t}const St=new xt;var Pt;function Ct(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Pt||(Pt={}));let Et=null,Tt=null,Mt=1;const At=new Map;function Rt(e){Et=e,Tt=e.getResourceManager(),Lt()}function Ft(){0!==kt&&Et&&(Et._free(kt),kt=0),At.clear(),Mt=1,It=!1,Tt=null,Et=null}function Ut(){if(!Tt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Tt}const Bt={createShader:(e,t)=>Ut().createShader(e,t),releaseShader(e){e>0&&Ut().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=At.get(e);return t?.blendMode??Pt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t)},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e)},isValid:e=>At.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=At.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return At.set(n,s),n},toAssetData(e,t){const n=At.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let It=!1,kt=0;const Wt=4096,zt=new Map;let $t=null;function Dt(e){const t=(0===kt&&Et&&(kt=Et._malloc(Wt)),kt);if(0===t||!Et)return{ptr:0,count:0};let n=0,s=0;const r=Et.HEAPU8,o=Et.HEAPU32,i=Et.HEAPF32;for(const[a,l]of e){if(n+128>Wt)break;let e=zt.get(a);e||($t||($t=new TextEncoder),e=$t.encode(a),zt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Lt(){if(!Et||It)return;Et.materialDataProvider=(e,t,n,s,r)=>{const o=At.get(e);if(!o)return Et.HEAPU32[t>>2]=0,Et.HEAPU32[n>>2]=0,Et.HEAPU32[s>>2]=0,void(Et.HEAPU32[r>>2]=0);Et.HEAPU32[t>>2]=o.shader,Et.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Dt(o.uniforms);Et.HEAPU32[s>>2]=i,Et.HEAPU32[r>>2]=a},It=!0}const Ht={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ot{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Bt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function jt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,ce,{value:s.name});for(const n of s.components)Xt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Nt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,ce,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Xt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Xt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,s);break;case"Sprite":e.insert(t,te,s);break;case"Camera":e.insert(t,ne,s);break;case"Canvas":e.insert(t,se,s);break;case"Text":e.insert(t,je,s);break;case"BitmapText":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,le,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Xe,n);break}case"UIMask":e.insert(t,Ge,s);break;case"Interactable":e.insert(t,rt,s);break;case"Button":e.insert(t,at,s);break;case"RigidBody":e.insert(t,$,s);break;case"BoxCollider":e.insert(t,D,s);break;case"CircleCollider":e.insert(t,L,s);break;case"CapsuleCollider":e.insert(t,H,s);break;default:{const r=G(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Vt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);n&&(n.aspectRatio=t,e.insert(s,ne,n))}}function Yt(e,t){const n=e.getEntitiesWithComponents([ce]);for(const s of n){const n=e.get(s,ce);if(n&&n.value===t)return s}return null}class Gt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class qt{constructor(e){this.textureCache_=new Gt,this.shaderCache_=new Gt,this.jsonCache_=new Gt,this.textCache_=new Gt,this.binaryCache_=new Gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Gt,this.prefabCache_=new Gt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Bt.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await l(t);return JSON.parse(n)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):l(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Jt=fe(null,"Assets");class Kt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new qt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Kt;function Zt(e,t){const n=e.getResource(Jt);n&&n.registerEmbeddedAssets(t)}let en=null,tn=0,nn=0,sn=0;const rn=new Float32Array(256);function on(e){en=e,tn=en._malloc(64),nn=en._malloc(64),sn=en._malloc(1024)}function an(){en&&(tn&&(en._free(tn),tn=0),nn&&(en._free(nn),nn=0),sn&&(en._free(sn),sn=0)),en=null}function ln(){if(!en)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return en}const cn={r:1,g:1,b:1,a:1},un={begin(e){const t=ln();t.HEAPF32.set(e,tn/4),t.draw_begin(tn)},end(){ln().draw_end()},line(e,t,n,s=1){ln().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){ln().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){ln().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){ln().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){ln().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=cn){ln().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=cn){ln().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){ln().draw_setLayer(e)},setDepth(e){ln().draw_setDepth(e)},getDrawCallCount:()=>en?en.draw_getDrawCallCount():0,getPrimitiveCount:()=>en?en.draw_getPrimitiveCount():0,setBlendMode(e){ln().draw_setBlendMode(e)},setDepthTest(e){ln().draw_setDepthTest(e)},drawMesh(e,t,n){const s=ln();s.HEAPF32.set(n,nn/4),s.draw_mesh(e,t,nn)},drawMeshWithMaterial(e,t,n){const s=ln(),r=Bt.get(t);if(!r)return;if(un.setBlendMode(r.blendMode),un.setDepthTest(r.depthTest),0===r.uniforms.size)return void un.drawMesh(e,r.shader,n);s.HEAPF32.set(n,nn/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=dn(e);if(!(n<0)){if(Ct(t))rn[o++]=10,rn[o++]=n,rn[o++]=t.slot??i++,rn[o++]=t.textureId;else if("number"==typeof t)rn[o++]=1,rn[o++]=n,rn[o++]=t;else if(Array.isArray(t)){rn[o++]=t.length,rn[o++]=n;for(let e=0;e<t.length;e++)rn[o++]=t[e]}else"w"in t?(rn[o++]=4,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y,rn[o++]=t.z,rn[o++]=t.w):"z"in t?(rn[o++]=3,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y,rn[o++]=t.z):(rn[o++]=2,rn[o++]=n,rn[o++]=t.x,rn[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(rn.subarray(0,o),sn/4),s.draw_meshWithUniforms(e,r.shader,nn,sn,o)):s.draw_mesh(e,r.shader,nn)}},hn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function dn(e){return hn[e]??-1}var fn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(fn||(fn={}));let pn=null,mn=0,gn=0,yn=0;function _n(e){pn=e,mn=pn._malloc(262144),gn=pn._malloc(65536),yn=pn._malloc(256)}function wn(){pn&&(mn&&pn._free(mn),gn&&pn._free(gn),yn&&pn._free(yn),mn=0,gn=0,yn=0),pn=null}function xn(){if(!pn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return pn}const bn={create(e){const t=xn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,mn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,yn,r).set(o),t.geometry_init(n,mn,s,yn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,gn,s).set(e.indices),t.geometry_setIndices16(n,gn,s)}else{new Uint32Array(t.HEAPU8.buffer,gn,s).set(e.indices),t.geometry_setIndices32(n,gn,s)}}return n},updateVertices(e,t,n=0){const s=xn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,mn/4),s.geometry_updateVertices(e,mn,r,n)},release(e){e>0&&xn().geometry_release(e)},isValid:e=>!(!pn||e<=0)&&pn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return bn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:fn.Float2},{name:"a_texCoord",type:fn.Float2}],indices:new Uint16Array(i)})}};let vn=null;function Sn(e){vn=e}function Pn(){vn&&En.isInitialized()&&En.shutdown(),vn=null}function Cn(){if(!vn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vn}const En={init:(e,t)=>Cn().postprocess_init(e,t),shutdown(){Cn().postprocess_shutdown()},resize(e,t){Cn().postprocess_resize(e,t)},addPass:(e,t)=>Cn().postprocess_addPass(e,t),removePass(e){Cn().postprocess_removePass(e)},setEnabled(e,t){Cn().postprocess_setPassEnabled(e,t)},isEnabled:e=>Cn().postprocess_isPassEnabled(e),setUniform(e,t,n){Cn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Cn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Cn().postprocess_begin()},end(){Cn().postprocess_end()},getPassCount:()=>Cn().postprocess_getPassCount(),isInitialized:()=>!!vn&&vn.postprocess_isInitialized(),setBypass(e){Cn().postprocess_setBypass(e)},isBypassed:()=>!vn||vn.postprocess_isBypassed(),createBlur:()=>Bt.createShader(Tn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Bt.createShader(Tn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Bt.createShader(Tn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Bt.createShader(Tn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},Tn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Mn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Mn||(Mn={}));let An=null,Rn=0;function Fn(e){An=e,Rn=An._malloc(64)}function Un(){An&&Rn&&(An._free(Rn),Rn=0),An=null}const Bn={init(e,t){An?.renderer_init(e,t)},resize(e,t){An?.renderer_resize(e,t)},begin(e,t){An&&Rn&&(An.HEAPF32.set(e,Rn/4),An.renderer_begin(Rn,t??0))},flush(){An?.renderer_flush()},end(){An?.renderer_end()},submitSprites(e){An&&An.renderer_submitSprites(e._cpp)},submitBitmapText(e){An&&An.renderer_submitBitmapText(e._cpp)},submitSpine(e){An&&An.renderer_submitSpine?.(e._cpp)},setStage(e){An?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>An?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){An?.renderer_releaseTarget(e)},getTargetTexture:e=>An?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>An?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){An?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){An?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){An?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){An?.renderer_clearBuffers(e)},getStats:()=>An?{drawCalls:An.renderer_getDrawCalls(),triangles:An.renderer_getTriangles(),sprites:An.renderer_getSprites(),text:An.renderer_getText(),spine:An.renderer_getSpine?.()??0,meshes:An.renderer_getMeshes(),culled:An.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let In=null;function kn(e){In=e}function Wn(){In=null}const zn={enable(){In?.gl_enableErrorCheck(!0)},disable(){In?.gl_enableErrorCheck(!1)},check:e=>In?.gl_checkErrors(e)??0,diagnose(){In?.renderer_diagnose()}},$n=new Map;function Dn(e,t){$n.set(e,t)}function Ln(e){$n.delete(e)}function Hn(){$n.clear()}class On{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Bn.resize(s,r),En.isInitialized()&&En.getPassCount()>0&&En.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Bn.setViewport(0,0,s,r),Bn.clearBuffers(3),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Bn.setViewport(s.x,s.y,s.w,s.h),Bn.setScissor(s.x,s.y,s.w,s.h,!0),Bn.clearBuffers(r),Bn.setScissor(0,0,0,0,!1),Bn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bn.submitSprites(t),Bn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bn.submitSpine(t),Bn.flush(),this.executeDrawCallbacks(n,o),Bn.end()}executeDrawCallbacks(e,t){const n=$n;if(n.size>0){un.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}un.end();for(const e of s)Ln(e)}}}class jn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Ee.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ee.FixedPreUpdate),this.runSchedule(Ee.FixedUpdate),this.runSchedule(Ee.FixedPostUpdate);this.runSchedule(Ee.PreUpdate),this.runSchedule(Ee.Update),this.runSchedule(Ee.PostUpdate),this.runSchedule(Ee.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new ye;for(const e of Object.values(Ee))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new jn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Ee.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ee.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Be(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ee.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Wn(),Un(),Pn(),wn(),Ft(),an()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Nn(e,t){const n=jn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),on(e),Rt(e),_n(e),Sn(e),Fn(e),kn(e);const r=new On;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Gn(e,s,t,r),i=n.getResource(ut);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ut,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Bn.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;Bn.resize(t,n),En.isInitialized()&&En.getPassCount()>0&&!En.isBypassed()&&En.resize(t,n);const u=Gn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Vn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Bn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.First,l),n.addSystemToSchedule(Ee.Last,c),n.addPlugin(Qt),n.addPlugin(ze),n.addPlugin(Ye),n.addPlugin(st),n.addPlugin(_t),n.addPlugin(ft),n.addPlugin(St),n}function Xn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Vn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Yn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Gn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Yn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=Jn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Qn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=es(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:ts(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const qn=new Float32Array(16);function Jn(e,t,n,s,r,o){const i=qn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const Kn=new Float32Array(16);function Qn(e,t,n,s){const r=Kn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Zn=new Float32Array(16);function es(e,t,n){const s=Zn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function ts(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function ns(e,t,n){const{entities:s,rootId:r}=await ss(t,n?.overrides??[],n),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components}))},i=await Nt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function ss(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await ss(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};rs(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function rs(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}async function os(e,t){if(t)return t();return(0,(await import(e)).default)()}const is=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),as=fe(null,"PhysicsAPI");function ls(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function cs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class us{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(is,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=os(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([se]);for(const n of t){const t=e.world.get(n,se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Ee.PostUpdate,Me([pe(_e)],a=>{const l=i.getEntitiesWithComponents([$,Z,ee]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,$),l=i.get(r,ee);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=ls(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),hs(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===O.Kinematic){const e=ls(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,Z);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(i,oe)){const t=e.world.get(i,oe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),s=ls(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=cs(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,Z,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(is,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(as,ds._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function hs(e,t,n){const s=e.world;if(s.has(n,D)){const e=s.get(n,D);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,L)){const e=s.get(n,L);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,H)){const e=s.get(n,H);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ds{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(ds.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function fs(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function ps(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ms(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,y=l*d,_=l*f,w=c*f,x=u*h,b=u*d,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function gs(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=fs(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let l={},c=null;if(r&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),l=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=ps(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=fs(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new us("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=fs(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Bt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Bt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),d=jt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,te);r&&(r.texture=n[s.data.texture]||0,e.insert(t,te,r))}}}(e.world,n,a,d),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,ae);o&&(o.font=r,e.insert(t,ae,o))}}}(e.world,n,u,d),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,te);n&&(n.material=r,e.insert(t,te,n))}else if("SpineAnimation"===s.type){const n=e.get(t,le);n&&(n.material=r,e.insert(t,le,n))}}}}(e.world,n,h,d),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(c,n,l,d);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,le)?c.get(o,le):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,ee)){const e=ms(c.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,d),t._free(_),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,c,s)}}class ys{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class _s{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ys(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await gs(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ne]);for(const s of n){if(e.get(s,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([se]);for(const r of s){const s=e.get(r,se);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,Z,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,ne,i)}}}const ws={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bn.releaseRenderTarget(e._handle),ws.create({width:t,height:n,depth:!0})),begin(e,t){Bn.begin(t,e._handle)},end(){Bn.end()},getDepthTexture:e=>Bn.getTargetDepthTexture(e._handle)};let xs=!1;function bs(e){xs=e}function vs(){return xs}function Ss(){return!xs}T||(T=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=M;export{jn as App,Kt as AssetPlugin,qt as AssetServer,Jt as Assets,Gt as AsyncCache,ae as BitmapText,Pt as BlendMode,O as BodyType,D as BoxCollider,at as Button,it as ButtonState,ne as Camera,se as Canvas,H as CapsuleCollider,ie as Children,L as CircleCollider,Se as Commands,Ce as CommandsInstance,fn as DataType,un as Draw,Pe as EntityCommands,zn as GLDebug,bn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,rt as Interactable,Z as LocalTransform,Bt as Material,Ot as MaterialLoader,we as Mut,ce as Name,oe as Parent,ds as Physics,is as PhysicsEvents,us as PhysicsPlugin,En as PostProcess,_s as PreviewPlugin,be as Query,ve as QueryInstance,On as RenderPipeline,Mn as RenderStage,ws as RenderTexture,Bn as Renderer,pe as Res,me as ResMut,$ as RigidBody,Ee as Schedule,pt as ScreenSpace,Ht as ShaderSources,le as SpineAnimation,te as Sprite,Be as SystemRunner,je as Text,Le as TextAlign,wt as TextInput,xt as TextInputPlugin,Oe as TextOverflow,Ve as TextPlugin,Ne as TextRenderer,He as TextVerticalAlign,_e as Time,ut as UICameraInfo,lt as UIEventQueue,ct as UIEvents,ot as UIInteraction,dt as UIInteractionPlugin,yt as UILayoutPlugin,Ge as UIMask,nt as UIMaskPlugin,Xe as UIRect,re as Velocity,ys as WebAssetProvider,De as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,Qt as assetPlugin,Hn as clearDrawCallbacks,q as clearUserComponents,k as color,mt as computeUIRectLayout,tt as createMaskProcessor,Nn as createWebApp,V as defineComponent,fe as defineResource,Me as defineSystem,Y as defineTag,Yt as findEntityByName,Xn as flushPendingSystems,he as getComponentDefaults,t as getPlatform,s as getPlatformType,G as getUserComponent,on as initDrawAPI,kn as initGLDebugAPI,_n as initGeometryAPI,Rt as initMaterialAPI,Sn as initPostProcessAPI,Fn as initRendererAPI,ze as inputPlugin,ns as instantiatePrefab,qe as intersectRects,Ke as invertMatrix4,Q as isBuiltinComponent,vs as isEditor,n as isPlatformInitialized,Ss as isRuntime,Ct as isTextureRef,r as isWeChat,o as isWeb,Xt as loadComponent,os as loadPhysicsModule,gs as loadRuntimeScene,jt as loadSceneData,Nt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ze as pointInWorldRect,W as quat,Dn as registerDrawCallback,Zt as registerEmbeddedAssets,Lt as registerMaterialCallback,Qe as screenToWorld,bs as setEditorMode,an as shutdownDrawAPI,Wn as shutdownGLDebugAPI,wn as shutdownGeometryAPI,Ft as shutdownMaterialAPI,Pn as shutdownPostProcessAPI,Un as shutdownRendererAPI,St as textInputPlugin,Ye as textPlugin,ft as uiInteractionPlugin,_t as uiLayoutPlugin,st as uiMaskPlugin,Ln as unregisterDrawCallback,Vt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Je as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,E as wxLoadImagePixels,y as wxReadFile,_ as wxReadTextFile,b as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(e,t){return new Promise((n,s)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}let m=null;function g(){return m||(m=wx.getFileSystemManager()),m}function y(e){return new Promise((t,n)=>{g().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function _(e,t="utf-8"){return new Promise((n,s)=>{g().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(`Failed to read file "${e}": ${t.errMsg}`))}})})}function w(e){return new Promise(t=>{g().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function x(e){const t=g();try{return t.accessSync(e),!0}catch{return!1}}function b(e,t){return new Promise((n,s)=>{g().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}let v=null,S=null;function P(e){return new Promise((t,n)=>{const s=wx.createImage();s.onload=()=>t(s),s.onerror=t=>n(new Error(`Failed to load image: ${e}, ${t}`)),s.src=e})}function C(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){return v||(v=wx.createCanvas(),v.width=e,v.height=t,S=v.getContext("2d")),(v.width<e||v.height<t)&&(v.width=Math.max(v.width,e),v.height=Math.max(v.height,t)),{canvas:v,ctx:S}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const r=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(r.data.buffer)}}async function E(e){return C(await P(e))}let T=!1;const M=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return y(e)}async readTextFile(e){return _(e)}async fileExists(e){return w(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{const n=t.touches[0];n&&e.onPointerDown(0,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(()=>{e.onPointerUp(0)})}},A=0,R=4294967295,F=4294967295,U=(e=0,t=0)=>({x:e,y:t}),B=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),I=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),k=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),W=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function $(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const z=$("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),D=$("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),L=$("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),H=$("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),O={Static:0,Kinematic:1,Dynamic:2};let j=0;function N(e,t){const n=++j;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function X(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function V(e,t){const n=X(),s=n.get(e);if(s)return s;const r=N(e,t);return n.set(e,r),J(e,t,!1),r}function Y(e){const t=X(),n=t.get(e);if(n)return n;const s=N(e,{});return t.set(e,s),J(e,{},!0),s}function G(e){return X().get(e)}function q(){X().clear()}function J(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function Q(e){return!0===e._builtin}const Z=K("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),ee=K("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),te=K("Sprite",{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),ne=K("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),se=K("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),re=K("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),oe=K("Parent",{entity:0}),ie=K("Children",{entities:[]}),ae=K("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:F}),le=K("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),ce={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ue={LocalTransform:Z,WorldTransform:ee,Sprite:te,Camera:ne,Canvas:se,Velocity:re,Parent:oe,Children:ie,BitmapText:ae,SpineAnimation:le,RigidBody:z,BoxCollider:D,CircleCollider:L,CapsuleCollider:H};function de(e){const t=ue[e];if(t)return{...t._default};const n=G(e);return n?{...n._default}:null}let he=0;function fe(e,t){const n=++he;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function pe(e){return{_type:"res",_resource:e}}function me(e){return{_type:"res_mut",_resource:e}}class ge{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ye{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new ge(this.get(e),t=>this.set(e,t))}}const _e=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return{_type:"mut",_component:e}}function xe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function be(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{xe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>xe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Se(){return{_type:"commands"}}class Pe{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=Q(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Ce{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Pe(this,null);return this.spawned_.push(e),e}entity(e){return new Pe(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ee;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(Ee||(Ee={}));let Te=0;function Me(e,t,n){const s=++Te;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Re(e){Ae().push({schedule:Ee.Update,system:e})}function Fe(e){Ae().push({schedule:Ee.Startup,system:e})}function Ue(e,t){Ae().push({schedule:e,system:t})}class Be{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ce&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Ce(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const ke=fe(new Ie,"Input");class We{constructor(e){this.target_=e??null}build(e){const n=new Ie;e.insertResource(ke,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(Ee.Last,Me([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const $e=new We;function ze(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:ze(e)}}return t}class De{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return Q(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return Q(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Q(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){Q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,ze(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!Q(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Le,He,Oe;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Le||(Le={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(He||(He={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Oe||(Oe={}));const je=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Le.Left,verticalAlign:He.Top,wordWrap:!0,overflow:Oe.Visible,lineHeight:1.2,dirty:!0});class Ne{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Oe.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,r&&e.overflow===Oe.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case He.Top:x=u;break;case He.Middle:x=(p-w)/2;break;case He.Bottom:x=p-w-u;break;default:x=u}else x=u;let b=x;for(const t of l){let s;switch(e.align){case Le.Left:s=u;break;case Le.Center:s=f/2;break;case Le.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}r&&e.overflow===Oe.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Le.Left:return"left";case Le.Center:return"center";case Le.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Xe=V("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Ve{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ne(t),s=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,je));const e=s.getEntitiesWithComponents([je]);for(const t of e){const e=s.get(t,je);if(!e.dirty)continue;s.has(t,te)||s.insert(t,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,Xe)?s.get(t,Xe):null,o=n.renderForEntity(t,e,r),i=s.get(t,te);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,te,i),e.dirty=!1}}))}}const Ye=new Ve,Ge=V("UIMask",{enabled:!0});function qe(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function Je(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[g,y]=m(d,f),[_,w]=m(h,p),x=Math.min(g,_),b=Math.max(g,_),v=Math.min(y,w),S=Math.max(y,w);return{x:Math.round(x),y:Math.round(v),w:Math.round(b-x),h:Math.round(S-v)}}function Ke(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-r*a,x=s*c-o*a,b=s*u-i*a,v=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=d*g-h*m,E=d*y-f*m,T=d*_-p*m,M=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let F=w*R-x*A+b*M+v*T-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*M)*F,n[1]=(o*A-r*R-i*M)*F,n[2]=(g*P-y*S+_*v)*F,n[3]=(f*S-h*P-p*v)*F,n[4]=(c*T-a*R-u*E)*F,n[5]=(s*R-o*T+i*E)*F,n[6]=(y*b-m*P-_*x)*F,n[7]=(d*P-f*b+p*x)*F,n[8]=(a*A-l*T+u*C)*F,n[9]=(r*T-s*A-i*C)*F,n[10]=(m*S-g*b+_*w)*F,n[11]=(h*b-d*S-p*w)*F,n[12]=(l*E-a*M-c*C)*F,n[13]=(s*M-r*E+o*C)*F,n[14]=(g*x-m*v-y*w)*F,n[15]=(d*v-h*x+f*w)*F),n}function Qe(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Ze(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function et(e,t,n,s,r,o,i){if(!e.has(t,Xe)||!e.has(t,ee))return null;const a=e.get(t,Xe),l=e.get(t,ee),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return Je(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function tt(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Ge]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Ge).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,oe);){const e=t.get(s,oe);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=et(t,n,r,o,i,a,l);e&&(s=qe(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=et(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class nt{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(tt(e.wasmModule,e.world))}}const st=new nt,rt=V("Interactable",{enabled:!0}),ot=V("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var it;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(it||(it={}));const at=V("Button",{state:it.Normal,transition:null});class lt{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const ct=fe(new lt,"UIEvents"),ut=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),dt=new Float32Array(16);class ht{build(e){const t=e.world,n=new lt;e.insertResource(ct,n);let s=null,r=null;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ke),pe(ut)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([ot]);for(const e of i){const n=t.get(e,ot);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;Ke(o.viewProjection,dt);const u=Qe(l,c,dt,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([rt,Xe,ee]);let h=null,f=-1/0;for(const e of d){t.has(e,ot)||t.insert(e,ot);if(!t.get(e,rt).enabled)continue;const n=t.get(e,ee),s=t.get(e,Xe),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Ze(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,te)&&(n=t.get(e,te).layer),n>=f&&(f=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,ot)){t.get(s,ot).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,ot).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,ot);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,ot)){const e=t.get(r,ot);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ee.Update,Me([],()=>{const e=t.getEntitiesWithComponents([at]);for(const n of e){if(t.has(n,rt)||t.insert(n,rt,{enabled:!0}),!t.has(n,ot))continue;const e=t.get(n,ot),s=t.get(n,at),r=t.get(n,rt),o=s.state;if(r.enabled?e.pressed?s.state=it.Pressed:e.hovered?s.state=it.Hovered:s.state=it.Normal:s.state=it.Disabled,o!==s.state&&s.transition&&t.has(n,te)){const e=t.get(n,te),r=s.transition;switch(s.state){case it.Normal:e.color={...r.normalColor};break;case it.Hovered:e.color={...r.hoveredColor};break;case it.Pressed:e.color={...r.pressedColor};break;case it.Disabled:e.color={...r.disabledColor}}t.insert(n,te,e)}}},{name:"ButtonSystem"}))}}const ft=new ht,pt=Y("ScreenSpace");function mt(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function gt(e,t,n,s,r,o){if(!e.has(t,Xe))return;const i=e.get(t,Xe),a=mt(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,Z);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,Z,l),!e.has(t,ie))return;const c=e.get(t,ie);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&gt(e,t,a.rect,a.centerX,a.centerY,!1)}class yt{build(e){const t=e.world;e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ut)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([pt,Xe,Z]);for(const e of o)gt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const _t=new yt,wt=V("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class xt{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,wt);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(ct).emit(i,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;m();const t=n.get(e,wt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function m(){if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null,h.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=vt(Math.max(r.width,a)),r.height=vt(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=bt(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=bt(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const g=o.getImageData(0,0,a,c),y=new Uint8Array(g.data.buffer),_=t.getResourceManager(),w=t._malloc(y.length);t.HEAPU8.set(y,w);const x=s.get(e);void 0!==x&&_.releaseTexture(x);const b=_.createTexture(a,c,w,y.length,1,!0);s.set(e,b),t._free(w);const v=n.get(e,te);v.texture=b,v.size.x=a,v.size.y=c,v.uvOffset.x=0,v.uvOffset.y=0,v.uvScale.x=1,v.uvScale.y=1,v.color={r:1,g:1,b:1,a:1},n.insert(e,te,v)}h.addEventListener("input",()=>{a||null===i||f()}),h.addEventListener("compositionstart",()=>{a=!0}),h.addEventListener("compositionend",()=>{a=!1,f()}),h.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void m();const s=n.get(i,wt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(ct).emit(i,"submit"),void m()}}),h.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,wt)){const e=n.get(i,wt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(Ee.PreUpdate,Me([pe(ct)],e=>{const t=n.getEntitiesWithComponents([wt,rt]);for(const e of t){if(!n.has(e,ot))continue;if(n.get(e,ot).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([rt]);for(const t of e){if(n.has(t,wt))continue;if(!n.has(t,ot))continue;if(n.get(t,ot).justPressed)return void m()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ee.PreUpdate,Me([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,wt)))){n.get(i,wt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,wt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([wt,Xe]);for(const e of a){const t=n.get(e,wt);if(!t.dirty)continue;const s=n.get(e,Xe),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,te)||n.insert(e,te,{texture:R,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function bt(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function vt(e){let t=1;for(;t<e;)t*=2;return t}const St=new xt;var Pt;function Ct(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Pt||(Pt={}));let Et=null,Tt=null,Mt=1;const At=new Map;function Rt(e){Et=e,Tt=e.getResourceManager(),Lt()}function Ft(){0!==kt&&Et&&(Et._free(kt),kt=0),At.clear(),Mt=1,It=!1,Tt=null,Et=null}function Ut(){if(!Tt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Tt}const Bt={createShader:(e,t)=>Ut().createShader(e,t),releaseShader(e){e>0&&Ut().releaseShader(e)},create(e){const t=Mt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pt.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=At.get(e);return t?.blendMode??Pt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t)},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e)},isValid:e=>At.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??Pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=At.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Mt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return At.set(n,s),n},toAssetData(e,t){const n=At.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let It=!1,kt=0;const Wt=4096,$t=new Map;let zt=null;function Dt(e){const t=(0===kt&&Et&&(kt=Et._malloc(Wt)),kt);if(0===t||!Et)return{ptr:0,count:0};let n=0,s=0;const r=Et.HEAPU8,o=Et.HEAPU32,i=Et.HEAPF32;for(const[a,l]of e){if(n+128>Wt)break;let e=$t.get(a);e||(zt||(zt=new TextEncoder),e=zt.encode(a),$t.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Lt(){if(!Et||It)return;Et.materialDataProvider=(e,t,n,s,r)=>{const o=At.get(e);if(!o)return Et.HEAPU32[t>>2]=0,Et.HEAPU32[n>>2]=0,Et.HEAPU32[s>>2]=0,void(Et.HEAPU32[r>>2]=0);Et.HEAPU32[t>>2]=o.shader,Et.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Dt(o.uniforms);Et.HEAPU32[s>>2]=i,Et.HEAPU32[r>>2]=a},It=!0}const Ht={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ot{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:Bt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function jt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,ce,{value:s.name});for(const n of s.components)Xt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function Nt(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,ce,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Xt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Xt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,Z,s);break;case"Sprite":e.insert(t,te,s);break;case"Camera":e.insert(t,ne,s);break;case"Canvas":e.insert(t,se,s);break;case"Text":e.insert(t,je,s);break;case"BitmapText":e.insert(t,ae,s);break;case"SpineAnimation":e.insert(t,le,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Xe,n);break}case"UIMask":e.insert(t,Ge,s);break;case"Interactable":e.insert(t,rt,s);break;case"Button":e.insert(t,at,s);break;case"RigidBody":e.insert(t,z,s);break;case"BoxCollider":e.insert(t,D,s);break;case"CircleCollider":e.insert(t,L,s);break;case"CapsuleCollider":e.insert(t,H,s);break;default:{const r=G(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Vt(e,t){const n=e.getEntitiesWithComponents([ne]);for(const s of n){const n=e.get(s,ne);n&&(n.aspectRatio=t,e.insert(s,ne,n))}}function Yt(e,t){const n=e.getEntitiesWithComponents([ce]);for(const s of n){const n=e.get(s,ce);if(n&&n.value===t)return s}return null}class Gt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class qt{constructor(e){this.textureCache_=new Gt,this.shaderCache_=new Gt,this.jsonCache_=new Gt,this.textCache_=new Gt,this.binaryCache_=new Gt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Gt,this.prefabCache_=new Gt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=d(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Ot(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Nt(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return Bt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return Bt.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Jt=fe(null,"Assets");class Kt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new qt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Kt;function Zt(e,t){const n=e.getResource(Jt);n&&n.registerEmbeddedAssets(t)}async function en(e,t,n){const{entities:s,rootId:r}=await tn(t,n?.overrides??[],n),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components}))},i=await Nt(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function tn(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await tn(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};nn(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function nn(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class sn{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=await this.assetServer_.loadPrefab(e,t?.baseUrl);return en(this.world_,n,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const rn=fe(null,"Prefabs");class on{build(e){const t=e.getResource(Jt);t?e.insertResource(rn,new sn(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const an=new on;let ln=null,cn=0,un=0,dn=0;const hn=new Float32Array(256);function fn(e){ln=e,cn=ln._malloc(64),un=ln._malloc(64),dn=ln._malloc(1024)}function pn(){ln&&(cn&&(ln._free(cn),cn=0),un&&(ln._free(un),un=0),dn&&(ln._free(dn),dn=0)),ln=null}function mn(){if(!ln)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ln}const gn={r:1,g:1,b:1,a:1},yn={begin(e){const t=mn();t.HEAPF32.set(e,cn/4),t.draw_begin(cn)},end(){mn().draw_end()},line(e,t,n,s=1){mn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){mn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){mn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){mn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){mn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=gn){mn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=gn){mn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){mn().draw_setLayer(e)},setDepth(e){mn().draw_setDepth(e)},getDrawCallCount:()=>ln?ln.draw_getDrawCallCount():0,getPrimitiveCount:()=>ln?ln.draw_getPrimitiveCount():0,setBlendMode(e){mn().draw_setBlendMode(e)},setDepthTest(e){mn().draw_setDepthTest(e)},drawMesh(e,t,n){const s=mn();s.HEAPF32.set(n,un/4),s.draw_mesh(e,t,un)},drawMeshWithMaterial(e,t,n){const s=mn(),r=Bt.get(t);if(!r)return;if(yn.setBlendMode(r.blendMode),yn.setDepthTest(r.depthTest),0===r.uniforms.size)return void yn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,un/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=wn(e);if(!(n<0)){if(Ct(t))hn[o++]=10,hn[o++]=n,hn[o++]=t.slot??i++,hn[o++]=t.textureId;else if("number"==typeof t)hn[o++]=1,hn[o++]=n,hn[o++]=t;else if(Array.isArray(t)){hn[o++]=t.length,hn[o++]=n;for(let e=0;e<t.length;e++)hn[o++]=t[e]}else"w"in t?(hn[o++]=4,hn[o++]=n,hn[o++]=t.x,hn[o++]=t.y,hn[o++]=t.z,hn[o++]=t.w):"z"in t?(hn[o++]=3,hn[o++]=n,hn[o++]=t.x,hn[o++]=t.y,hn[o++]=t.z):(hn[o++]=2,hn[o++]=n,hn[o++]=t.x,hn[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(hn.subarray(0,o),dn/4),s.draw_meshWithUniforms(e,r.shader,un,dn,o)):s.draw_mesh(e,r.shader,un)}},_n={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function wn(e){return _n[e]??-1}var xn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(xn||(xn={}));let bn=null,vn=0,Sn=0,Pn=0;function Cn(e){bn=e,vn=bn._malloc(262144),Sn=bn._malloc(65536),Pn=bn._malloc(256)}function En(){bn&&(vn&&bn._free(vn),Sn&&bn._free(Sn),Pn&&bn._free(Pn),vn=0,Sn=0,Pn=0),bn=null}function Tn(){if(!bn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return bn}const Mn={create(e){const t=Tn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,vn/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Pn,r).set(o),t.geometry_init(n,vn,s,Pn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Sn,s).set(e.indices),t.geometry_setIndices16(n,Sn,s)}else{new Uint32Array(t.HEAPU8.buffer,Sn,s).set(e.indices),t.geometry_setIndices32(n,Sn,s)}}return n},updateVertices(e,t,n=0){const s=Tn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,vn/4),s.geometry_updateVertices(e,vn,r,n)},release(e){e>0&&Tn().geometry_release(e)},isValid:e=>!(!bn||e<=0)&&bn.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Mn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:xn.Float2},{name:"a_texCoord",type:xn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Mn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:xn.Float2},{name:"a_texCoord",type:xn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Mn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:xn.Float2},{name:"a_texCoord",type:xn.Float2}],indices:new Uint16Array(i)})}};let An=null;function Rn(e){An=e}function Fn(){An&&Bn.isInitialized()&&Bn.shutdown(),An=null}function Un(){if(!An)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return An}const Bn={init:(e,t)=>Un().postprocess_init(e,t),shutdown(){Un().postprocess_shutdown()},resize(e,t){Un().postprocess_resize(e,t)},addPass:(e,t)=>Un().postprocess_addPass(e,t),removePass(e){Un().postprocess_removePass(e)},setEnabled(e,t){Un().postprocess_setPassEnabled(e,t)},isEnabled:e=>Un().postprocess_isPassEnabled(e),setUniform(e,t,n){Un().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){Un().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){Un().postprocess_begin()},end(){Un().postprocess_end()},getPassCount:()=>Un().postprocess_getPassCount(),isInitialized:()=>!!An&&An.postprocess_isInitialized(),setBypass(e){Un().postprocess_setBypass(e)},isBypassed:()=>!An||An.postprocess_isBypassed(),createBlur:()=>Bt.createShader(In,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Bt.createShader(In,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Bt.createShader(In,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Bt.createShader(In,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},In="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var kn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(kn||(kn={}));let Wn=null,$n=0;function zn(e){Wn=e,$n=Wn._malloc(64)}function Dn(){Wn&&$n&&(Wn._free($n),$n=0),Wn=null}const Ln={init(e,t){Wn?.renderer_init(e,t)},resize(e,t){Wn?.renderer_resize(e,t)},begin(e,t){Wn&&$n&&(Wn.HEAPF32.set(e,$n/4),Wn.renderer_begin($n,t??0))},flush(){Wn?.renderer_flush()},end(){Wn?.renderer_end()},submitSprites(e){Wn&&Wn.renderer_submitSprites(e._cpp)},submitBitmapText(e){Wn&&Wn.renderer_submitBitmapText(e._cpp)},submitSpine(e){Wn&&Wn.renderer_submitSpine?.(e._cpp)},setStage(e){Wn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Wn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Wn?.renderer_releaseTarget(e)},getTargetTexture:e=>Wn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Wn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Wn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Wn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){Wn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){Wn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Wn?Wn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Wn?{drawCalls:Wn.renderer_getDrawCalls(),triangles:Wn.renderer_getTriangles(),sprites:Wn.renderer_getSprites(),text:Wn.renderer_getText(),spine:Wn.renderer_getSpine?.()??0,meshes:Wn.renderer_getMeshes(),culled:Wn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Hn=null;function On(e){Hn=e}function jn(){Hn=null}const Nn={enable(){Hn?.gl_enableErrorCheck(!0)},disable(){Hn?.gl_enableErrorCheck(!1)},check:e=>Hn?.gl_checkErrors(e)??0,diagnose(){Hn?.renderer_diagnose()}},Xn=new Map;function Vn(e,t){Xn.set(e,t)}function Yn(e){Xn.delete(e)}function Gn(){Xn.clear()}class qn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Ln.resize(s,r),Bn.isInitialized()&&Bn.getPassCount()>0&&Bn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Ln.setViewport(0,0,s,r),Ln.clearBuffers(3),Ln.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(n,o),Ln.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Ln.setViewport(s.x,s.y,s.w,s.h),Ln.setScissor(s.x,s.y,s.w,s.h,!0),Ln.clearBuffers(r),Ln.setScissor(0,0,0,0,!1),Ln.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Ln.submitSprites(t),Ln.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ln.submitSpine(t),Ln.flush(),this.executeDrawCallbacks(n,o),Ln.end()}executeDrawCallbacks(e,t){const n=Xn;if(n.size>0){yn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}yn.end();for(const e of s)Yn(e)}}}class Jn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(Ee.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ee.FixedPreUpdate),this.runSchedule(Ee.FixedUpdate),this.runSchedule(Ee.FixedPostUpdate);this.runSchedule(Ee.PreUpdate),this.runSchedule(Ee.Update),this.runSchedule(Ee.PostUpdate),this.runSchedule(Ee.Last),requestAnimationFrame(this.mainLoop)},this.world_=new De,this.resources_=new ye;for(const e of Object.values(Ee))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Jn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(Ee.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ee.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new Be(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ee.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,jn(),Dn(),Fn(),En(),Ft(),pn()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Kn(e,t){const n=Jn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),fn(e),Rt(e),Cn(e),Rn(e),zn(e),On(e);const r=new qn;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=ts(e,s,t,r),i=n.getResource(ut);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(ut,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Ln.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;Ln.resize(t,n),Bn.isInitialized()&&Bn.getPassCount()>0&&!Bn.isBypassed()&&Bn.resize(t,n);const u=ts(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Zn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Ln.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(Ee.First,l),n.addSystemToSchedule(Ee.Last,c),n.addPlugin(Qt),n.addPlugin(an),n.addPlugin($e),n.addPlugin(Ye),n.addPlugin(st),n.addPlugin(_t),n.addPlugin(ft),n.addPlugin(St),n}function Qn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Zn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function es(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function ts(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=es(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=ss(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=os(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=as(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:ls(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const ns=new Float32Array(16);function ss(e,t,n,s,r,o){const i=ns;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const rs=new Float32Array(16);function os(e,t,n,s){const r=rs;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const is=new Float32Array(16);function as(e,t,n){const s=is;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function ls(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function cs(e,t){if(t)return t();return(0,(await import(e)).default)()}const us=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ds=fe(null,"PhysicsAPI");function hs(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function fs(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ps{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(us,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=cs(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([se]);for(const n of t){const t=e.world.get(n,se);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(Ee.PostUpdate,Me([pe(_e)],a=>{const l=i.getEntitiesWithComponents([z,Z,ee]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,z),l=i.get(r,ee);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=hs(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ms(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===O.Kinematic){const e=hs(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,Z);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,oe)){const t=e.world.get(i,oe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ee)){const n=e.world.get(t.entity,ee),s=hs(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=fs(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,Z,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(us,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(ds,gs._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function ms(e,t,n){const s=e.world;if(s.has(n,D)){const e=s.get(n,D);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,L)){const e=s.get(n,L);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,H)){const e=s.get(n,H);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class gs{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(gs.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function ys(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function _s(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function ws(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*r,(m+v)*r,(g-b)*r,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*i,(_-x)*i,(1-(p+y))*i,0,e.position.x,e.position.y,e.position.z,1])}async function xs(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=ys(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let l={},c=null;if(r&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),l=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=_s(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=ys(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new ps("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=ys(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),d=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=Bt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=Bt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=jt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,te);r&&(r.texture=n[s.data.texture]||0,e.insert(t,te,r))}}}(e.world,n,a,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,ae);o&&(o.font=r,e.insert(t,ae,o))}}}(e.world,n,u,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,te);n&&(n.material=r,e.insert(t,te,n))}else if("SpineAnimation"===s.type){const n=e.get(t,le);n&&(n.material=r,e.insert(t,le,n))}}}}(e.world,n,d,h),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(c,n,l,h);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,le)?c.get(o,le):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,ee)){const e=ws(c.get(o,ee),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*r),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,r,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,c,s)}}class bs{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class vs{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new bs(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await xs(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ne]);for(const s of n){if(e.get(s,ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([se]);for(const r of s){const s=e.get(r,se);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,Z,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,ne,i)}}}const Ss={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Ln.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Ln.getTargetTexture(n),width:e.width,height:e.height}},release(e){Ln.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Ln.releaseRenderTarget(e._handle),Ss.create({width:t,height:n,depth:!0})),begin(e,t){Ln.begin(t,e._handle)},end(){Ln.end()},getDepthTexture:e=>Ln.getTargetDepthTexture(e._handle)};let Ps=!1;function Cs(e){Ps=e}function Es(){return Ps}function Ts(){return!Ps}T||(T=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(n,s);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n[s++]=r:r<2048?(n[s++]=192|r>>6,n[s++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,n[s++]=240|r>>18,n[s++]=128|r>>12&63,n[s++]=128|r>>6&63,n[s++]=128|63&r):(n[s++]=224|r>>12,n[s++]=128|r>>6&63,n[s++]=128|63&r)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=M;export{Jn as App,Kt as AssetPlugin,qt as AssetServer,Jt as Assets,Gt as AsyncCache,ae as BitmapText,Pt as BlendMode,O as BodyType,D as BoxCollider,at as Button,it as ButtonState,ne as Camera,se as Canvas,H as CapsuleCollider,ie as Children,L as CircleCollider,Se as Commands,Ce as CommandsInstance,xn as DataType,yn as Draw,Pe as EntityCommands,Nn as GLDebug,Mn as Geometry,A as INVALID_ENTITY,F as INVALID_FONT,R as INVALID_TEXTURE,ke as Input,We as InputPlugin,Ie as InputState,rt as Interactable,Z as LocalTransform,Bt as Material,Ot as MaterialLoader,we as Mut,ce as Name,oe as Parent,gs as Physics,us as PhysicsEvents,ps as PhysicsPlugin,Bn as PostProcess,sn as PrefabServer,rn as Prefabs,on as PrefabsPlugin,vs as PreviewPlugin,be as Query,ve as QueryInstance,qn as RenderPipeline,kn as RenderStage,Ss as RenderTexture,Ln as Renderer,pe as Res,me as ResMut,z as RigidBody,Ee as Schedule,pt as ScreenSpace,Ht as ShaderSources,le as SpineAnimation,te as Sprite,Be as SystemRunner,je as Text,Le as TextAlign,wt as TextInput,xt as TextInputPlugin,Oe as TextOverflow,Ve as TextPlugin,Ne as TextRenderer,He as TextVerticalAlign,_e as Time,ut as UICameraInfo,lt as UIEventQueue,ct as UIEvents,ot as UIInteraction,ht as UIInteractionPlugin,yt as UILayoutPlugin,Ge as UIMask,nt as UIMaskPlugin,Xe as UIRect,re as Velocity,bs as WebAssetProvider,De as World,ee as WorldTransform,Fe as addStartupSystem,Re as addSystem,Ue as addSystemToSchedule,Qt as assetPlugin,Gn as clearDrawCallbacks,q as clearUserComponents,k as color,mt as computeUIRectLayout,tt as createMaskProcessor,Kn as createWebApp,V as defineComponent,fe as defineResource,Me as defineSystem,Y as defineTag,Yt as findEntityByName,Qn as flushPendingSystems,de as getComponentDefaults,t as getPlatform,s as getPlatformType,G as getUserComponent,fn as initDrawAPI,On as initGLDebugAPI,Cn as initGeometryAPI,Rt as initMaterialAPI,Rn as initPostProcessAPI,zn as initRendererAPI,$e as inputPlugin,en as instantiatePrefab,qe as intersectRects,Ke as invertMatrix4,Q as isBuiltinComponent,Es as isEditor,n as isPlatformInitialized,Ts as isRuntime,Ct as isTextureRef,r as isWeChat,o as isWeb,Xt as loadComponent,cs as loadPhysicsModule,xs as loadRuntimeScene,jt as loadSceneData,Nt as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ze as pointInWorldRect,an as prefabsPlugin,W as quat,Vn as registerDrawCallback,Zt as registerEmbeddedAssets,Lt as registerMaterialCallback,Qe as screenToWorld,Cs as setEditorMode,pn as shutdownDrawAPI,jn as shutdownGLDebugAPI,En as shutdownGeometryAPI,Ft as shutdownMaterialAPI,Fn as shutdownPostProcessAPI,Dn as shutdownRendererAPI,St as textInputPlugin,Ye as textPlugin,ft as uiInteractionPlugin,_t as uiLayoutPlugin,st as uiMaskPlugin,Yn as unregisterDrawCallback,Vt as updateCameraAspectRatio,U as vec2,B as vec3,I as vec4,Je as worldRectToScreen,w as wxFileExists,x as wxFileExistsSync,C as wxGetImagePixels,P as wxLoadImage,E as wxLoadImagePixels,y as wxReadFile,_ as wxReadTextFile,b as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index fe345c3c8..e301a26fb 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -462,6 +462,10 @@ interface CppResourceManager {
loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
releaseBitmapFont(handle: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
+ width: number;
+ height: number;
+ };
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -787,7 +791,9 @@ declare class RenderPipeline {
private maskProcessor_;
private lastWidth_;
private lastHeight_;
+ get spineRenderer(): SpineRendererFn | null;
setSpineRenderer(fn: SpineRendererFn | null): void;
+ get maskProcessor(): MaskProcessorFn | null;
setMaskProcessor(fn: MaskProcessorFn | null): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
@@ -1477,6 +1483,7 @@ declare class AssetServer {
private fontCache_;
private prefabCache_;
private embedded_;
+ private embeddedOnly_;
private addressableManifest_;
private addressIndex_;
private labelIndex_;
@@ -1573,6 +1580,22 @@ declare const assetPlugin: AssetPlugin;
declare function registerEmbeddedAssets(app: App, assets: Record<string, string>): void;
+declare class PrefabServer {
+ private readonly world_;
+ private readonly assetServer_;
+ constructor(world: World, assetServer: AssetServer);
+ instantiate(path: string, options?: {
+ baseUrl?: string;
+ parent?: Entity;
+ overrides?: PrefabOverride[];
+ }): Promise<InstantiatePrefabResult>;
+}
+declare const Prefabs: ResourceDef<PrefabServer>;
+declare class PrefabsPlugin implements Plugin {
+ build(app: App): void;
+}
+declare const prefabsPlugin: PrefabsPlugin;
+
/**
* @file SpineModuleLoader.ts
* @brief Loads and initializes the standalone Spine WASM module
@@ -2192,6 +2215,10 @@ declare const Renderer: {
setViewport(x: number, y: number, w: number, h: number): void;
setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
clearBuffers(flags: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
+ width: number;
+ height: number;
+ };
getStats(): RenderStats;
};
@@ -2294,5 +2321,5 @@ declare const GLDebug: {
diagnose(): void;
};
-export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };
+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Children$1 as Children, CircleCollider$1 as CircleCollider, Commands, CommandsInstance, DataType, Draw, EntityCommands, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_TEXTURE, Input, InputPlugin, InputState, Interactable, LocalTransform$1 as LocalTransform, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, Schedule, ScreenSpace, ShaderSources, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform$1 as WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeUIRectLayout, createMaskProcessor, createWebApp, defineComponent, defineResource, defineSystem, defineTag, findEntityByName, flushPendingSystems, getComponentDefaults, getPlatform, getPlatformType, getUserComponent, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInWorldRect, prefabsPlugin, quat, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, screenToWorld, setEditorMode, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textInputPlugin, textPlugin, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, worldRectToScreen };
export type { AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, FontHandle, GeometryHandle, GeometryOptions, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, LoadedMaterial, LocalTransformData, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PrefabData, PrefabEntityData, PrefabOverride, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ScreenRect, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index e3f38c21b..d1ee7e1da 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function d(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,_=4294967295,g=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const S=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),P=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),M={Static:0,Kinematic:1,Dynamic:2};let T=0;function A(e,t){const n=++T;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=R(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),k(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),k(e,{},!0),s}function B(e){return R().get(e)}function I(){R().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function z(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function L(e){return!0===e._builtin}const $=z("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=z("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=z("Sprite",{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),W=z("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=z("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),j=z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=z("Parent",{entity:0}),X=z("Children",{entities:[]}),V=z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_}),Y=z("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:$,WorldTransform:D,Sprite:H,Camera:W,Canvas:O,Velocity:j,Parent:N,Children:X,BitmapText:V,SpineAnimation:Y,RigidBody:S,BoxCollider:P,CircleCollider:C,CapsuleCollider:E};function J(e){const t=q[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let K=0;function Q(e,t){const n=++K;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}function ee(e){return{_type:"res_mut",_resource:e}}class te{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ne{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new te(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return{_type:"mut",_component:e}}function oe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ie(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{oe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>oe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function le(){return{_type:"commands"}}class ce{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=L(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ce(this,null);return this.spawned_.push(e),e}entity(e){return new ce(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var he;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(he||(he={}));let de=0;function fe(e,t,n){const s=++de;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function me(e){pe().push({schedule:he.Update,system:e})}function _e(e){pe().push({schedule:he.Startup,system:e})}function ge(e,t){pe().push({schedule:e,system:t})}class ye{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class we{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const xe=Q(new we,"Input");class ve{constructor(e){this.target_=e??null}build(e){const n=new we;e.insertResource(xe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(he.Last,fe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const be=new ve;function Se(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Se(e)}}return t}class Pe{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return L(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return L(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return L(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){L(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,Se(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!L(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Ce,Ee,Me;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Ce||(Ce={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ee||(Ee={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Me||(Me={}));const Te=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Ee.Top,wordWrap:!0,overflow:Me.Visible,lineHeight:1.2,dirty:!0});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=h(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=r?Math.ceil(o):h+2*u,p=r?Math.ceil(i):d+2*u;if(r&&e.overflow===Me.Ellipsis&&d>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Me.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Ee.Top:x=u;break;case Ee.Middle:x=(p-w)/2;break;case Ee.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case Ce.Left:s=u;break;case Ce.Center:s=f/2;break;case Ce.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Me.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const E=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Ce.Left:return"left";case Ce.Center:return"center";case Ce.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Re=F("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Fe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ae(t),s=e.world;e.addSystemToSchedule(he.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te);if(!e.dirty)continue;s.has(t,H)||s.insert(t,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,Re)?s.get(t,Re):null,o=n.renderForEntity(t,e,r),i=s.get(t,H);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,H,i),e.dirty=!1}}))}}const Ue=new Fe,Be=F("UIMask",{enabled:!0});function Ie(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ke(e,t,n,s,r,o,i,a,l,c,u){const h=e-n*r,d=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(h,f),[y,w]=m(d,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function ze(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,C=h*_-d*m,E=h*g-f*m,M=h*y-p*m,T=d*g-f*_,A=d*y-p*_,R=f*y-p*g;let F=w*R-x*A+v*T+b*M-S*E+P*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*T)*F,n[1]=(o*A-r*R-i*T)*F,n[2]=(_*P-g*S+y*b)*F,n[3]=(f*S-d*P-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(g*v-m*P-y*x)*F,n[7]=(h*P-f*v+p*x)*F,n[8]=(a*A-l*M+u*C)*F,n[9]=(r*M-s*A-i*C)*F,n[10]=(m*S-_*v+y*w)*F,n[11]=(d*v-h*S-p*w)*F,n[12]=(l*E-a*T-c*C)*F,n[13]=(s*T-r*E+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(h*b-d*x+f*w)*F),n}function Le(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:u/h}}function $e(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function De(e,t,n,s,r,o,i){if(!e.has(t,Re)||!e.has(t,D))return null;const a=e.get(t,Re),l=e.get(t,D),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ke(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function He(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Be]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Be).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,N);){const e=t.get(s,N);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(c.has(n)){const e=De(t,n,r,o,i,a,l);e&&(s=Ie(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=De(t,e,r,o,i,a,l);n&&h(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class We{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(He(e.wasmModule,e.world))}}const Oe=new We,je=F("Interactable",{enabled:!0}),Ne=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xe;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xe||(Xe={}));const Ve=F("Button",{state:Xe.Normal,transition:null});class Ye{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ge=Q(new Ye,"UIEvents"),qe=Q({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),Je=new Float32Array(16);class Ke{build(e){const t=e.world,n=new Ye;e.insertResource(Ge,n);let s=null,r=null;e.addSystemToSchedule(he.PreUpdate,fe([Z(xe),Z(qe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ne]);for(const e of i){const n=t.get(e,Ne);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;ze(o.viewProjection,Je);const u=Le(l,c,Je,o.vpX,o.vpY,o.vpW,o.vpH),h=t.getEntitiesWithComponents([je,Re,D]);let d=null,f=-1/0;for(const e of h){t.has(e,Ne)||t.insert(e,Ne);if(!t.get(e,je).enabled)continue;const n=t.get(e,D),s=t.get(e,Re),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if($e(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,H)&&(n=t.get(e,H).layer),n>=f&&(f=n,d=e)}}if(s!==d){if(null!==s&&t.valid(s)&&t.has(s,Ne)){t.get(s,Ne).hovered=!1,n.emit(s,"hover_exit")}if(null!==d){t.get(d,Ne).hovered=!0,n.emit(d,"hover_enter")}s=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,Ne);e.pressed=!0,e.justPressed=!0,r=d,n.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ne)){const e=t.get(r,Ne);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(he.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ve]);for(const n of e){if(t.has(n,je)||t.insert(n,je,{enabled:!0}),!t.has(n,Ne))continue;const e=t.get(n,Ne),s=t.get(n,Ve),r=t.get(n,je),o=s.state;if(r.enabled?e.pressed?s.state=Xe.Pressed:e.hovered?s.state=Xe.Hovered:s.state=Xe.Normal:s.state=Xe.Disabled,o!==s.state&&s.transition&&t.has(n,H)){const e=t.get(n,H),r=s.transition;switch(s.state){case Xe.Normal:e.color={...r.normalColor};break;case Xe.Hovered:e.color={...r.hoveredColor};break;case Xe.Pressed:e.color={...r.pressedColor};break;case Xe.Disabled:e.color={...r.disabledColor}}t.insert(n,H,e)}}},{name:"ButtonSystem"}))}}const Qe=new Ke,Ze=U("ScreenSpace");function et(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,h=o.bottom+t.y*a;let d,f,p,m;if(l===c&&u===h){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;d=e-s,f=t-o,p=e+s,m=t+o}else d=l+n.x,f=u+n.y,p=c+s.x,m=h+s.y;return{centerX:.5*(d+p),centerY:.5*(f+m),width:p-d,height:m-f,rect:{left:d,bottom:f,right:p,top:m}}}function tt(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=et(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,$);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,$,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&tt(e,t,a.rect,a.centerX,a.centerY,!1)}class nt{build(e){const t=e.world;e.addSystemToSchedule(he.PreUpdate,fe([Z(qe)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Ze,Re,$]);for(const e of o)tt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const st=new nt,rt=F("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class ot{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=h(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const d=function(){const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,rt);if(t.readOnly)return;let s=d.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),d.value=s),s!==t.value){t.value=s;e.getResource(Ge).emit(i,"change")}t.cursorPos=d.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;_();const t=n.get(e,rt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,d.value=t.value,d.selectionStart=t.cursorPos,d.selectionEnd=t.cursorPos,d.focus(),g())}function _(){if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null,d.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=at(Math.max(r.width,a)),r.height=at(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const h=0===i.value.length,d=h?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=h?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=it(o,d,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(d,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=it(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,H);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,H,b)}d.addEventListener("input",()=>{a||null===i||f()}),d.addEventListener("compositionstart",()=>{a=!0}),d.addEventListener("compositionend",()=>{a=!1,f()}),d.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,rt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ge).emit(i,"submit"),void _()}}),d.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(he.PreUpdate,fe([Z(Ge)],e=>{const t=n.getEntitiesWithComponents([rt,je]);for(const e of t){if(!n.has(e,Ne))continue;if(n.get(e,Ne).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([je]);for(const t of e){if(n.has(t,rt))continue;if(!n.has(t,Ne))continue;if(n.get(t,Ne).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(he.PreUpdate,fe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,rt)))){n.get(i,rt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,rt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([rt,Re]);for(const e of a){const t=n.get(e,rt);if(!t.dirty)continue;const s=n.get(e,Re),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,H)||n.insert(e,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function it(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function at(e){let t=1;for(;t<e;)t*=2;return t}const lt=new ot;var ct;function ut(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(ct||(ct={}));let ht=null,dt=null,ft=1;const pt=new Map;function mt(e){ht=e,dt=e.getResourceManager(),Ct()}function _t(){0!==xt&&ht&&(ht._free(xt),xt=0),pt.clear(),ft=1,wt=!1,dt=null,ht=null}function gt(){if(!dt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return dt}const yt={createShader:(e,t)=>gt().createShader(e,t),releaseShader(e){e>0&&gt().releaseShader(e)},create(e){const t=ft++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ct.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return pt.set(t,n),t},get:e=>pt.get(e),setUniform(e,t,n){const s=pt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=pt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=pt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=pt.get(e);return t?.blendMode??ct.Normal},setDepthTest(e,t){const n=pt.get(e);n&&(n.depthTest=t)},getShader(e){const t=pt.get(e);return t?.shader??0},release(e){pt.delete(e)},isValid:e=>pt.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??ct.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=pt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ft++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return pt.set(n,s),n},toAssetData(e,t){const n=pt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=pt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wt=!1,xt=0;const vt=4096,bt=new Map;let St=null;function Pt(e){const t=(0===xt&&ht&&(xt=ht._malloc(vt)),xt);if(0===t||!ht)return{ptr:0,count:0};let n=0,s=0;const r=ht.HEAPU8,o=ht.HEAPU32,i=ht.HEAPF32;for(const[a,l]of e){if(n+128>vt)break;let e=bt.get(a);e||(St||(St=new TextEncoder),e=St.encode(a),bt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ct(){if(!ht||wt)return;ht.materialDataProvider=(e,t,n,s,r)=>{const o=pt.get(e);if(!o)return ht.HEAPU32[t>>2]=0,ht.HEAPU32[n>>2]=0,ht.HEAPU32[s>>2]=0,void(ht.HEAPU32[r>>2]=0);ht.HEAPU32[t>>2]=o.shader,ht.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=Pt(o.uniforms);ht.HEAPU32[s>>2]=i,ht.HEAPU32[r>>2]=a},wt=!0}const Et={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Mt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(yt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())yt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:yt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Tt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,G,{value:s.name});for(const n of s.components)Rt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function At(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,G,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Rt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Rt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,$,s);break;case"Sprite":e.insert(t,H,s);break;case"Camera":e.insert(t,W,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,Te,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,Y,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Re,n);break}case"UIMask":e.insert(t,Be,s);break;case"Interactable":e.insert(t,je,s);break;case"Button":e.insert(t,Ve,s);break;case"RigidBody":e.insert(t,S,s);break;case"BoxCollider":e.insert(t,P,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,E,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ft(e,t){const n=e.getEntitiesWithComponents([W]);for(const s of n){const n=e.get(s,W);n&&(n.aspectRatio=t,e.insert(s,W,n))}}function Ut(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);if(n&&n.value===t)return s}return null}class Bt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class It{constructor(e){this.textureCache_=new Bt,this.shaderCache_=new Bt,this.jsonCache_=new Bt,this.textCache_=new Bt,this.binaryCache_=new Bt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bt,this.prefabCache_=new Bt,this.embedded_=new Map,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=h(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Mt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n)}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return At(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n)??n;return new Promise((n,r)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>r(new Error(`Failed to load image: ${e}`)),o.src=s})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e;if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:s,fragment:r}=this.parseEsShader(n);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return yt.createShader(s,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);if(e)return JSON.parse(this.decodeDataUrlText(e));const n=await l(t);return JSON.parse(n)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlText(e):l(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const e=this.embedded_.get(t);return e?this.decodeDataUrlBinary(e):a(t)}const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const kt=Q(null,"Assets");class zt{build(e){const t=e.wasmModule;t?e.insertResource(kt,new It(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new zt;function $t(e,t){const n=e.getResource(kt);n&&n.registerEmbeddedAssets(t)}let Dt=null,Ht=0,Wt=0,Ot=0;const jt=new Float32Array(256);function Nt(e){Dt=e,Ht=Dt._malloc(64),Wt=Dt._malloc(64),Ot=Dt._malloc(1024)}function Xt(){Dt&&(Ht&&(Dt._free(Ht),Ht=0),Wt&&(Dt._free(Wt),Wt=0),Ot&&(Dt._free(Ot),Ot=0)),Dt=null}function Vt(){if(!Dt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dt}const Yt={r:1,g:1,b:1,a:1},Gt={begin(e){const t=Vt();t.HEAPF32.set(e,Ht/4),t.draw_begin(Ht)},end(){Vt().draw_end()},line(e,t,n,s=1){Vt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){Vt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){Vt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){Vt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){Vt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=Yt){Vt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=Yt){Vt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Vt().draw_setLayer(e)},setDepth(e){Vt().draw_setDepth(e)},getDrawCallCount:()=>Dt?Dt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dt?Dt.draw_getPrimitiveCount():0,setBlendMode(e){Vt().draw_setBlendMode(e)},setDepthTest(e){Vt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Vt();s.HEAPF32.set(n,Wt/4),s.draw_mesh(e,t,Wt)},drawMeshWithMaterial(e,t,n){const s=Vt(),r=yt.get(t);if(!r)return;if(Gt.setBlendMode(r.blendMode),Gt.setDepthTest(r.depthTest),0===r.uniforms.size)return void Gt.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Wt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=Jt(e);if(!(n<0)){if(ut(t))jt[o++]=10,jt[o++]=n,jt[o++]=t.slot??i++,jt[o++]=t.textureId;else if("number"==typeof t)jt[o++]=1,jt[o++]=n,jt[o++]=t;else if(Array.isArray(t)){jt[o++]=t.length,jt[o++]=n;for(let e=0;e<t.length;e++)jt[o++]=t[e]}else"w"in t?(jt[o++]=4,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y,jt[o++]=t.z,jt[o++]=t.w):"z"in t?(jt[o++]=3,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y,jt[o++]=t.z):(jt[o++]=2,jt[o++]=n,jt[o++]=t.x,jt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(jt.subarray(0,o),Ot/4),s.draw_meshWithUniforms(e,r.shader,Wt,Ot,o)):s.draw_mesh(e,r.shader,Wt)}},qt={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function Jt(e){return qt[e]??-1}var Kt;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Kt||(Kt={}));let Qt=null,Zt=0,en=0,tn=0;function nn(e){Qt=e,Zt=Qt._malloc(262144),en=Qt._malloc(65536),tn=Qt._malloc(256)}function sn(){Qt&&(Zt&&Qt._free(Zt),en&&Qt._free(en),tn&&Qt._free(tn),Zt=0,en=0,tn=0),Qt=null}function rn(){if(!Qt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qt}const on={create(e){const t=rn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,Zt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,tn,r).set(o),t.geometry_init(n,Zt,s,tn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,en,s).set(e.indices),t.geometry_setIndices16(n,en,s)}else{new Uint32Array(t.HEAPU8.buffer,en,s).set(e.indices),t.geometry_setIndices32(n,en,s)}}return n},updateVertices(e,t,n=0){const s=rn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,Zt/4),s.geometry_updateVertices(e,Zt,r,n)},release(e){e>0&&rn().geometry_release(e)},isValid:e=>!(!Qt||e<=0)&&Qt.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return on.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:Kt.Float2},{name:"a_texCoord",type:Kt.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return on.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Kt.Float2},{name:"a_texCoord",type:Kt.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return on.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Kt.Float2},{name:"a_texCoord",type:Kt.Float2}],indices:new Uint16Array(i)})}};let an=null;function ln(e){an=e}function cn(){an&&hn.isInitialized()&&hn.shutdown(),an=null}function un(){if(!an)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return an}const hn={init:(e,t)=>un().postprocess_init(e,t),shutdown(){un().postprocess_shutdown()},resize(e,t){un().postprocess_resize(e,t)},addPass:(e,t)=>un().postprocess_addPass(e,t),removePass(e){un().postprocess_removePass(e)},setEnabled(e,t){un().postprocess_setPassEnabled(e,t)},isEnabled:e=>un().postprocess_isPassEnabled(e),setUniform(e,t,n){un().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){un().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){un().postprocess_begin()},end(){un().postprocess_end()},getPassCount:()=>un().postprocess_getPassCount(),isInitialized:()=>!!an&&an.postprocess_isInitialized(),setBypass(e){un().postprocess_setBypass(e)},isBypassed:()=>!an||an.postprocess_isBypassed(),createBlur:()=>yt.createShader(dn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>yt.createShader(dn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>yt.createShader(dn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>yt.createShader(dn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},dn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var fn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(fn||(fn={}));let pn=null,mn=0;function _n(e){pn=e,mn=pn._malloc(64)}function gn(){pn&&mn&&(pn._free(mn),mn=0),pn=null}const yn={init(e,t){pn?.renderer_init(e,t)},resize(e,t){pn?.renderer_resize(e,t)},begin(e,t){pn&&mn&&(pn.HEAPF32.set(e,mn/4),pn.renderer_begin(mn,t??0))},flush(){pn?.renderer_flush()},end(){pn?.renderer_end()},submitSprites(e){pn&&pn.renderer_submitSprites(e._cpp)},submitBitmapText(e){pn&&pn.renderer_submitBitmapText(e._cpp)},submitSpine(e){pn&&pn.renderer_submitSpine?.(e._cpp)},setStage(e){pn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>pn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){pn?.renderer_releaseTarget(e)},getTargetTexture:e=>pn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>pn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){pn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){pn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){pn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){pn?.renderer_clearBuffers(e)},getStats:()=>pn?{drawCalls:pn.renderer_getDrawCalls(),triangles:pn.renderer_getTriangles(),sprites:pn.renderer_getSprites(),text:pn.renderer_getText(),spine:pn.renderer_getSpine?.()??0,meshes:pn.renderer_getMeshes(),culled:pn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let wn=null;function xn(e){wn=e}function vn(){wn=null}const bn={enable(){wn?.gl_enableErrorCheck(!0)},disable(){wn?.gl_enableErrorCheck(!1)},check:e=>wn?.gl_checkErrors(e)??0,diagnose(){wn?.renderer_diagnose()}},Sn=new Map;function Pn(e,t){Sn.set(e,t)}function Cn(e){Sn.delete(e)}function En(){Sn.clear()}class Mn{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}setSpineRenderer(e){this.spineRenderer_=e}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(yn.resize(s,r),hn.isInitialized()&&hn.getPassCount()>0&&hn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),yn.setViewport(0,0,s,r),yn.clearBuffers(3),yn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),yn.submitSprites(t),yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):yn.submitSpine(t),yn.flush(),this.executeDrawCallbacks(n,o),yn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;yn.setViewport(s.x,s.y,s.w,s.h),yn.setScissor(s.x,s.y,s.w,s.h,!0),yn.clearBuffers(r),yn.setScissor(0,0,0,0,!1),yn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),yn.submitSprites(t),yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):yn.submitSpine(t),yn.flush(),this.executeDrawCallbacks(n,o),yn.end()}executeDrawCallbacks(e,t){const n=Sn;if(n.size>0){Gt.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}Gt.end();for(const e of s)Cn(e)}}}class Tn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(he.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(he.FixedPreUpdate),this.runSchedule(he.FixedUpdate),this.runSchedule(he.FixedPostUpdate);this.runSchedule(he.PreUpdate),this.runSchedule(he.Update),this.runSchedule(he.PostUpdate),this.runSchedule(he.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Pe,this.resources_=new ne;for(const e of Object.values(he))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Tn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(he.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(he.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ye(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(he.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,vn(),gn(),cn(),sn(),_t(),Xt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}function An(e,t){const n=Tn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Nt(e),mt(e),nn(e),ln(e),_n(e),xn(e);const r=new Mn;n.pipeline_=r;let o=d();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Bn(e,s,t,r),i=n.getResource(qe);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(qe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;yn.setClearColor(e.x,e.y,e.z,e.w)}const c=(d()-o)/1e3;yn.resize(t,n),hn.isInitialized()&&hn.getPassCount()>0&&!hn.isBypassed()&&hn.resize(t,n);const u=Bn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Fn,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}yn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(he.First,l),n.addSystemToSchedule(he.Last,c),n.addPlugin(Lt),n.addPlugin(be),n.addPlugin(Ue),n.addPlugin(Oe),n.addPlugin(st),n.addPlugin(Qe),n.addPlugin(lt),n}function Rn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Fn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Un(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Bn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,h=0,d=0;if(1===r.projectionType){if(d=r.orthoSize,o){d=Un(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}h=d*c,u=kn(-h,h,-d,d,-r.farPlane,r.farPlane)}else u=Ln(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Dn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Hn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:h,halfH:d,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const In=new Float32Array(16);function kn(e,t,n,s,r,o){const i=In;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const zn=new Float32Array(16);function Ln(e,t,n,s){const r=zn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const $n=new Float32Array(16);function Dn(e,t,n){const s=$n;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function Hn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function Wn(e,t,n){const{entities:s,rootId:r}=await On(t,n?.overrides??[],n),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components}))},i=await At(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function On(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await On(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};jn(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function jn(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}async function Nn(e,t){if(t)return t();return(0,(await import(e)).default)()}const Xn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Vn=Q(null,"PhysicsAPI");function Yn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Gn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class qn{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Xn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Nn(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(he.PostUpdate,fe([Z(se)],a=>{const l=i.getEntitiesWithComponents([S,$,D]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,S),l=i.get(r,D);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Yn(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Jn(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===M.Kinematic){const e=Yn(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,$);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,D)){const n=e.world.get(t.entity,D),s=Yn(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);h=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),d=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Gn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,$,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Xn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Vn,Kn._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function Jn(e,t,n){const s=e.world;if(s.has(n,P)){const e=s.get(n,P);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,C)){const e=s.get(n,C);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,E)){const e=s.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Kn{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(Kn.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function Qn(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Zn(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function es(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,_=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function ts(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=Qn(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let l={},c=null;if(r&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),l=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let h,d;if(u){const e=r.readBinary(i);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);d=n.length,h=t._malloc(d+1),t.HEAPU8.set(n,h),t.HEAPU8[h+d]=0}const f=n.loadSkeleton(h,d,s,s.length,u);if(t._free(h),f<0)continue;o[i]=f;const p=Zn(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=Qn(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new qn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=Qn(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),h=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=yt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=yt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),d=Tt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,H);r&&(r.texture=n[s.data.texture]||0,e.insert(t,H,r))}}}(e.world,n,a,d),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,V);o&&(o.font=r,e.insert(t,V,o))}}}(e.world,n,u,d),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,H);n&&(n.material=r,e.insert(t,H,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Y);n&&(n.material=r,e.insert(t,Y,n))}}}}(e.world,n,h,d),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(c,n,l,d);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Y)?c.get(o,Y):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(i,l*h);let d=0;if(c.has(o,D)){const e=es(c.get(o,D),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,d),t._free(y),t._free(w),n._free(c),n._free(u),n._free(h),n._free(f)}d&&t._free(d)}})}(e,t,r,c,s)}}class ns{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class ss{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new ns(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await ts(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([W]);for(const s of n){if(e.get(s,W).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,$,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,W,i)}}}const rs={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=yn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:yn.getTargetTexture(n),width:e.width,height:e.height}},release(e){yn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(yn.releaseRenderTarget(e._handle),rs.create({width:t,height:n,depth:!0})),begin(e,t){yn.begin(t,e._handle)},end(){yn.end()},getDepthTexture:e=>yn.getTargetDepthTexture(e._handle)};let os=!1;function is(e){os=e}function as(){return os}function ls(){return!os}e=f;export{Tn as App,zt as AssetPlugin,It as AssetServer,kt as Assets,Bt as AsyncCache,V as BitmapText,ct as BlendMode,M as BodyType,P as BoxCollider,Ve as Button,Xe as ButtonState,W as Camera,O as Canvas,E as CapsuleCollider,X as Children,C as CircleCollider,le as Commands,ue as CommandsInstance,Kt as DataType,Gt as Draw,ce as EntityCommands,bn as GLDebug,on as Geometry,p as INVALID_ENTITY,_ as INVALID_FONT,m as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,je as Interactable,$ as LocalTransform,yt as Material,Mt as MaterialLoader,re as Mut,G as Name,N as Parent,Kn as Physics,Xn as PhysicsEvents,qn as PhysicsPlugin,hn as PostProcess,ss as PreviewPlugin,ie as Query,ae as QueryInstance,Mn as RenderPipeline,fn as RenderStage,rs as RenderTexture,yn as Renderer,Z as Res,ee as ResMut,S as RigidBody,he as Schedule,Ze as ScreenSpace,Et as ShaderSources,Y as SpineAnimation,H as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,rt as TextInput,ot as TextInputPlugin,Me as TextOverflow,Fe as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,qe as UICameraInfo,Ye as UIEventQueue,Ge as UIEvents,Ne as UIInteraction,Ke as UIInteractionPlugin,nt as UILayoutPlugin,Be as UIMask,We as UIMaskPlugin,Re as UIRect,j as Velocity,ns as WebAssetProvider,Pe as World,D as WorldTransform,_e as addStartupSystem,me as addSystem,ge as addSystemToSchedule,Lt as assetPlugin,En as clearDrawCallbacks,I as clearUserComponents,x as color,et as computeUIRectLayout,He as createMaskProcessor,An as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,Ut as findEntityByName,Rn as flushPendingSystems,J as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Nt as initDrawAPI,xn as initGLDebugAPI,nn as initGeometryAPI,mt as initMaterialAPI,ln as initPostProcessAPI,_n as initRendererAPI,be as inputPlugin,Wn as instantiatePrefab,Ie as intersectRects,ze as invertMatrix4,L as isBuiltinComponent,as as isEditor,n as isPlatformInitialized,ls as isRuntime,ut as isTextureRef,r as isWeChat,o as isWeb,Rt as loadComponent,Nn as loadPhysicsModule,ts as loadRuntimeScene,Tt as loadSceneData,At as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,$e as pointInWorldRect,v as quat,Pn as registerDrawCallback,$t as registerEmbeddedAssets,Ct as registerMaterialCallback,Le as screenToWorld,is as setEditorMode,Xt as shutdownDrawAPI,vn as shutdownGLDebugAPI,sn as shutdownGeometryAPI,_t as shutdownMaterialAPI,cn as shutdownPostProcessAPI,gn as shutdownRendererAPI,lt as textInputPlugin,Ue as textPlugin,Qe as uiInteractionPlugin,st as uiLayoutPlugin,Oe as uiMaskPlugin,Cn as unregisterDrawCallback,Ft as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,ke as worldRectToScreen};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function r(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function i(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}const f=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),r=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},i=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const n=t;e.onWheel(n.deltaX,n.deltaY)};document.addEventListener("keydown",s),document.addEventListener("keyup",r),n.addEventListener("mousemove",o),n.addEventListener("mousedown",i),n.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",u),n.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",r),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",i),n.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",u),n.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=0,m=4294967295,_=4294967295,g=(e=0,t=0)=>({x:e,y:t}),y=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),w=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),x=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),v=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function b(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}const P=b("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),S=b("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),C=b("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),E=b("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),M={Static:0,Kinematic:1,Dynamic:2};let T=0;function A(e,t){const n=++T;return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...t,...e}:{...t}}}function R(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const n=R(),s=n.get(e);if(s)return s;const r=A(e,t);return n.set(e,r),k(e,t,!1),r}function U(e){const t=R(),n=t.get(e);if(n)return n;const s=A(e,{});return t.set(e,s),k(e,{},!0),s}function B(e){return R().get(e)}function I(){R().clear()}function k(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function $(e,t){return{_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t}}function z(e){return!0===e._builtin}const L=$("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),D=$("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),H=$("Sprite",{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),W=$("Camera",{projectionType:0,fov:60,orthoSize:5,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3}),O=$("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),j=$("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),N=$("Parent",{entity:0}),X=$("Children",{entities:[]}),V=$("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_}),Y=$("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0}),G={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},q={LocalTransform:L,WorldTransform:D,Sprite:H,Camera:W,Canvas:O,Velocity:j,Parent:N,Children:X,BitmapText:V,SpineAnimation:Y,RigidBody:P,BoxCollider:S,CircleCollider:C,CapsuleCollider:E};function J(e){const t=q[e];if(t)return{...t._default};const n=B(e);return n?{...n._default}:null}let K=0;function Q(e,t){const n=++K;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Z(e){return{_type:"res",_resource:e}}function ee(e){return{_type:"res_mut",_resource:e}}class te{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}}class ne{constructor(){this.resources_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id)}getResMut(e){return new te(this.get(e),t=>this.set(e,t))}}const se=Q({delta:0,elapsed:0,frameCount:0},"Time");function re(e){return{_type:"mut",_component:e}}function oe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ie(...e){return function(e,t=[],n=[]){const s=[];return e.forEach((e,t)=>{oe(e)&&s.push(t)}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n}}(e)}class ae{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>oe(e)?e._component:e),this.allRequired_=this.actualComponents_.concat(t._with)}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,n=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_),r=n.length,o=e.length>0,i=t.length>0,a=new Array(r+1);let l=null,c=[];try{for(const u of s){if(null!==l&&o){for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}c.length=0}if(i){let e=!1;for(let n=0;n<t.length;n++)if(this.world_.has(u,t[n])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,n[e]);if(o){for(let t=0;t<e.length;t++){const s=e[t];c.push({component:n[s],data:a[s+1]})}l=u}yield a}}finally{if(null!==l&&o)for(let e=0;e<c.length;e++){const t=c[e];this.world_.insert(l,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function le(){return{_type:"commands"}}class ce{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let n;return n=z(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:n}):this.commands_.queueInsert(this.entityRef_.entity,e,n),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class ue{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ce(this,null);return this.spawned_.push(e),e}entity(e){return new ce(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_=[];for(const e of this.pending_)this.executeCommand(e);this.pending_=[]}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":this.world_.despawn(e.entity);break;case"insert":this.world_.insert(e.entity,e.component,e.data);break;case"remove":this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var de;!function(e){e[e.Startup=0]="Startup",e[e.First=1]="First",e[e.PreUpdate=2]="PreUpdate",e[e.Update=3]="Update",e[e.PostUpdate=4]="PostUpdate",e[e.Last=5]="Last",e[e.FixedPreUpdate=10]="FixedPreUpdate",e[e.FixedUpdate=11]="FixedUpdate",e[e.FixedPostUpdate=12]="FixedPostUpdate"}(de||(de={}));let he=0;function fe(e,t,n){const s=++he;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pe(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function me(e){pe().push({schedule:de.Update,system:e})}function _e(e){pe().push({schedule:de.Startup,system:e})}function ge(e,t){pe().push({schedule:e,system:t})}class ye{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ue&&t[e].flush()}resolveParam(e){switch(e._type){case"query":return new ae(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new ue(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class we{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const xe=Q(new we,"Input");class ve{constructor(e){this.target_=e??null}build(e){const n=new we;e.insertResource(xe,n),t().bindInputEvents({onKeyDown(e){n.keysDown.has(e)||n.keysPressed.add(e),n.keysDown.add(e)},onKeyUp(e){n.keysDown.delete(e),n.keysReleased.add(e)},onPointerMove(e,t){n.mouseX=e,n.mouseY=t},onPointerDown(e,t,s){n.mouseX=t,n.mouseY=s,n.mouseButtons.add(e),n.mouseButtonsPressed.add(e)},onPointerUp(e){n.mouseButtons.delete(e),n.mouseButtonsReleased.add(e)},onWheel(e,t){n.scrollDeltaX+=e,n.scrollDeltaY+=t}},this.target_??void 0),e.addSystemToSchedule(de.Last,fe([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const be=new ve;function Pe(e){const t={};for(const n of Object.keys(e)){const s=e[n];if(null==s||"object"!=typeof s||Array.isArray(s))t[n]=s;else{const e=s;t[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:Pe(e)}}return t}class Se{constructor(){this.cppRegistry_=null,this.entities_=new Set,this.tsStorage_=new Map}connectCpp(e){this.cppRegistry_=e}disconnectCpp(){this.cppRegistry_=null}get hasCpp(){return null!==this.cppRegistry_}spawn(){let e;return e=this.cppRegistry_?this.cppRegistry_.create():this.entities_.size+1,this.entities_.add(e),e}despawn(e){this.cppRegistry_&&this.cppRegistry_.destroy(e),this.entities_.delete(e);for(const t of this.tsStorage_.values())t.delete(e)}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){this.cppRegistry_&&this.cppRegistry_.setParent(e,t)}removeParent(e){this.cppRegistry_&&this.cppRegistry_.removeParent(e)}insert(e,t,n){return z(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}get(e,t){return z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}remove(e,t){z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n)for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const r={...t._default,...s};if(this.cppRegistry_){const n=`add${t._cppName}`,s=this.cppRegistry_[n];s?.call(this.cppRegistry_,e,Pe(r))}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");const n=`get${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;const n=`has${t._cppName}`;return this.cppRegistry_[n].call(this.cppRegistry_,e)}removeBuiltin(e,t){if(!this.cppRegistry_)return;const n=`remove${t._cppName}`;this.cppRegistry_[n].call(this.cppRegistry_,e)}insertScript(e,t,n){const s=t.create(n);return this.getStorage(t).set(e,s),s}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e)}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}getEntitiesWithComponents(e){if(0===e.length)return this.getAllEntities();let t=null,n=1/0;for(const s of e)if(!z(s)){const e=this.tsStorage_.get(s._id),r=e?e.size:0;r<n&&(n=r,t=e??null)}const s=[],r=t?t.keys():this.entities_;for(const t of r){let n=!0;for(const s of e)if(!this.has(t,s)){n=!1;break}n&&s.push(t)}return s}}var Ce,Ee,Me;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(Ce||(Ce={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(Ee||(Ee={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(Me||(Me={}));const Te=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ce.Left,verticalAlign:Ee.Top,wordWrap:!0,overflow:Me.Visible,lineHeight:1.2,dirty:!0});class Ae{constructor(e){this.cache=new Map,this.module=e,this.canvas=d(512,512),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=this.wrapText(e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=r?Math.ceil(o):d+2*u,p=r?Math.ceil(i):h+2*u;if(r&&e.overflow===Me.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}if(s.width<f||s.height<p){const e=Math.max(s.width,this.nextPowerOf2(f)),t=Math.max(s.height,this.nextPowerOf2(p));s.width=e,s.height=t}const m=Math.round(255*e.color.r),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,r&&e.overflow===Me.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(r)switch(e.verticalAlign){case Ee.Top:x=u;break;case Ee.Middle:x=(p-w)/2;break;case Ee.Bottom:x=p-w-u;break;default:x=u}else x=u;let v=x;for(const t of l){let s;switch(e.align){case Ce.Left:s=u;break;case Ce.Center:s=f/2;break;case Ce.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}r&&e.overflow===Me.Clip&&n.restore();const b=n.getImageData(0,0,f,p),P=new Uint8Array(b.data.buffer),S=this.module.getResourceManager(),C=this.module._malloc(P.length);this.module.HEAPU8.set(P,C);const E=S.createTexture(f,p,C,P.length,1,!0);return this.module._free(C),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let n=e;for(;n.length>0&&this.ctx.measureText(n+"...").width>t;)n=n.slice(0,-1);return n+"..."}renderForEntity(e,t,n){const s=this.cache.get(e);if(s){this.module.getResourceManager().releaseTexture(s.textureHandle)}const r=this.renderText(t,n);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[n,s]of this.cache)e(n)||(t.releaseTexture(s.textureHandle),this.cache.delete(n))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const n=e.split("\n"),s=[];for(const e of n){if(!e){s.push("");continue}let n="";for(const r of e){const e=n+r;this.ctx.measureText(e).width>t&&n?(s.push(n),n=r):n=e}n&&s.push(n)}return s.length>0?s:[""]}measureWidth(e){let t=0;for(const n of e){const e=this.ctx.measureText(n),s=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,s)}return t}mapAlign(e){switch(e){case Ce.Left:return"left";case Ce.Center:return"center";case Ce.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}const Re=F("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});class Fe{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ae(t),s=e.world;e.addSystemToSchedule(de.PreUpdate,fe([],()=>{n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Te));const e=s.getEntitiesWithComponents([Te]);for(const t of e){const e=s.get(t,Te);if(!e.dirty)continue;s.has(t,H)||s.insert(t,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const r=s.has(t,Re)?s.get(t,Re):null,o=n.renderForEntity(t,e,r),i=s.get(t,H);i.texture=o.textureHandle,i.size.x=o.width,i.size.y=o.height,i.uvOffset.x=0,i.uvOffset.y=0,i.uvScale.x=1,i.uvScale.y=1,s.insert(t,H,i),e.dirty=!1}}))}}const Ue=new Fe,Be=F("UIMask",{enabled:!0});function Ie(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,r-n),h:Math.max(0,o-s)}}function ke(e,t,n,s,r,o,i,a,l,c,u){const d=e-n*r,h=e+n*(1-r),f=t-s*o,p=t+s*(1-o);function m(e,t){const n=i[0]*e+i[4]*t+i[12],s=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(n/r)+.5)*c,l+(.5*(s/r)+.5)*u]}const[_,g]=m(d,f),[y,w]=m(h,p),x=Math.min(_,y),v=Math.max(_,y),b=Math.min(g,w),P=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(P-b)}}function $e(e,t){const n=t??new Float32Array(16),s=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],_=e[13],g=e[14],y=e[15],w=s*l-r*a,x=s*c-o*a,v=s*u-i*a,b=r*c-o*l,P=r*u-i*l,S=o*u-i*c,C=d*_-h*m,E=d*g-f*m,M=d*y-p*m,T=h*g-f*_,A=h*y-p*_,R=f*y-p*g;let F=w*R-x*A+v*T+b*M-P*E+S*C;return 0===F||(F=1/F,n[0]=(l*R-c*A+u*T)*F,n[1]=(o*A-r*R-i*T)*F,n[2]=(_*S-g*P+y*b)*F,n[3]=(f*P-h*S-p*b)*F,n[4]=(c*M-a*R-u*E)*F,n[5]=(s*R-o*M+i*E)*F,n[6]=(g*v-m*S-y*x)*F,n[7]=(d*S-f*v+p*x)*F,n[8]=(a*A-l*M+u*C)*F,n[9]=(r*M-s*A-i*C)*F,n[10]=(m*P-_*v+y*w)*F,n[11]=(h*v-d*P-p*w)*F,n[12]=(l*E-a*T-c*C)*F,n[13]=(s*T-r*E+o*C)*F,n[14]=(_*x-m*b-g*w)*F,n[15]=(d*b-h*x+f*w)*F),n}function ze(e,t,n,s,r,o,i){const a=(e-s)/o*2-1,l=(t-r)/i*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function Le(e,t,n,s,r,o,i,a){return e>=n-r*i&&e<=n+r*(1-i)&&t>=s-o*a&&t<=s+o*(1-a)}function De(e,t,n,s,r,o,i){if(!e.has(t,Re)||!e.has(t,D))return null;const a=e.get(t,Re),l=e.get(t,D),c=a.size.x*l.scale.x,u=a.size.y*l.scale.y;return ke(l.position.x,l.position.y,c,u,a.pivot.x,a.pivot.y,n,s,r,o,i)}function He(e,t){return(n,s,r,o,i,a)=>{e.renderer_clearAllClipRects();const l=t.getEntitiesWithComponents([Be]);if(0!==l.length)try{!function(e,t,n,s,r,o,i,a,l){const c=new Set;for(const e of s){t.get(e,Be).enabled&&c.add(e)}const u=[];for(const e of s){if(!c.has(e))continue;let n=!0,s=e;for(;t.has(s,N);){const e=t.get(s,N);if(c.has(e.entity)){n=!1;break}s=e.entity}n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(c.has(n)){const e=De(t,n,r,o,i,a,l);e&&(s=Ie(u,e))}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=De(t,e,r,o,i,a,l);n&&d(e,n)}}(e,t,n,l,s,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class We{build(e){if(!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(He(e.wasmModule,e.world))}}const Oe=new We,je=F("Interactable",{enabled:!0}),Ne=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Xe;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Xe||(Xe={}));const Ve=F("Button",{state:Xe.Normal,transition:null});class Ye{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(n=>n.entity===e&&n.type===t)}}const Ge=Q(new Ye,"UIEvents"),qe=Q({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo"),Je=new Float32Array(16);class Ke{build(e){const t=e.world,n=new Ye;e.insertResource(Ge,n);let s=null,r=null;e.addSystemToSchedule(de.PreUpdate,fe([Z(xe),Z(qe)],(e,o)=>{n.drain();const i=t.getEntitiesWithComponents([Ne]);for(const e of i){const n=t.get(e,Ne);n.justPressed=!1,n.justReleased=!1}if(!o.valid)return;const a="undefined"!=typeof window&&window.devicePixelRatio||1,l=e.mouseX*a,c=o.screenH-e.mouseY*a;$e(o.viewProjection,Je);const u=ze(l,c,Je,o.vpX,o.vpY,o.vpW,o.vpH),d=t.getEntitiesWithComponents([je,Re,D]);let h=null,f=-1/0;for(const e of d){t.has(e,Ne)||t.insert(e,Ne);if(!t.get(e,je).enabled)continue;const n=t.get(e,D),s=t.get(e,Re),r=s.size.x*n.scale.x,o=s.size.y*n.scale.y;if(Le(u.x,u.y,n.position.x,n.position.y,r,o,s.pivot.x,s.pivot.y)){let n=0;t.has(e,H)&&(n=t.get(e,H).layer),n>=f&&(f=n,h=e)}}if(s!==h){if(null!==s&&t.valid(s)&&t.has(s,Ne)){t.get(s,Ne).hovered=!1,n.emit(s,"hover_exit")}if(null!==h){t.get(h,Ne).hovered=!0,n.emit(h,"hover_enter")}s=h}if(e.isMouseButtonPressed(0)&&null!==h){const e=t.get(h,Ne);e.pressed=!0,e.justPressed=!0,r=h,n.emit(h,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ne)){const e=t.get(r,Ne);e.pressed=!1,e.justReleased=!0,n.emit(r,"release"),r===s&&n.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(de.Update,fe([],()=>{const e=t.getEntitiesWithComponents([Ve]);for(const n of e){if(t.has(n,je)||t.insert(n,je,{enabled:!0}),!t.has(n,Ne))continue;const e=t.get(n,Ne),s=t.get(n,Ve),r=t.get(n,je),o=s.state;if(r.enabled?e.pressed?s.state=Xe.Pressed:e.hovered?s.state=Xe.Hovered:s.state=Xe.Normal:s.state=Xe.Disabled,o!==s.state&&s.transition&&t.has(n,H)){const e=t.get(n,H),r=s.transition;switch(s.state){case Xe.Normal:e.color={...r.normalColor};break;case Xe.Hovered:e.color={...r.hoveredColor};break;case Xe.Pressed:e.color={...r.pressedColor};break;case Xe.Disabled:e.color={...r.disabledColor}}t.insert(n,H,e)}}},{name:"ButtonSystem"}))}}const Qe=new Ke,Ze=U("ScreenSpace");function et(e,t,n,s,r,o){const i=o.right-o.left,a=o.top-o.bottom,l=o.left+e.x*i,c=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,f,p,m;if(l===c&&u===d){const e=l+n.x,t=u+n.y,s=.5*r.x,o=.5*r.y;h=e-s,f=t-o,p=e+s,m=t+o}else h=l+n.x,f=u+n.y,p=c+s.x,m=d+s.y;return{centerX:.5*(h+p),centerY:.5*(f+m),width:p-h,height:m-f,rect:{left:h,bottom:f,right:p,top:m}}}function tt(e,t,n,s,r,o){if(!e.has(t,Re))return;const i=e.get(t,Re),a=et(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,n);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const l=e.get(t,L);if(o?(l.position.x=a.centerX,l.position.y=a.centerY):(l.position.x=a.centerX-s,l.position.y=a.centerY-r),e.insert(t,L,l),!e.has(t,X))return;const c=e.get(t,X);if(c&&c.entities)for(const t of c.entities)e.valid(t)&&tt(e,t,a.rect,a.centerX,a.centerY,!1)}class nt{build(e){const t=e.world;e.addSystemToSchedule(de.PreUpdate,fe([Z(qe)],e=>{if(!e.valid)return;const n={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},s=.5*(n.left+n.right),r=.5*(n.bottom+n.top),o=t.getEntitiesWithComponents([Ze,Re,L]);for(const e of o)tt(t,e,n,s,r,!0)},{name:"UILayoutSystem"}))}}const st=new nt,rt=F("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0});class ot{build(e){const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,r=d(512,64),o=r.getContext("2d",{willReadFrequently:!0});let i=null,a=!1,l=!0,c=0,u=0;const h=function(){const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();function f(){if(null===i||!n.valid(i))return;const t=n.get(i,rt);if(t.readOnly)return;let s=h.value;if(t.maxLength>0&&s.length>t.maxLength&&(s=s.substring(0,t.maxLength),h.value=s),s!==t.value){t.value=s;e.getResource(Ge).emit(i,"change")}t.cursorPos=h.selectionStart??s.length,t.dirty=!0,g()}function p(e){if(i===e)return;_();const t=n.get(e,rt);t.readOnly||(i=e,t.focused=!0,t.dirty=!0,h.value=t.value,h.selectionStart=t.cursorPos,h.selectionEnd=t.cursorPos,h.focus(),g())}function _(){if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null,h.blur()}function g(){l=!0,c=0}function y(e,i,a,c){(r.width<a||r.height<c)&&(r.width=at(Math.max(r.width,a)),r.height=at(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,f=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*i.fontSize),m=i.padding;if(i.multiline){const e=it(o,h,a-2*m);let t=m;for(const n of e)o.fillText(n,m,t),t+=p}else{const e=(c-i.fontSize)/2;o.fillText(h,m,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,n,s;if(i.multiline){const e=it(o,i.value.substring(0,i.cursorPos),a-2*m),r=e.length>0?e[e.length-1]:"";t=m+o.measureText(r).width,n=m+(e.length-1)*p,s=p}else t=m+o.measureText(e).width,n=(c-i.fontSize)/2,s=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,a,c),g=new Uint8Array(_.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=s.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,c,w,g.length,1,!0);s.set(e,v),t._free(w);const b=n.get(e,H);b.texture=v,b.size.x=a,b.size.y=c,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},n.insert(e,H,b)}h.addEventListener("input",()=>{a||null===i||f()}),h.addEventListener("compositionstart",()=>{a=!0}),h.addEventListener("compositionend",()=>{a=!1,f()}),h.addEventListener("keydown",t=>{if(null===i)return;if("Escape"===t.key)return void _();const s=n.get(i,rt);if("Enter"===t.key&&!s.multiline){t.preventDefault();return e.getResource(Ge).emit(i,"submit"),void _()}}),h.addEventListener("blur",()=>{if(null!==i&&n.valid(i)&&n.has(i,rt)){const e=n.get(i,rt);e.focused=!1,e.dirty=!0}i=null}),e.addSystemToSchedule(de.PreUpdate,fe([Z(Ge)],e=>{const t=n.getEntitiesWithComponents([rt,je]);for(const e of t){if(!n.has(e,Ne))continue;if(n.get(e,Ne).justPressed)return void p(e)}if(null!==i){const e=n.getEntitiesWithComponents([je]);for(const t of e){if(n.has(t,rt))continue;if(!n.has(t,Ne))continue;if(n.get(t,Ne).justPressed)return void _()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(de.PreUpdate,fe([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===u?0:(e-u)/1e3;if(u=e,null!==i&&(c+=r,c>=.5&&(c-=.5,l=!l,null!==i&&n.valid(i)&&n.has(i,rt)))){n.get(i,rt).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,rt)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([rt,Re]);for(const e of a){const t=n.get(e,rt);if(!t.dirty)continue;const s=n.get(e,Re),r=Math.ceil(s.size.x),o=Math.ceil(s.size.y);r<=0||o<=0||(n.has(e,H)||n.insert(e,H,{texture:m,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),y(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function it(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),r=[];for(const t of s){if(!t){r.push("");continue}let s="";for(const o of t){const t=s+o;e.measureText(t).width>n&&s?(r.push(s),s=o):s=t}s&&r.push(s)}return r.length>0?r:[""]}function at(e){let t=1;for(;t<e;)t*=2;return t}const lt=new ot;var ct;function ut(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(ct||(ct={}));let dt=null,ht=null,ft=1;const pt=new Map;function mt(e){dt=e,ht=e.getResourceManager(),Ct()}function _t(){0!==xt&&dt&&(dt._free(xt),xt=0),pt.clear(),ft=1,wt=!1,ht=null,dt=null}function gt(){if(!ht)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ht}const yt={createShader:(e,t)=>gt().createShader(e,t),releaseShader(e){e>0&&gt().releaseShader(e)},create(e){const t=ft++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??ct.Normal,depthTest:e.depthTest??!1};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return pt.set(t,n),t},get:e=>pt.get(e),setUniform(e,t,n){const s=pt.get(e);s&&s.uniforms.set(t,n)},getUniform(e,t){const n=pt.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=pt.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=pt.get(e);return t?.blendMode??ct.Normal},setDepthTest(e,t){const n=pt.get(e);n&&(n.depthTest=t)},getShader(e){const t=pt.get(e);return t?.shader??0},release(e){pt.delete(e)},isValid:e=>pt.has(e),createFromAsset(e,t){const n={};for(const[t,s]of Object.entries(e.properties))if("number"==typeof s)n[t]=s;else if("object"==typeof s&&null!==s){const e=s;"a"in e?n[t]={x:e.r??0,y:e.g??0,z:e.b??0,w:e.a??0}:"w"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0,w:e.w??0}:"z"in e?n[t]={x:e.x??0,y:e.y??0,z:e.z??0}:"y"in e&&(n[t]={x:e.x??0,y:e.y??0})}return this.create({shader:t,uniforms:n,blendMode:e.blendMode??ct.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=pt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ft++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest};return pt.set(n,s),n},toAssetData(e,t){const n=pt.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=pt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wt=!1,xt=0;const vt=4096,bt=new Map;let Pt=null;function St(e){const t=(0===xt&&dt&&(xt=dt._malloc(vt)),xt);if(0===t||!dt)return{ptr:0,count:0};let n=0,s=0;const r=dt.HEAPU8,o=dt.HEAPU32,i=dt.HEAPF32;for(const[a,l]of e){if(n+128>vt)break;let e=bt.get(a);e||(Pt||(Pt=new TextEncoder),e=Pt.encode(a),bt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);o[t+n>>2]=c,n+=4,r.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)i[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Ct(){if(!dt||wt)return;dt.materialDataProvider=(e,t,n,s,r)=>{const o=pt.get(e);if(!o)return dt.HEAPU32[t>>2]=0,dt.HEAPU32[n>>2]=0,dt.HEAPU32[s>>2]=0,void(dt.HEAPU32[r>>2]=0);dt.HEAPU32[t>>2]=o.shader,dt.HEAPU32[n>>2]=o.blendMode;const{ptr:i,count:a}=St(o.uniforms);dt.HEAPU32[s>>2]=i,dt.HEAPU32[r>>2]=a},wt=!0}const Et={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Mt{constructor(e,t=""){this.cache_=new Map,this.pending_=new Map,this.shaderLoader_=e,this.basePath_=t}async load(e){const t=this.cache_.get(e);if(t)return t;const n=this.pending_.get(e);if(n)return n;const s=this.loadInternal(e);this.pending_.set(e,s);try{const t=await s;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(yt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())yt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const r=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(r);return{handle:yt.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Tt(e,t){const n=new Map;for(const s of t.entities){const t=e.spawn();n.set(s.id,t),e.insert(t,G,{value:s.name});for(const n of s.components)Rt(e,t,n)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return n}async function At(e,t,n){const s=new Map,r=n?.assetServer,o=new Map;for(const i of t.entities){const t=e.spawn();s.set(i.id,t),e.insert(t,G,{value:i.name});for(const s of i.components){if("Sprite"===s.type&&r){const e=s.data;if("string"==typeof e.texture&&e.texture){const t=e.texture,s=t.startsWith("data:")?t:n?.assetBaseUrl?`${n.assetBaseUrl}/${t}`:`/${t}`;try{const n=await r.loadTexture(s);e.texture=n.handle,o.set(t,s)}catch(t){console.warn(`Failed to load texture: ${s}`,t),e.texture=0}}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}if("BitmapText"===s.type&&r){const e=s.data;if("string"==typeof e.font&&e.font)try{const t=await r.loadBitmapFont(e.font,n?.assetBaseUrl);e.font=t}catch(t){console.warn(`Failed to load bitmap font: ${e.font}`,t),e.font=0}}if("SpineAnimation"===s.type&&r){const e=s.data,t=e.skeletonPath,o=e.atlasPath;if(t&&o){const e=await r.loadSpine(t,o,n?.assetBaseUrl);e.success||console.warn(`Failed to load Spine: ${e.error}`)}if("string"==typeof e.material&&e.material)try{const t=await r.loadMaterial(e.material,n?.assetBaseUrl);e.material=t.handle}catch(t){console.warn(`Failed to load material: ${e.material}`,t),e.material=0}}Rt(e,t,s)}}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&r.setTextureMetadataByPath(t,n.sliceBorder)}return s}function Rt(e,t,n){const s=n.data;switch(n.type){case"LocalTransform":e.insert(t,L,s);break;case"Sprite":e.insert(t,H,s);break;case"Camera":e.insert(t,W,s);break;case"Canvas":e.insert(t,O,s);break;case"Text":e.insert(t,Te,s);break;case"BitmapText":e.insert(t,V,s);break;case"SpineAnimation":e.insert(t,Y,s);break;case"UIRect":{const n=s;n.anchor&&!n.anchorMin&&(n.anchorMin={...n.anchor},n.anchorMax={...n.anchor},delete n.anchor),e.insert(t,Re,n);break}case"UIMask":e.insert(t,Be,s);break;case"Interactable":e.insert(t,je,s);break;case"Button":e.insert(t,Ve,s);break;case"RigidBody":e.insert(t,P,s);break;case"BoxCollider":e.insert(t,S,s);break;case"CircleCollider":e.insert(t,C,s);break;case"CapsuleCollider":e.insert(t,E,s);break;default:{const r=B(n.type);r?e.insert(t,r,s):console.warn(`Unknown component type: ${n.type}`);break}}}function Ft(e,t){const n=e.getEntitiesWithComponents([W]);for(const s of n){const n=e.get(s,W);n&&(n.aspectRatio=t,e.insert(s,W,n))}}function Ut(e,t){const n=e.getEntitiesWithComponents([G]);for(const s of n){const n=e.get(s,G);if(n&&n.value===t)return s}return null}class Bt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t){const n=this.cache_.get(e);if(void 0!==n)return n;const s=this.pending_.get(e);if(s)return s;const r=t();this.pending_.set(e,r);try{const t=await r;return this.cache_.set(e,t),t}finally{this.pending_.delete(e)}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}values(){return this.cache_.values()}}class It{constructor(e){this.textureCache_=new Bt,this.shaderCache_=new Bt,this.jsonCache_=new Bt,this.textCache_=new Bt,this.binaryCache_=new Bt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Bt,this.prefabCache_=new Bt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.module_=e,this.canvas_=d(512,512),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Mt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),r=this.textureCache_.get(s);r&&(t.releaseTexture(r.handle),this.textureCache_.delete(s))}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);this.textureCache_.clear(),this.fontCache_.clear(),this.prefabCache_.clear(),this.jsonCache_.clear(),this.textCache_.clear(),this.binaryCache_.clear(),this.loadedSpines_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const r=this.resolveUrl(t,n),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o);for(const e of a){const t=i?`${i}/${e}`:e,s=this.resolveUrl(t,n);try{const e=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(e.handle,t)}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,n),c=e.endsWith(".skel")?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);return this.writeToVirtualFS(e,c)?(this.loadedSpines_.add(s),{success:!0}):{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>e.endsWith(".bmfont")?this.loadBmfontAsset(n):this.loadFntFile(n))}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const r=n?`${n}/${s}`:s;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${s}`:s,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return At(e,t,{assetServer:this})}async loadAll(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];if(e.textures)for(const s of e.textures)n.push(this.loadTexture(s).then(e=>{t.textures.set(s,e)}));if(e.materials)for(const s of e.materials)n.push(this.loadMaterial(s).then(e=>{t.materials.set(s,e)}));if(e.spine)for(const s of e.spine){const e=`${s.skeleton}:${s.atlas}`;n.push(this.loadSpine(s.skeleton,s.atlas,s.baseUrl).then(n=>{t.spine.set(e,n)}))}if(e.json)for(const s of e.json)n.push(this.loadJson(s).then(e=>{t.json.set(s,e)}));if(e.text)for(const s of e.text)n.push(this.loadText(s).then(e=>{t.text.set(s,e)}));if(e.binary)for(const s of e.binary)n.push(this.loadBinary(s).then(e=>{t.binary.set(s,e)}));return await Promise.all(n),t}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups)){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}async loadByAddress(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path);default:return this.loadBinary(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e)switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(e=>{t.textures.set(s.path,e)}));break;case"material":n.push(this.loadMaterial(s.path).then(e=>{t.materials.set(s.path,e)}));break;case"json":n.push(this.loadJson(s.path).then(e=>{t.json.set(s.path,e)}));break;case"text":n.push(this.loadText(s.path).then(e=>{t.text.set(s.path,e)}));break;default:n.push(this.loadBinary(s.path).then(e=>{t.binary.set(s.path,e)}))}return await Promise.all(n),t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t);return this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t))}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const r=s??n;return new Promise((n,s)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(o)},o.onerror=()=>s(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:n,height:s}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:r}=this.parseEsShader(t);if(!s||!r)throw new Error(`Invalid shader format: ${e}`);return yt.createShader(s,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:o}=this.parseEsShader(s);if(!r||!o)throw new Error(`Invalid shader format: ${e}`);return yt.createShader(r,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await i(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let r="";for(const e of s){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const kt=Q(null,"Assets");class $t{build(e){const t=e.wasmModule;t?e.insertResource(kt,new It(t)):console.warn("AssetPlugin: No WASM module available")}}const zt=new $t;function Lt(e,t){const n=e.getResource(kt);n&&n.registerEmbeddedAssets(t)}async function Dt(e,t,n){const{entities:s,rootId:r}=await Ht(t,n?.overrides??[],n),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components}))},i=await At(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=i.get(r);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:i}}async function Ht(e,t,n,s){const r=new Map;let o;if(void 0===s){o=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),o=Math.max(o,t.prefabEntityId+1))}else{o=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,o++)}const i=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Ht(e,s.nestedPrefab.overrides,n,o);r.set(s.prefabEntityId,t.rootId),o=t.nextId;const a=t.entities.find(e=>e.id===t.rootId);a&&(a.parent=null!==s.parent?r.get(s.parent)??null:null),i.push(...t.entities);continue}const a=r.get(s.prefabEntityId),l=s.prefabEntityId===e.rootEntityId,c={id:a,prefabEntityId:s.prefabEntityId,name:s.name,parent:l?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Wt(c,t),i.push(c)}const a=r.get(e.rootEntityId);if(void 0===a)throw new Error("Failed to resolve prefab root entity");return{entities:i,rootId:a,nextId:o}}function Wt(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Ot{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=await this.assetServer_.loadPrefab(e,t?.baseUrl);return Dt(this.world_,n,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const jt=Q(null,"Prefabs");class Nt{build(e){const t=e.getResource(kt);t?e.insertResource(jt,new Ot(e.world,t)):console.warn("PrefabsPlugin: Assets resource not available")}}const Xt=new Nt;let Vt=null,Yt=0,Gt=0,qt=0;const Jt=new Float32Array(256);function Kt(e){Vt=e,Yt=Vt._malloc(64),Gt=Vt._malloc(64),qt=Vt._malloc(1024)}function Qt(){Vt&&(Yt&&(Vt._free(Yt),Yt=0),Gt&&(Vt._free(Gt),Gt=0),qt&&(Vt._free(qt),qt=0)),Vt=null}function Zt(){if(!Vt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Vt}const en={r:1,g:1,b:1,a:1},tn={begin(e){const t=Zt();t.HEAPF32.set(e,Yt/4),t.draw_begin(Yt)},end(){Zt().draw_end()},line(e,t,n,s=1){Zt().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rect(e,t,n,s=!0){Zt().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},rectOutline(e,t,n,s=1){Zt().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)},circle(e,t,n,s=!0,r=32){Zt().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},circleOutline(e,t,n,s=1,r=32){Zt().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)},texture(e,t,n,s=en){Zt().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)},textureRotated(e,t,n,s,r=en){Zt().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)},setLayer(e){Zt().draw_setLayer(e)},setDepth(e){Zt().draw_setDepth(e)},getDrawCallCount:()=>Vt?Vt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Vt?Vt.draw_getPrimitiveCount():0,setBlendMode(e){Zt().draw_setBlendMode(e)},setDepthTest(e){Zt().draw_setDepthTest(e)},drawMesh(e,t,n){const s=Zt();s.HEAPF32.set(n,Gt/4),s.draw_mesh(e,t,Gt)},drawMeshWithMaterial(e,t,n){const s=Zt(),r=yt.get(t);if(!r)return;if(tn.setBlendMode(r.blendMode),tn.setDepthTest(r.depthTest),0===r.uniforms.size)return void tn.drawMesh(e,r.shader,n);s.HEAPF32.set(n,Gt/4);let o=0,i=0;for(const[e,t]of r.uniforms){const n=sn(e);if(!(n<0)){if(ut(t))Jt[o++]=10,Jt[o++]=n,Jt[o++]=t.slot??i++,Jt[o++]=t.textureId;else if("number"==typeof t)Jt[o++]=1,Jt[o++]=n,Jt[o++]=t;else if(Array.isArray(t)){Jt[o++]=t.length,Jt[o++]=n;for(let e=0;e<t.length;e++)Jt[o++]=t[e]}else"w"in t?(Jt[o++]=4,Jt[o++]=n,Jt[o++]=t.x,Jt[o++]=t.y,Jt[o++]=t.z,Jt[o++]=t.w):"z"in t?(Jt[o++]=3,Jt[o++]=n,Jt[o++]=t.x,Jt[o++]=t.y,Jt[o++]=t.z):(Jt[o++]=2,Jt[o++]=n,Jt[o++]=t.x,Jt[o++]=t.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}0!==o?(s.HEAPF32.set(Jt.subarray(0,o),qt/4),s.draw_meshWithUniforms(e,r.shader,Gt,qt,o)):s.draw_mesh(e,r.shader,Gt)}},nn={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17};function sn(e){return nn[e]??-1}var rn;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(rn||(rn={}));let on=null,an=0,ln=0,cn=0;function un(e){on=e,an=on._malloc(262144),ln=on._malloc(65536),cn=on._malloc(256)}function dn(){on&&(an&&on._free(an),ln&&on._free(ln),cn&&on._free(cn),an=0,ln=0,cn=0),on=null}function hn(){if(!on)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return on}const fn={create(e){const t=hn(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,an/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,cn,r).set(o),t.geometry_init(n,an,s,cn,r,e.dynamic??!1),e.indices){const s=e.indices.length;if(4*s>65536)throw new Error(`Index data too large: ${s} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,ln,s).set(e.indices),t.geometry_setIndices16(n,ln,s)}else{new Uint32Array(t.HEAPU8.buffer,ln,s).set(e.indices),t.geometry_setIndices32(n,ln,s)}}return n},updateVertices(e,t,n=0){const s=hn(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);s.HEAPF32.set(t,an/4),s.geometry_updateVertices(e,an,r,n)},release(e){e>0&&hn().geometry_release(e)},isValid:e=>!(!on||e<=0)&&on.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return fn.create({vertices:new Float32Array([-n,-s,0,0,n,-s,1,0,n,s,1,1,-n,s,0,1]),layout:[{name:"a_position",type:rn.Float2},{name:"a_texCoord",type:rn.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const r=s/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;n.push(o,i,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return fn.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:rn.Float2},{name:"a_texCoord",type:rn.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(s-t),a=(i.y-n)/(r-n);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return fn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:rn.Float2},{name:"a_texCoord",type:rn.Float2}],indices:new Uint16Array(i)})}};let pn=null;function mn(e){pn=e}function _n(){pn&&yn.isInitialized()&&yn.shutdown(),pn=null}function gn(){if(!pn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return pn}const yn={init:(e,t)=>gn().postprocess_init(e,t),shutdown(){gn().postprocess_shutdown()},resize(e,t){gn().postprocess_resize(e,t)},addPass:(e,t)=>gn().postprocess_addPass(e,t),removePass(e){gn().postprocess_removePass(e)},setEnabled(e,t){gn().postprocess_setPassEnabled(e,t)},isEnabled:e=>gn().postprocess_isPassEnabled(e),setUniform(e,t,n){gn().postprocess_setUniformFloat(e,t,n)},setUniformVec4(e,t,n){gn().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)},begin(){gn().postprocess_begin()},end(){gn().postprocess_end()},getPassCount:()=>gn().postprocess_getPassCount(),isInitialized:()=>!!pn&&pn.postprocess_isInitialized(),setBypass(e){gn().postprocess_setBypass(e)},isBypassed:()=>!pn||pn.postprocess_isBypassed(),createBlur:()=>yt.createShader(wn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>yt.createShader(wn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>yt.createShader(wn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>yt.createShader(wn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},wn="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var xn;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(xn||(xn={}));let vn=null,bn=0;function Pn(e){vn=e,bn=vn._malloc(64)}function Sn(){vn&&bn&&(vn._free(bn),bn=0),vn=null}const Cn={init(e,t){vn?.renderer_init(e,t)},resize(e,t){vn?.renderer_resize(e,t)},begin(e,t){vn&&bn&&(vn.HEAPF32.set(e,bn/4),vn.renderer_begin(bn,t??0))},flush(){vn?.renderer_flush()},end(){vn?.renderer_end()},submitSprites(e){vn&&vn.renderer_submitSprites(e._cpp)},submitBitmapText(e){vn&&vn.renderer_submitBitmapText(e._cpp)},submitSpine(e){vn&&vn.renderer_submitSpine?.(e._cpp)},setStage(e){vn?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>vn?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){vn?.renderer_releaseTarget(e)},getTargetTexture:e=>vn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>vn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){vn?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){vn?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,r){vn?.renderer_setScissor(e,t,n,s,r)},clearBuffers(e){vn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>vn?vn.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>vn?{drawCalls:vn.renderer_getDrawCalls(),triangles:vn.renderer_getTriangles(),sprites:vn.renderer_getSprites(),text:vn.renderer_getText(),spine:vn.renderer_getSpine?.()??0,meshes:vn.renderer_getMeshes(),culled:vn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let En=null;function Mn(e){En=e}function Tn(){En=null}const An={enable(){En?.gl_enableErrorCheck(!0)},disable(){En?.gl_enableErrorCheck(!1)},check:e=>En?.gl_checkErrors(e)??0,diagnose(){En?.renderer_diagnose()}},Rn=new Map;function Fn(e,t){Rn.set(e,t)}function Un(e){Rn.delete(e)}function Bn(){Rn.clear()}class In{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}render(e){const{registry:t,viewProjection:n,width:s,height:r,elapsed:o}=e;s===this.lastWidth_&&r===this.lastHeight_||(Cn.resize(s,r),yn.isInitialized()&&yn.getPassCount()>0&&yn.resize(s,r),this.lastWidth_=s,this.lastHeight_=r),Cn.setViewport(0,0,s,r),Cn.clearBuffers(3),Cn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,r),Cn.submitSprites(t),Cn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Cn.submitSpine(t),Cn.flush(),this.executeDrawCallbacks(n,o),Cn.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:r,elapsed:o}=e;Cn.setViewport(s.x,s.y,s.w,s.h),Cn.setScissor(s.x,s.y,s.w,s.h,!0),Cn.clearBuffers(r),Cn.setScissor(0,0,0,0,!1),Cn.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Cn.submitSprites(t),Cn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Cn.submitSpine(t),Cn.flush(),this.executeDrawCallbacks(n,o),Cn.end()}executeDrawCallbacks(e,t){const n=Rn;if(n.size>0){tn.begin(e);const s=[];for(const[e,r]of n.entries())try{r(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}tn.end();for(const e of s)Un(e)}}}class kn{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.module_=null,this.pipeline_=null,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=t/1e3;for(this.updateTime(n),this.runSchedule(de.First),this.fixedAccumulator_+=n;this.fixedAccumulator_>=this.fixedTimestep_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(de.FixedPreUpdate),this.runSchedule(de.FixedUpdate),this.runSchedule(de.FixedPostUpdate);this.runSchedule(de.PreUpdate),this.runSchedule(de.Update),this.runSchedule(de.PostUpdate),this.runSchedule(de.Last),requestAnimationFrame(this.mainLoop)},this.world_=new Se,this.resources_=new ne;for(const e of Object.values(de))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new kn}addPlugin(e){return e.build(this),this}addSystemToSchedule(e,t){return this.systems_.get(e).push({system:t}),this}addSystem(e){return this.addSystemToSchedule(de.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(de.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}run(){this.running_||(this.running_=!0,this.runner_=new ye(this.world_,this.resources_),this.resources_.insert(se,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(de.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Tn(),Sn(),_n(),dn(),_t(),Qt()}runSchedule(e){const t=this.systems_.get(e);if(t&&this.runner_)for(const e of t)this.runner_.run(e.system)}updateTime(e){const t=this.resources_.get(se);t.delta=e,t.elapsed+=e,t.frameCount++}}function $n(e,t){const n=kn.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Kt(e),mt(e),un(e),mn(e),Pn(e),Mn(e);const r=new In;n.pipeline_=r;let o=h();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r){const o=Hn(e,s,t,r),i=n.getResource(qe);if(o.length>0){const e=o[0],n=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(n.x*t),i.vpY=Math.round((1-n.y-n.h)*r),i.vpW=Math.round(n.w*t),i.vpH=Math.round(n.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}n.insertResource(qe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:n}=i();if(0===t||0===n)return;const l=e.registry_getCanvasEntity(s);if(l>=0){const e=s.getCanvas(l).backgroundColor;Cn.setClearColor(e.x,e.y,e.z,e.w)}const c=(h()-o)/1e3;Cn.resize(t,n),yn.isInitialized()&&yn.getPassCount()>0&&!yn.isBypassed()&&yn.resize(t,n);const u=Hn(e,s,t,n);if(a(t,n),0===u.length)r.render({registry:{_cpp:s},viewProjection:Ln,width:t,height:n,elapsed:c});else{for(const e of u){const o=e.viewportRect,i=Math.round(o.x*t),a=Math.round((1-o.y-o.h)*n),l=Math.round(o.w*t),u=Math.round(o.h*n);r.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:i,y:a,w:l,h:u},clearFlags:e.clearFlags,elapsed:c})}Cn.setViewport(0,0,t,n)}}};return n.addSystemToSchedule(de.First,l),n.addSystemToSchedule(de.Last,c),n.addPlugin(zt),n.addPlugin(Xt),n.addPlugin(be),n.addPlugin(Ue),n.addPlugin(Oe),n.addPlugin(st),n.addPlugin(Qe),n.addPlugin(lt),n}function zn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Dn(e,t,n,s,r){const o=e*t/n,i=e;switch(s){case 0:return o;case 1:default:return i;case 2:return Math.max(o,i);case 3:return Math.min(o,i);case 4:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}}}function Hn(e,t,n,s){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const o=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),i=[];for(const e of r){const r=t.getCamera(e),a=t.getLocalTransform(e),l={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},c=l.w*n/(l.h*s);let u,d=0,h=0;if(1===r.projectionType){if(h=r.orthoSize,o){h=Dn(o.designResolution.y/2,o.designResolution.x/o.designResolution.y,c,o.scaleMode,o.matchWidthOrHeight)}d=h*c,u=On(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Nn(r.fov*Math.PI/180,c,r.nearPlane,r.farPlane);const f=Vn(a.position.x,a.position.y,a.position.z);i.push({entity:e,viewProjection:Yn(u,f),viewportRect:l,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:a.position.x,cameraY:a.position.y})}return i.sort((e,t)=>e.priority-t.priority),i}const Wn=new Float32Array(16);function On(e,t,n,s,r,o){const i=Wn;i.fill(0);const a=t-e,l=s-n,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(s+n)/l,i[14]=-(o+r)/c,i[15]=1,i}const jn=new Float32Array(16);function Nn(e,t,n,s){const r=jn;r.fill(0);const o=1/Math.tan(e/2),i=n-s;return r[0]=o/t,r[5]=o,r[10]=(s+n)/i,r[11]=-1,r[14]=2*s*n/i,r}const Xn=new Float32Array(16);function Vn(e,t,n){const s=Xn;return s[0]=1,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=1,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[10]=1,s[11]=0,s[12]=-e,s[13]=-t,s[14]=-n,s[15]=1,s}function Yn(e,t){const n=new Float32Array(16);for(let s=0;s<4;s++)for(let r=0;r<4;r++)n[4*r+s]=e[0+s]*t[4*r+0]+e[4+s]*t[4*r+1]+e[8+s]*t[4*r+2]+e[12+s]*t[4*r+3];return n}async function Gn(e,t){if(t)return t();return(0,(await import(e)).default)()}const qn=Q({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Jn=Q(null,"PhysicsAPI");function Kn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Qn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Zn{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(qn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Gn(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([O]);for(const n of t){const t=e.world.get(n,O);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(de.PostUpdate,fe([Z(se)],a=>{const l=i.getEntitiesWithComponents([P,L,D]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,P),l=i.get(r,D);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Kn(l.rotation);s._physics_createBody(r,a.bodyType,l.position.x*o,l.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),es(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===M.Kinematic){const e=Kn(l.rotation);s._physics_setBodyTransform(r,l.position.x*o,l.position.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<s;r++){const s=o+4*r,i=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(i))continue;const u=e.world.get(i,L);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(i,N)){const t=e.world.get(i,N);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,D)){const n=e.world.get(t.entity,D),s=Kn(n.rotation),r=a-n.position.x,o=l-n.position.y,i=Math.cos(-s),u=Math.sin(-s);d=(r*i-o*u)/(0!==n.scale.x?n.scale.x:1),h=(r*u+o*i)/(0!==n.scale.y?n.scale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Qn(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(i,L,u)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<i;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(qn,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.__physicsModule=s,e.insertResource(Jn,ts._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});e.__physicsInitPromise=s}}function es(e,t,n){const s=e.world;if(s.has(n,S)){const e=s.get(n,S);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,C)){const e=s.get(n,C);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,E)){const e=s.get(n,E);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class ts{constructor(e){if(this.module_=e.__physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(ts.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}function ns(e,t,n=!0){const s=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=s.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function ss(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function rs(e,t,n,s){const r=e.scale.x*t*(n?-1:1),o=e.scale.y*t*(s?-1:1),i=e.scale.z,a=e.rotation.x,l=e.rotation.y,c=e.rotation.z,u=e.rotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,_=a*f,g=l*h,y=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(g+w))*r,(m+b)*r,(_-v)*r,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*i,(y-x)*i,(1-(p+g))*i,0,e.position.x,e.position.y,e.position.z,1])}async function os(e,t,n,s,r,o,i){const a=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==s[r])continue;try{s[r]=ns(e,await n.loadPixels(r))}catch{s[r]=0}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const r=n[e];if(r&&r>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,n,a);let l={},c=null;if(r&&(c=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),l=await async function(e,t,n,s,r){const o={};for(const i of s.entities)for(const s of i.components){if("SpineAnimation"!==s.type||!s.data)continue;const i=s.data.skeletonPath,a=s.data.atlasPath;if(!i||!a)continue;const l=r.resolvePath(i),c=r.resolvePath(a);try{const s=r.readText(a),u=l.endsWith(".skel");let d,h;if(u){const e=r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=r.readText(i),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,u);if(t._free(d),f<0)continue;o[i]=f;const p=ss(s),m=c.substring(0,c.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(s):await r.loadPixels(s),i=ns(e,o,!1),a=e.getResourceManager().getTextureGLId(i);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,c,n,s)),o){new Zn("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const u=await async function(e,t,n){const s={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===s[r])try{let t,o;if(r.endsWith(".bmfont")){const e=JSON.parse(n.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=n.readText(l),o=l.substring(0,l.lastIndexOf("/"))}else t=n.readText(r),o=r.substring(0,r.lastIndexOf("/"));const i=t.match(/file="([^"]+)"/);if(!i){s[r]=0;continue}const a=o?`${o}/${i[1]}`:i[1],l=n.loadPixelsRaw?await n.loadPixelsRaw(a):await n.loadPixels(a),c=ns(e,l,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,c,l.width,l.height)}catch{s[r]=0}}return s}(t,n,s),d=function(e,t){const n={},s={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===n[r])try{const e=JSON.parse(t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=s[o];i||(i=yt.createShader(e.vertexSource,e.fragmentSource),s[o]=i),n[r]=yt.createFromAsset(e,i)}catch{n[r]=0}}return n}(n,s),h=Tt(e.world,n);if(function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components)if("Sprite"===s.type&&s.data.texture&&"string"==typeof s.data.texture){const r=e.get(t,H);r&&(r.texture=n[s.data.texture]||0,e.insert(t,H,r))}}}(e.world,n,a,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if("BitmapText"!==s.type||!s.data.font||"string"!=typeof s.data.font)continue;const r=n[s.data.font]||0;if(!r)continue;const o=e.get(t,V);o&&(o.font=r,e.insert(t,V,o))}}}(e.world,n,u,h),function(e,t,n,s){for(const r of t.entities){const t=s.get(r.id);if(void 0!==t)for(const s of r.components){if(!s.data||"string"!=typeof s.data.material||!s.data.material)continue;const r=n[s.data.material]||0;if(r)if("Sprite"===s.type){const n=e.get(t,H);n&&(n.material=r,e.insert(t,H,n))}else if("SpineAnimation"===s.type){const n=e.get(t,Y);n&&(n.material=r,e.insert(t,Y,n))}}}}(e.world,n,d,h),r&&c){const s=function(e,t,n,s){const r={};for(const o of t.entities)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=n[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const l=s.get(o.id);void 0!==l&&(r[l]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(c,n,l,h);!function(e,t,n,s,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=1/60);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,Y)?c.get(o,Y):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(i,l*d);let h=0;if(c.has(o,D)){const e=rs(c.get(o,D),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=s.getMeshBatchVertexCount(i,e),o=s.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(i,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],_=new Float32Array(n.HEAPF32.buffer,c,8*r),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,r,w,o,p,m,h),t._free(y),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,r,c,s)}}class is{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const s=e.data.skeletonPath,r=e.data.atlasPath;s&&(s.endsWith(".skel")?n.add(s):t.add(s)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(s.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(()=>{}));for(const e of n)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(()=>{}));await Promise.all(r);const o=[];for(const e of s){if(!e.endsWith(".bmfont"))continue;const t=this.textCache_.get(e);if(t)try{const n=JSON.parse(t),s="label-atlas"===n.type?n.generatedFnt:n.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(()=>{}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),r=await createImageBitmap(s),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}class as{constructor(e,t){this.app_=null,this.loadPromise_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e,this.loadPromise_=this.loadScene()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadScene(){if(this.app_)try{const e=await i(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new is(this.baseUrl_);await n.prefetch(t);let s=null;const r=this.app_.__spineInitPromise;if(r){s=(await r).controller.raw}await os(this.app_,this.app_.wasmModule,t,n,s),this.ensureCamera()}catch(e){console.error("[PreviewPlugin] Failed to load scene:",e)}}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([W]);for(const s of n){if(e.get(s,W).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1920/1080;const s=e.getEntitiesWithComponents([O]);for(const r of s){const s=e.get(r,O);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const r=e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(r,L,o);const i={isActive:!0,projectionType:1,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!0,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:3};e.insert(r,W,i)}}}const ls={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Cn.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Cn.getTargetTexture(n),width:e.width,height:e.height}},release(e){Cn.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Cn.releaseRenderTarget(e._handle),ls.create({width:t,height:n,depth:!0})),begin(e,t){Cn.begin(t,e._handle)},end(){Cn.end()},getDepthTexture:e=>Cn.getTargetDepthTexture(e._handle)};let cs=!1;function us(e){cs=e}function ds(){return cs}function hs(){return!cs}e=f;export{kn as App,$t as AssetPlugin,It as AssetServer,kt as Assets,Bt as AsyncCache,V as BitmapText,ct as BlendMode,M as BodyType,S as BoxCollider,Ve as Button,Xe as ButtonState,W as Camera,O as Canvas,E as CapsuleCollider,X as Children,C as CircleCollider,le as Commands,ue as CommandsInstance,rn as DataType,tn as Draw,ce as EntityCommands,An as GLDebug,fn as Geometry,p as INVALID_ENTITY,_ as INVALID_FONT,m as INVALID_TEXTURE,xe as Input,ve as InputPlugin,we as InputState,je as Interactable,L as LocalTransform,yt as Material,Mt as MaterialLoader,re as Mut,G as Name,N as Parent,ts as Physics,qn as PhysicsEvents,Zn as PhysicsPlugin,yn as PostProcess,Ot as PrefabServer,jt as Prefabs,Nt as PrefabsPlugin,as as PreviewPlugin,ie as Query,ae as QueryInstance,In as RenderPipeline,xn as RenderStage,ls as RenderTexture,Cn as Renderer,Z as Res,ee as ResMut,P as RigidBody,de as Schedule,Ze as ScreenSpace,Et as ShaderSources,Y as SpineAnimation,H as Sprite,ye as SystemRunner,Te as Text,Ce as TextAlign,rt as TextInput,ot as TextInputPlugin,Me as TextOverflow,Fe as TextPlugin,Ae as TextRenderer,Ee as TextVerticalAlign,se as Time,qe as UICameraInfo,Ye as UIEventQueue,Ge as UIEvents,Ne as UIInteraction,Ke as UIInteractionPlugin,nt as UILayoutPlugin,Be as UIMask,We as UIMaskPlugin,Re as UIRect,j as Velocity,is as WebAssetProvider,Se as World,D as WorldTransform,_e as addStartupSystem,me as addSystem,ge as addSystemToSchedule,zt as assetPlugin,Bn as clearDrawCallbacks,I as clearUserComponents,x as color,et as computeUIRectLayout,He as createMaskProcessor,$n as createWebApp,F as defineComponent,Q as defineResource,fe as defineSystem,U as defineTag,Ut as findEntityByName,zn as flushPendingSystems,J as getComponentDefaults,t as getPlatform,s as getPlatformType,B as getUserComponent,Kt as initDrawAPI,Mn as initGLDebugAPI,un as initGeometryAPI,mt as initMaterialAPI,mn as initPostProcessAPI,Pn as initRendererAPI,be as inputPlugin,Dt as instantiatePrefab,Ie as intersectRects,$e as invertMatrix4,z as isBuiltinComponent,ds as isEditor,n as isPlatformInitialized,hs as isRuntime,ut as isTextureRef,r as isWeChat,o as isWeb,Rt as loadComponent,Gn as loadPhysicsModule,os as loadRuntimeScene,Tt as loadSceneData,At as loadSceneWithAssets,i as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Le as pointInWorldRect,Xt as prefabsPlugin,v as quat,Fn as registerDrawCallback,Lt as registerEmbeddedAssets,Ct as registerMaterialCallback,ze as screenToWorld,us as setEditorMode,Qt as shutdownDrawAPI,Tn as shutdownGLDebugAPI,dn as shutdownGeometryAPI,_t as shutdownMaterialAPI,_n as shutdownPostProcessAPI,Sn as shutdownRendererAPI,lt as textInputPlugin,Ue as textPlugin,Qe as uiInteractionPlugin,st as uiLayoutPlugin,Oe as uiMaskPlugin,Un as unregisterDrawCallback,Ft as updateCameraAspectRatio,g as vec2,y as vec3,w as vec4,ke as worldRectToScreen};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index c9f538421..7aae13ecf 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -321,6 +321,10 @@ interface CppResourceManager {
loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
releaseBitmapFont(handle: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
+ width: number;
+ height: number;
+ };
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -571,7 +575,9 @@ declare class RenderPipeline {
private maskProcessor_;
private lastWidth_;
private lastHeight_;
+ get spineRenderer(): SpineRendererFn | null;
setSpineRenderer(fn: SpineRendererFn | null): void;
+ get maskProcessor(): MaskProcessorFn | null;
setMaskProcessor(fn: MaskProcessorFn | null): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index ebd6311cf..d06be5ca4 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -271,6 +271,10 @@ interface CppResourceManager {
loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
releaseBitmapFont(handle: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
+ width: number;
+ height: number;
+ };
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
@@ -521,7 +525,9 @@ declare class RenderPipeline {
private maskProcessor_;
private lastWidth_;
private lastHeight_;
+ get spineRenderer(): SpineRendererFn | null;
setSpineRenderer(fn: SpineRendererFn | null): void;
+ get maskProcessor(): MaskProcessorFn | null;
setMaskProcessor(fn: MaskProcessorFn | null): void;
render(params: RenderParams): void;
renderCamera(params: CameraRenderParams): void;
diff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.ts
index d1fbd9072..0e26f2590 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -231,6 +231,10 @@ interface CppResourceManager {
loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
releaseBitmapFont(handle: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
+ width: number;
+ height: number;
+ };
}
interface EmscriptenFS {
writeFile(path: string, data: string | Uint8Array): void;
diff --git a/desktop/public/wasm/esengine.js b/desktop/public/wasm/esengine.js
index b0c47f948..25c82406c 100644
--- a/desktop/public/wasm/esengine.js
+++ b/desktop/public/wasm/esengine.js
@@ -10,129 +10,129 @@ a=b[0];b=b[1];if(!a&&!b)return".";b&&=b.slice(0,-1);return a+b},Na=a=>a&&a.match
return(c?"/":"")+b||"."},Sa=(a,b)=>{function c(g){for(var k=0;k<g.length&&""===g[k];k++);for(var m=g.length-1;0<=m&&""===g[m];m--);return k>m?[]:g.slice(k,m-k+1)}a=Ra(a).slice(1);b=Ra(b).slice(1);a=c(a.split("/"));b=c(b.split("/"));for(var d=Math.min(a.length,b.length),e=d,f=0;f<d;f++)if(a[f]!==b[f]){e=f;break}d=[];for(f=e;f<a.length;f++)d.push("..");d=d.concat(b.slice(e));return d.join("/")},Ta=globalThis.TextDecoder&&new TextDecoder,Ua=(a,b,c,d)=>{c=b+c;if(d)return c;for(;a[b]&&!(b>=c);)++b;return b},
D=(a,b=0,c,d)=>{c=Ua(a,b,c,d);if(16<c-b&&a.buffer&&Ta)return Ta.decode(a.subarray(b,c));for(d="";b<c;){var e=a[b++];if(e&128){var f=a[b++]&63;if(192==(e&224))d+=String.fromCharCode((e&31)<<6|f);else{var g=a[b++]&63;e=224==(e&240)?(e&15)<<12|f<<6|g:(e&7)<<18|f<<12|g<<6|a[b++]&63;65536>e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}return d},Va=[],Wa=a=>{for(var b=0,c=0;c<a.length;++c){var d=a.charCodeAt(c);127>=d?b++:2047>=d?
b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b},E=(a,b,c,d)=>{if(!(0<d))return 0;var e=c;d=c+d-1;for(var f=0;f<a.length;++f){var g=a.codePointAt(f);if(127>=g){if(c>=d)break;b[c++]=g}else if(2047>=g){if(c+1>=d)break;b[c++]=192|g>>6;b[c++]=128|g&63}else if(65535>=g){if(c+2>=d)break;b[c++]=224|g>>12;b[c++]=128|g>>6&63;b[c++]=128|g&63}else{if(c+3>=d)break;b[c++]=240|g>>18;b[c++]=128|g>>12&63;b[c++]=128|g>>6&63;b[c++]=128|g&63;f++}}b[c]=0;return c-e},Xa=a=>{var b=Array(Wa(a)+1);a=E(a,b,0,b.length);b.length=
-a;return b},Ya=[];function Za(a,b){Ya[a]={input:[],output:[],Jb:b};$a(a,ab)}
-var ab={open(a){var b=Ya[a.node.rdev];if(!b)throw new C.gb(43);a.tty=b;a.seekable=!1},close(a){a.tty.Jb.fsync(a.tty)},fsync(a){a.tty.Jb.fsync(a.tty)},read(a,b,c,d){if(!a.tty||!a.tty.Jb.Oc)throw new C.gb(60);for(var e=0,f=0;f<d;f++){try{var g=a.tty.Jb.Oc(a.tty)}catch(k){throw new C.gb(29);}if(void 0===g&&0===e)throw new C.gb(6);if(null===g||void 0===g)break;e++;b[c+f]=g}e&&(a.node.atime=Date.now());return e},write(a,b,c,d){if(!a.tty||!a.tty.Jb.Bc)throw new C.gb(60);try{for(var e=0;e<d;e++)a.tty.Jb.Bc(a.tty,
-b[c+e])}catch(f){throw new C.gb(29);}d&&(a.node.mtime=a.node.ctime=Date.now());return e}},bb={Oc(){a:{if(!Va.length){var a=null;if(ca){var b=Buffer.alloc(256),c=0,d=process.stdin.fd;try{c=fs.readSync(d,b,0,256)}catch(e){if(e.toString().includes("EOF"))c=0;else throw e;}0<c&&(a=b.slice(0,c).toString("utf-8"))}else globalThis.window?.prompt&&(a=window.prompt("Input: "),null!==a&&(a+="\n"));if(!a){a=null;break a}Va=Xa(a)}a=Va.shift()}return a},Bc(a,b){null===b||10===b?(la(D(a.output)),a.output=[]):0!=
-b&&a.output.push(b)},fsync(a){0<a.output?.length&&(la(D(a.output)),a.output=[])},Bd(){return{Xd:25856,Zd:5,Wd:191,Yd:35387,Vd:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},Cd(){return 0},Dd(){return[24,80]}},cb={Bc(a,b){null===b||10===b?(n(D(a.output)),a.output=[]):0!=b&&a.output.push(b)},fsync(a){0<a.output?.length&&(n(D(a.output)),a.output=[])}},H={Fb:null,ob(){return H.createNode(null,"/",16895,0)},createNode(a,b,c,d){if(24576===(c&61440)||C.isFIFO(c))throw new C.gb(63);
-H.Fb||(H.Fb={dir:{node:{Cb:H.ib.Cb,Eb:H.ib.Eb,lookup:H.ib.lookup,Hb:H.ib.Hb,rename:H.ib.rename,unlink:H.ib.unlink,rmdir:H.ib.rmdir,readdir:H.ib.readdir,symlink:H.ib.symlink},stream:{wb:H.jb.wb}},file:{node:{Cb:H.ib.Cb,Eb:H.ib.Eb},stream:{wb:H.jb.wb,read:H.jb.read,write:H.jb.write,Tb:H.jb.Tb,ac:H.jb.ac}},link:{node:{Cb:H.ib.Cb,Eb:H.ib.Eb,readlink:H.ib.readlink},stream:{}},Fc:{node:{Cb:H.ib.Cb,Eb:H.ib.Eb},stream:C.ld}});c=C.createNode(a,b,c,d);I(c.mode)?(c.ib=H.Fb.dir.node,c.jb=H.Fb.dir.stream,c.kb=
-{}):C.isFile(c.mode)?(c.ib=H.Fb.file.node,c.jb=H.Fb.file.stream,c.qb=0,c.kb=null):40960===(c.mode&61440)?(c.ib=H.Fb.link.node,c.jb=H.Fb.link.stream):8192===(c.mode&61440)&&(c.ib=H.Fb.Fc.node,c.jb=H.Fb.Fc.stream);c.atime=c.mtime=c.ctime=Date.now();a&&(a.kb[b]=c,a.atime=a.mtime=a.ctime=c.atime);return c},ke(a){return a.kb?a.kb.subarray?a.kb.subarray(0,a.qb):new Uint8Array(a.kb):new Uint8Array(0)},ib:{Cb(a){var b={};b.dev=8192===(a.mode&61440)?a.id:1;b.ino=a.id;b.mode=a.mode;b.nlink=1;b.uid=0;b.gid=
-0;b.rdev=a.rdev;I(a.mode)?b.size=4096:C.isFile(a.mode)?b.size=a.qb:40960===(a.mode&61440)?b.size=a.link.length:b.size=0;b.atime=new Date(a.atime);b.mtime=new Date(a.mtime);b.ctime=new Date(a.ctime);b.blksize=4096;b.blocks=Math.ceil(b.size/b.blksize);return b},Eb(a,b){for(var c of["mode","atime","mtime","ctime"])null!=b[c]&&(a[c]=b[c]);void 0!==b.size&&(b=b.size,a.qb!=b&&(0==b?(a.kb=null,a.qb=0):(c=a.kb,a.kb=new Uint8Array(b),c&&a.kb.set(c.subarray(0,Math.min(b,a.qb))),a.qb=b)))},lookup(){H.qc||(H.qc=
-new C.gb(44),H.qc.stack="<generic error, no stack>");throw H.qc;},Hb(a,b,c,d){return H.createNode(a,b,c,d)},rename(a,b,c){try{var d=L(b,c)}catch(f){}if(d){if(I(a.mode))for(var e in d.kb)throw new C.gb(55);db(d)}delete a.parent.kb[a.name];b.kb[c]=a;a.name=c;b.ctime=b.mtime=a.parent.ctime=a.parent.mtime=Date.now()},unlink(a,b){delete a.kb[b];a.ctime=a.mtime=Date.now()},rmdir(a,b){var c=L(a,b),d;for(d in c.kb)throw new C.gb(55);delete a.kb[b];a.ctime=a.mtime=Date.now()},readdir(a){return[".","..",...Object.keys(a.kb)]},
-symlink(a,b,c){a=H.createNode(a,b,41471,0);a.link=c;return a},readlink(a){if(40960!==(a.mode&61440))throw new C.gb(28);return a.link}},jb:{read(a,b,c,d,e){var f=a.node.kb;if(e>=a.node.qb)return 0;a=Math.min(a.node.qb-e,d);if(8<a&&f.subarray)b.set(f.subarray(e,e+a),c);else for(d=0;d<a;d++)b[c+d]=f[e+d];return a},write(a,b,c,d,e,f){b.buffer===q.buffer&&(f=!1);if(!d)return 0;a=a.node;a.mtime=a.ctime=Date.now();if(b.subarray&&(!a.kb||a.kb.subarray)){if(f)return a.kb=b.subarray(c,c+d),a.qb=d;if(0===a.qb&&
-0===e)return a.kb=b.slice(c,c+d),a.qb=d;if(e+d<=a.qb)return a.kb.set(b.subarray(c,c+d),e),d}f=e+d;var g=a.kb?a.kb.length:0;g>=f||(f=Math.max(f,g*(1048576>g?2:1.125)>>>0),0!=g&&(f=Math.max(f,256)),g=a.kb,a.kb=new Uint8Array(f),0<a.qb&&a.kb.set(g.subarray(0,a.qb),0));if(a.kb.subarray&&b.subarray)a.kb.set(b.subarray(c,c+d),e);else for(f=0;f<d;f++)a.kb[e+f]=b[c+f];a.qb=Math.max(a.qb,e+d);return d},wb(a,b,c){1===c?b+=a.position:2===c&&C.isFile(a.node.mode)&&(b+=a.node.qb);if(0>b)throw new C.gb(28);return b},
-Tb(a,b,c,d,e){if(!C.isFile(a.node.mode))throw new C.gb(43);a=a.node.kb;if(e&2||!a||a.buffer!==q.buffer){d=!0;y();e=void 0;if(!e)throw new C.gb(48);if(a){if(0<c||c+b<a.length)a.subarray?a=a.subarray(c,c+b):a=Array.prototype.slice.call(a,c,c+b);q.set(a,e)}}else d=!1,e=a.byteOffset;return{lb:e,Rd:d}},ac(a,b,c,d){H.jb.write(a,b,0,d,c,!1);return 0}}},eb=(a,b)=>{var c=0;a&&(c|=365);b&&(c|=146);return c},fb=async a=>{a=await ia(a);return new Uint8Array(a)},gb=0,hb=null,ib=()=>{gb--;h.monitorRunDependencies?.(gb);
+a;return b},Ya=[];function Za(a,b){Ya[a]={input:[],output:[],Lb:b};$a(a,ab)}
+var ab={open(a){var b=Ya[a.node.rdev];if(!b)throw new C.ib(43);a.tty=b;a.seekable=!1},close(a){a.tty.Lb.fsync(a.tty)},fsync(a){a.tty.Lb.fsync(a.tty)},read(a,b,c,d){if(!a.tty||!a.tty.Lb.Qc)throw new C.ib(60);for(var e=0,f=0;f<d;f++){try{var g=a.tty.Lb.Qc(a.tty)}catch(k){throw new C.ib(29);}if(void 0===g&&0===e)throw new C.ib(6);if(null===g||void 0===g)break;e++;b[c+f]=g}e&&(a.node.atime=Date.now());return e},write(a,b,c,d){if(!a.tty||!a.tty.Lb.Dc)throw new C.ib(60);try{for(var e=0;e<d;e++)a.tty.Lb.Dc(a.tty,
+b[c+e])}catch(f){throw new C.ib(29);}d&&(a.node.mtime=a.node.ctime=Date.now());return e}},bb={Qc(){a:{if(!Va.length){var a=null;if(ca){var b=Buffer.alloc(256),c=0,d=process.stdin.fd;try{c=fs.readSync(d,b,0,256)}catch(e){if(e.toString().includes("EOF"))c=0;else throw e;}0<c&&(a=b.slice(0,c).toString("utf-8"))}else globalThis.window?.prompt&&(a=window.prompt("Input: "),null!==a&&(a+="\n"));if(!a){a=null;break a}Va=Xa(a)}a=Va.shift()}return a},Dc(a,b){null===b||10===b?(la(D(a.output)),a.output=[]):0!=
+b&&a.output.push(b)},fsync(a){0<a.output?.length&&(la(D(a.output)),a.output=[])},Dd(){return{Zd:25856,ae:5,Yd:191,$d:35387,Xd:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},Ed(){return 0},Fd(){return[24,80]}},cb={Dc(a,b){null===b||10===b?(n(D(a.output)),a.output=[]):0!=b&&a.output.push(b)},fsync(a){0<a.output?.length&&(n(D(a.output)),a.output=[])}},H={Hb:null,qb(){return H.createNode(null,"/",16895,0)},createNode(a,b,c,d){if(24576===(c&61440)||C.isFIFO(c))throw new C.ib(63);
+H.Hb||(H.Hb={dir:{node:{Eb:H.kb.Eb,Gb:H.kb.Gb,lookup:H.kb.lookup,Jb:H.kb.Jb,rename:H.kb.rename,unlink:H.kb.unlink,rmdir:H.kb.rmdir,readdir:H.kb.readdir,symlink:H.kb.symlink},stream:{yb:H.lb.yb}},file:{node:{Eb:H.kb.Eb,Gb:H.kb.Gb},stream:{yb:H.lb.yb,read:H.lb.read,write:H.lb.write,Vb:H.lb.Vb,cc:H.lb.cc}},link:{node:{Eb:H.kb.Eb,Gb:H.kb.Gb,readlink:H.kb.readlink},stream:{}},Hc:{node:{Eb:H.kb.Eb,Gb:H.kb.Gb},stream:C.nd}});c=C.createNode(a,b,c,d);I(c.mode)?(c.kb=H.Hb.dir.node,c.lb=H.Hb.dir.stream,c.mb=
+{}):C.isFile(c.mode)?(c.kb=H.Hb.file.node,c.lb=H.Hb.file.stream,c.sb=0,c.mb=null):40960===(c.mode&61440)?(c.kb=H.Hb.link.node,c.lb=H.Hb.link.stream):8192===(c.mode&61440)&&(c.kb=H.Hb.Hc.node,c.lb=H.Hb.Hc.stream);c.atime=c.mtime=c.ctime=Date.now();a&&(a.mb[b]=c,a.atime=a.mtime=a.ctime=c.atime);return c},me(a){return a.mb?a.mb.subarray?a.mb.subarray(0,a.sb):new Uint8Array(a.mb):new Uint8Array(0)},kb:{Eb(a){var b={};b.dev=8192===(a.mode&61440)?a.id:1;b.ino=a.id;b.mode=a.mode;b.nlink=1;b.uid=0;b.gid=
+0;b.rdev=a.rdev;I(a.mode)?b.size=4096:C.isFile(a.mode)?b.size=a.sb:40960===(a.mode&61440)?b.size=a.link.length:b.size=0;b.atime=new Date(a.atime);b.mtime=new Date(a.mtime);b.ctime=new Date(a.ctime);b.blksize=4096;b.blocks=Math.ceil(b.size/b.blksize);return b},Gb(a,b){for(var c of["mode","atime","mtime","ctime"])null!=b[c]&&(a[c]=b[c]);void 0!==b.size&&(b=b.size,a.sb!=b&&(0==b?(a.mb=null,a.sb=0):(c=a.mb,a.mb=new Uint8Array(b),c&&a.mb.set(c.subarray(0,Math.min(b,a.sb))),a.sb=b)))},lookup(){H.sc||(H.sc=
+new C.ib(44),H.sc.stack="<generic error, no stack>");throw H.sc;},Jb(a,b,c,d){return H.createNode(a,b,c,d)},rename(a,b,c){try{var d=L(b,c)}catch(f){}if(d){if(I(a.mode))for(var e in d.mb)throw new C.ib(55);db(d)}delete a.parent.mb[a.name];b.mb[c]=a;a.name=c;b.ctime=b.mtime=a.parent.ctime=a.parent.mtime=Date.now()},unlink(a,b){delete a.mb[b];a.ctime=a.mtime=Date.now()},rmdir(a,b){var c=L(a,b),d;for(d in c.mb)throw new C.ib(55);delete a.mb[b];a.ctime=a.mtime=Date.now()},readdir(a){return[".","..",...Object.keys(a.mb)]},
+symlink(a,b,c){a=H.createNode(a,b,41471,0);a.link=c;return a},readlink(a){if(40960!==(a.mode&61440))throw new C.ib(28);return a.link}},lb:{read(a,b,c,d,e){var f=a.node.mb;if(e>=a.node.sb)return 0;a=Math.min(a.node.sb-e,d);if(8<a&&f.subarray)b.set(f.subarray(e,e+a),c);else for(d=0;d<a;d++)b[c+d]=f[e+d];return a},write(a,b,c,d,e,f){b.buffer===q.buffer&&(f=!1);if(!d)return 0;a=a.node;a.mtime=a.ctime=Date.now();if(b.subarray&&(!a.mb||a.mb.subarray)){if(f)return a.mb=b.subarray(c,c+d),a.sb=d;if(0===a.sb&&
+0===e)return a.mb=b.slice(c,c+d),a.sb=d;if(e+d<=a.sb)return a.mb.set(b.subarray(c,c+d),e),d}f=e+d;var g=a.mb?a.mb.length:0;g>=f||(f=Math.max(f,g*(1048576>g?2:1.125)>>>0),0!=g&&(f=Math.max(f,256)),g=a.mb,a.mb=new Uint8Array(f),0<a.sb&&a.mb.set(g.subarray(0,a.sb),0));if(a.mb.subarray&&b.subarray)a.mb.set(b.subarray(c,c+d),e);else for(f=0;f<d;f++)a.mb[e+f]=b[c+f];a.sb=Math.max(a.sb,e+d);return d},yb(a,b,c){1===c?b+=a.position:2===c&&C.isFile(a.node.mode)&&(b+=a.node.sb);if(0>b)throw new C.ib(28);return b},
+Vb(a,b,c,d,e){if(!C.isFile(a.node.mode))throw new C.ib(43);a=a.node.mb;if(e&2||!a||a.buffer!==q.buffer){d=!0;y();e=void 0;if(!e)throw new C.ib(48);if(a){if(0<c||c+b<a.length)a.subarray?a=a.subarray(c,c+b):a=Array.prototype.slice.call(a,c,c+b);q.set(a,e)}}else d=!1,e=a.byteOffset;return{nb:e,Td:d}},cc(a,b,c,d){H.lb.write(a,b,0,d,c,!1);return 0}}},eb=(a,b)=>{var c=0;a&&(c|=365);b&&(c|=146);return c},fb=async a=>{a=await ia(a);return new Uint8Array(a)},gb=0,hb=null,ib=()=>{gb--;h.monitorRunDependencies?.(gb);
if(0==gb&&hb){var a=hb;hb=null;a()}},jb=()=>{gb++;h.monitorRunDependencies?.(gb)},kb=[],mb=async(a,b)=>{"undefined"!=typeof Browser&&lb();for(var c of kb)if(c.canHandle(b))return c.handle(a,b);return a},ob=async(a,b,c,d,e,f,g,k)=>{var m=b?Ra(La(a+"/"+b)):a,l=`cp ${m}`;jb(l);try{var p=c;"string"==typeof c&&(p=await fb(c));p=await mb(p,m);k?.();f||nb(a,b,p,d,e,g)}finally{ib(l)}};
-function lb(){var a,b,c;C.tc=!0;a??=h.stdin;b??=h.stdout;c??=h.stderr;a?C.Kb("/dev","stdin",a):C.symlink("/dev/tty","/dev/stdin");b?C.Kb("/dev","stdout",null,b):C.symlink("/dev/tty","/dev/stdout");c?C.Kb("/dev","stderr",null,c):C.symlink("/dev/tty1","/dev/stderr");C.open("/dev/stdin",0);C.open("/dev/stdout",1);C.open("/dev/stderr",1)}function $a(a,b){C.Jc[a]={jb:b}}function I(a){return 16384===(a&61440)}
-function L(a,b){var c=I(a.mode)?(c=pb(a,"x"))?c:a.ib.lookup?0:2:54;if(c)throw new C.gb(c);for(c=C.Ib[qb(a.id,b)];c;c=c.Pb){var d=c.name;if(c.parent.id===a.id&&d===b)return c}return C.lookup(a,b)}function db(a){var b=qb(a.parent.id,a.name);if(C.Ib[b]===a)C.Ib[b]=a.Pb;else for(b=C.Ib[b];b;){if(b.Pb===a){b.Pb=a.Pb;break}b=b.Pb}}
+function lb(){var a,b,c;C.uc=!0;a??=h.stdin;b??=h.stdout;c??=h.stderr;a?C.Mb("/dev","stdin",a):C.symlink("/dev/tty","/dev/stdin");b?C.Mb("/dev","stdout",null,b):C.symlink("/dev/tty","/dev/stdout");c?C.Mb("/dev","stderr",null,c):C.symlink("/dev/tty1","/dev/stderr");C.open("/dev/stdin",0);C.open("/dev/stdout",1);C.open("/dev/stderr",1)}function $a(a,b){C.Lc[a]={lb:b}}function I(a){return 16384===(a&61440)}
+function L(a,b){var c=I(a.mode)?(c=pb(a,"x"))?c:a.kb.lookup?0:2:54;if(c)throw new C.ib(c);for(c=C.Kb[qb(a.id,b)];c;c=c.Rb){var d=c.name;if(c.parent.id===a.id&&d===b)return c}return C.lookup(a,b)}function db(a){var b=qb(a.parent.id,a.name);if(C.Kb[b]===a)C.Kb[b]=a.Rb;else for(b=C.Kb[b];b;){if(b.Rb===a){b.Rb=a.Rb;break}b=b.Rb}}
function nb(a,b,c,d,e,f){var g=b;a&&(a="string"==typeof a?a:rb(a),g=b?La(a+"/"+b):a);a=eb(d,e);g=C.create(g,a);if(c){if("string"==typeof c){b=Array(c.length);d=0;for(e=c.length;d<e;++d)b[d]=c.charCodeAt(d);c=b}C.chmod(g,a|146);b=C.open(g,577);C.write(b,c,0,c.length,0,f);C.close(b);C.chmod(g,a)}}
-function M(a,b={}){if(!a)throw new C.gb(44);b.ic??(b.ic=!0);"/"===a.charAt(0)||(a=C.cwd()+"/"+a);var c=0;a:for(;40>c;c++){a=a.split("/").filter(k=>!!k);for(var d=C.root,e="/",f=0;f<a.length;f++){var g=f===a.length-1;if(g&&b.parent)break;if("."!==a[f])if(".."===a[f])if(e=Ma(e),C.wc(d)){a=e+"/"+a.slice(f+1).join("/");c--;continue a}else d=d.parent;else{e=La(e+"/"+a[f]);try{d=L(d,a[f])}catch(k){if(44===k?.Ab&&g&&b.Hd)return{path:e};throw k;}!d.Db||g&&!b.ic||(d=d.Db.root);if(40960===(d.mode&61440)&&(!g||
-b.Bb)){if(!d.ib.readlink)throw new C.gb(52);d=d.ib.readlink(d);"/"===d.charAt(0)||(d=Ma(e)+"/"+d);a=d+"/"+a.slice(f+1).join("/");continue a}}}return{path:e,node:d}}throw new C.gb(32);}function rb(a){for(var b;;){if(C.wc(a))return a=a.ob.Vc,b?"/"!==a[a.length-1]?`${a}/${b}`:a+b:a;b=b?`${a.name}/${b}`:a.name;a=a.parent}}function qb(a,b){for(var c=0,d=0;d<b.length;d++)c=(c<<5)-c+b.charCodeAt(d)|0;return(a+c>>>0)%C.Ib.length}function sb(a){var b=qb(a.parent.id,a.name);a.Pb=C.Ib[b];C.Ib[b]=a}
-function tb(a){var b=["r","w","rw"][a&3];a&512&&(b+="w");return b}function pb(a,b){if(C.Qc)return 0;if(!b.includes("r")||a.mode&292){if(b.includes("w")&&!(a.mode&146)||b.includes("x")&&!(a.mode&73))return 2}else return 2;return 0}function ub(a,b){if(!I(a.mode))return 54;try{return L(a,b),20}catch(c){}return pb(a,"wx")}
-function vb(a,b,c){try{var d=L(a,b)}catch(e){return e.Ab}if(a=pb(a,"wx"))return a;if(c){if(!I(d.mode))return 54;if(C.wc(d)||rb(d)===C.cwd())return 10}else if(I(d.mode))return 31;return 0}function wb(a,b){if(!a)throw new C.gb(b);return a}function N(a){a=C.wd(a);if(!a)throw new C.gb(8);return a}function xb(a,b=-1){a=Object.assign(new C.hd,a);if(-1==b)a:{for(b=0;b<=C.kd;b++)if(!C.streams[b])break a;throw new C.gb(33);}a.fd=b;return C.streams[b]=a}
-function yb(a,b=-1){a=xb(a,b);a.jb?.ce?.(a);return a}function zb(a,b,c){var d=a?.jb.Eb;a=d?a:b;d??=b.ib.Eb;wb(d,63);d(a,c)}function Ab(a){var b=[];for(a=[a];a.length;){var c=a.pop();b.push(c);a.push(...c.$b)}return b}function Bb(a){var b={Ud:4096,he:4096,blocks:1E6,Td:5E5,Sd:5E5,files:C.Ac,fe:C.Ac-1,ie:42,flags:2,qe:255};a.ib.$c&&Object.assign(b,a.ib.$c(a.ob.Id.root));return b}function Cb(a,b,c){"undefined"==typeof c&&(c=b,b=438);return C.Hb(a,b|8192,c)}
-function Db(a,b,c,d){zb(a,b,{mode:c&4095|b.mode&-4096,ctime:Date.now(),Lc:d})}function Eb(a,b,c){if(I(b.mode))throw new C.gb(31);if(!C.isFile(b.mode))throw new C.gb(28);var d=pb(b,"w");if(d)throw new C.gb(d);zb(a,b,{size:c,timestamp:Date.now()})}function Fb(a,b){a="string"==typeof a?a:rb(a);for(b=b.split("/").reverse();b.length;){var c=b.pop();if(c){var d=La(a+"/"+c);try{C.mkdir(d)}catch(e){if(20!=e.Ab)throw e;}a=d}}return d}
-function Gb(a,b,c,d){a="string"==typeof a?a:rb(a);b=La(a+"/"+b);return C.create(b,eb(c,d))}function Hb(a){if(!(a.Ed||a.Fd||a.link||a.kb))if(globalThis.XMLHttpRequest)y("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{a.kb=ja(a.url)}catch(b){throw new C.gb(29);}}
-function Ib(a,b,c,d,e){class f{sc=!1;yb=[];Zb=void 0;Sc=0;Pc=0;get(l){if(!(l>this.length-1||0>l)){var p=l%this.chunkSize;return this.Zb(l/this.chunkSize|0)[p]}}Gd(l){this.Zb=l}Tc(){var l=new XMLHttpRequest;l.open("HEAD",c,!1);l.send(null);200<=l.status&&300>l.status||304===l.status||y("Couldn't load "+c+". Status: "+l.status);var p=Number(l.getResponseHeader("Content-length")),r,v=(r=l.getResponseHeader("Accept-Ranges"))&&"bytes"===r;l=(r=l.getResponseHeader("Content-Encoding"))&&"gzip"===r;var z=
-1048576;v||(z=p);var B=this;B.Gd(F=>{var J=F*z,P=(F+1)*z-1;P=Math.min(P,p-1);if("undefined"==typeof B.yb[F]){var K=B.yb;J>P&&y("invalid range ("+J+", "+P+") or no bytes requested!");P>p-1&&y("only "+p+" bytes available! programmer error!");var G=new XMLHttpRequest;G.open("GET",c,!1);p!==z&&G.setRequestHeader("Range","bytes="+J+"-"+P);G.responseType="arraybuffer";G.overrideMimeType&&G.overrideMimeType("text/plain; charset=x-user-defined");G.send(null);200<=G.status&&300>G.status||304===G.status||y("Couldn't load "+
-c+". Status: "+G.status);J=void 0!==G.response?new Uint8Array(G.response||[]):Xa(G.responseText||"");K[F]=J}"undefined"==typeof B.yb[F]&&y("doXHR failed!");return B.yb[F]});if(l||!p)z=p=1,z=p=this.Zb(0).length,la("LazyFiles on gzip forces download of the whole file when length is accessed");this.Sc=p;this.Pc=z;this.sc=!0}get length(){this.sc||this.Tc();return this.Sc}get chunkSize(){this.sc||this.Tc();return this.Pc}}if(globalThis.XMLHttpRequest){ba||y("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");
-var g=new f;var k=void 0}else k=c,g=void 0;var m=Gb(a,b,d,e);g?m.kb=g:k&&(m.kb=null,m.url=k);Object.defineProperties(m,{qb:{get:function(){return this.kb.length}}});a={};for(const [l,p]of Object.entries(m.jb))a[l]=(...r)=>{Hb(m);return p(...r)};a.read=(l,p,r,v,z)=>{Hb(m);l=l.node.kb;if(z>=l.length)p=0;else{v=Math.min(l.length-z,v);if(l.slice)for(var B=0;B<v;B++)p[r+B]=l[z+B];else for(B=0;B<v;B++)p[r+B]=l.get(z+B);p=v}return p};a.Tb=()=>{Hb(m);y();throw new C.gb(48);};m.jb=a;return m}
-var C={root:null,$b:[],Jc:{},streams:[],Ac:1,Ib:null,Gc:"/",tc:!1,Qc:!0,sd:null,oc:0,Yc:{},gb:class{name="ErrnoError";constructor(a){this.Ab=a}},hd:class{yb={};node=null;get object(){return this.node}set object(a){this.node=a}get flags(){return this.yb.flags}set flags(a){this.yb.flags=a}get position(){return this.yb.position}set position(a){this.yb.position=a}},gd:class{ib={};jb={};Db=null;constructor(a,b,c,d){a||=this;this.parent=a;this.ob=a.ob;this.id=C.Ac++;this.name=b;this.mode=c;this.rdev=d;
-this.atime=this.mtime=this.ctime=Date.now()}get read(){return 365===(this.mode&365)}set read(a){a?this.mode|=365:this.mode&=-366}get write(){return 146===(this.mode&146)}set write(a){a?this.mode|=146:this.mode&=-147}get Fd(){return I(this.mode)}get Ed(){return 8192===(this.mode&61440)}},createNode(a,b,c,d){a=new C.gd(a,b,c,d);sb(a);return a},wc(a){return a===a.parent},isFile(a){return 32768===(a&61440)},isFIFO(a){return 4096===(a&61440)},isSocket(a){return 49152===(a&49152)},kd:4096,wd:a=>C.streams[a],
-ld:{open(a){a.jb=C.ud(a.node.rdev).jb;a.jb.open?.(a)},wb(){throw new C.gb(70);}},yc:a=>a>>8,me:a=>a&255,Ob:(a,b)=>a<<8|b,ud:a=>C.Jc[a],ad(a,b){function c(k){C.oc--;return b(k)}function d(k){if(k){if(!d.pd)return d.pd=!0,c(k)}else++f>=e.length&&c(null)}"function"==typeof a&&(b=a,a=!1);C.oc++;1<C.oc&&n(`warning: ${C.oc} FS.syncfs operations in flight at once, probably just doing extra work`);var e=Ab(C.root.ob),f=0,g;for(g of e)g.type.ad?g.type.ad(g,a,d):d(null)},ob(a,b,c){var d="/"===c;if(d&&C.root)throw new C.gb(10);
-if(!d&&c){var e=M(c,{ic:!1});c=e.path;e=e.node;if(e.Db)throw new C.gb(10);if(!I(e.mode))throw new C.gb(54);}b={type:a,Id:b,Vc:c,$b:[]};a=a.ob(b);a.ob=b;b.root=a;d?C.root=a:e&&(e.Db=b,e.ob&&e.ob.$b.push(b));return a},ze(a){a=M(a,{ic:!1});if(!a.node.Db)throw new C.gb(28);a=a.node;var b=a.Db,c=Ab(b);for([,e]of Object.entries(C.Ib))for(;e;){var d=e.Pb;c.includes(e.ob)&&db(e);var e=d}a.Db=null;a.ob.$b.splice(a.ob.$b.indexOf(b),1)},lookup(a,b){return a.ib.lookup(a,b)},Hb(a,b,c){var d=M(a,{parent:!0}).node;
-a=Na(a);if(!a)throw new C.gb(28);if("."===a||".."===a)throw new C.gb(20);var e=ub(d,a);if(e)throw new C.gb(e);if(!d.ib.Hb)throw new C.gb(63);return d.ib.Hb(d,a,b,c)},$c(a){return Bb(M(a,{Bb:!0}).node)},xe(a){return Bb(a.node)},create(a,b=438){return C.Hb(a,b&4095|32768,0)},mkdir(a,b=511){return C.Hb(a,b&1023|16384,0)},oe(a,b){var c=a.split("/"),d="",e;for(e of c)if(e){if(d||"/"===a.charAt(0))d+="/";d+=e;try{C.mkdir(d,b)}catch(f){if(20!=f.Ab)throw f;}}},symlink(a,b){if(!Ra(a))throw new C.gb(44);var c=
-M(b,{parent:!0}).node;if(!c)throw new C.gb(44);b=Na(b);var d=ub(c,b);if(d)throw new C.gb(d);if(!c.ib.symlink)throw new C.gb(63);return c.ib.symlink(c,b,a)},rename(a,b){var c=Ma(a),d=Ma(b),e=Na(a),f=Na(b);var g=M(a,{parent:!0});var k=g.node;g=M(b,{parent:!0});g=g.node;if(!k||!g)throw new C.gb(44);if(k.ob!==g.ob)throw new C.gb(75);var m=L(k,e);a=Sa(a,d);if("."!==a.charAt(0))throw new C.gb(28);a=Sa(b,c);if("."!==a.charAt(0))throw new C.gb(55);try{var l=L(g,f)}catch(p){}if(m!==l){b=I(m.mode);if(e=vb(k,
-e,b))throw new C.gb(e);if(e=l?vb(g,f,b):ub(g,f))throw new C.gb(e);if(!k.ib.rename)throw new C.gb(63);if(m.Db||l&&l.Db)throw new C.gb(10);if(g!==k&&(e=pb(k,"w")))throw new C.gb(e);db(m);try{k.ib.rename(m,g,f),m.parent=g}catch(p){throw p;}finally{sb(m)}}},rmdir(a){var b=M(a,{parent:!0}).node;a=Na(a);var c=L(b,a),d=vb(b,a,!0);if(d)throw new C.gb(d);if(!b.ib.rmdir)throw new C.gb(63);if(c.Db)throw new C.gb(10);b.ib.rmdir(b,a);db(c)},readdir(a){a=M(a,{Bb:!0}).node;return wb(a.ib.readdir,54)(a)},unlink(a){var b=
-M(a,{parent:!0}).node;if(!b)throw new C.gb(44);a=Na(a);var c=L(b,a),d=vb(b,a,!1);if(d)throw new C.gb(d);if(!b.ib.unlink)throw new C.gb(63);if(c.Db)throw new C.gb(10);b.ib.unlink(b,a);db(c)},readlink(a){a=M(a).node;if(!a)throw new C.gb(44);if(!a.ib.readlink)throw new C.gb(28);return a.ib.readlink(a)},stat(a,b){a=M(a,{Bb:!b}).node;return wb(a.ib.Cb,63)(a)},fstat(a){var b=N(a);a=b.node;var c=b.jb.Cb;b=c?b:a;c??=a.ib.Cb;wb(c,63);return c(b)},lstat(a){return C.stat(a,!0)},chmod(a,b,c){a="string"==typeof a?
-M(a,{Bb:!c}).node:a;Db(null,a,b,c)},lchmod(a,b){C.chmod(a,b,!0)},fchmod(a,b){a=N(a);Db(a,a.node,b,!1)},chown(a,b,c,d){a="string"==typeof a?M(a,{Bb:!d}).node:a;zb(null,a,{timestamp:Date.now(),Lc:d})},lchown(a,b,c){C.chown(a,b,c,!0)},fchown(a){a=N(a);zb(a,a.node,{timestamp:Date.now(),Lc:!1})},truncate(a,b){if(0>b)throw new C.gb(28);a="string"==typeof a?M(a,{Bb:!0}).node:a;Eb(null,a,b)},je(a,b){a=N(a);if(0>b||0===(a.flags&2097155))throw new C.gb(28);Eb(a,a.node,b)},Ae(a,b,c){a=M(a,{Bb:!0}).node;wb(a.ib.Eb,
-63)(a,{atime:b,mtime:c})},open(a,b,c=438){if(""===a)throw new C.gb(44);if("string"==typeof b){var d={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[b];if("undefined"==typeof d)throw Error(`Unknown file open mode: ${b}`);b=d}c=b&64?c&4095|32768:0;if("object"==typeof a)d=a;else{var e=a.endsWith("/");a=M(a,{Bb:!(b&131072),Hd:!0});d=a.node;a=a.path}var f=!1;if(b&64)if(d){if(b&128)throw new C.gb(20);}else{if(e)throw new C.gb(31);d=C.Hb(a,c|511,0);f=!0}if(!d)throw new C.gb(44);8192===(d.mode&61440)&&(b&=-513);
-if(b&65536&&!I(d.mode))throw new C.gb(54);if(!f&&(e=d?40960===(d.mode&61440)?32:I(d.mode)&&("r"!==tb(b)||b&576)?31:pb(d,tb(b)):44))throw new C.gb(e);b&512&&!f&&C.truncate(d,0);b&=-131713;e=xb({node:d,path:rb(d),flags:b,seekable:!0,position:0,jb:d.jb,Qd:[],error:!1});e.jb.open&&e.jb.open(e);f&&C.chmod(d,c&511);!h.logReadFiles||b&1||a in C.Yc||(C.Yc[a]=1);return e},close(a){if(null===a.fd)throw new C.gb(8);a.rc&&(a.rc=null);try{a.jb.close&&a.jb.close(a)}catch(b){throw b;}finally{C.streams[a.fd]=null}a.fd=
-null},wb(a,b,c){if(null===a.fd)throw new C.gb(8);if(!a.seekable||!a.jb.wb)throw new C.gb(70);if(0!=c&&1!=c&&2!=c)throw new C.gb(28);a.position=a.jb.wb(a,b,c);a.Qd=[];return a.position},read(a,b,c,d,e){if(0>d||0>e)throw new C.gb(28);if(null===a.fd)throw new C.gb(8);if(1===(a.flags&2097155))throw new C.gb(8);if(I(a.node.mode))throw new C.gb(31);if(!a.jb.read)throw new C.gb(28);var f="undefined"!=typeof e;if(!f)e=a.position;else if(!a.seekable)throw new C.gb(70);b=a.jb.read(a,b,c,d,e);f||(a.position+=
-b);return b},write(a,b,c,d,e,f){if(0>d||0>e)throw new C.gb(28);if(null===a.fd)throw new C.gb(8);if(0===(a.flags&2097155))throw new C.gb(8);if(I(a.node.mode))throw new C.gb(31);if(!a.jb.write)throw new C.gb(28);a.seekable&&a.flags&1024&&C.wb(a,0,2);var g="undefined"!=typeof e;if(!g)e=a.position;else if(!a.seekable)throw new C.gb(70);b=a.jb.write(a,b,c,d,e,f);g||(a.position+=b);return b},Tb(a,b,c,d,e){if(0!==(d&2)&&0===(e&2)&&2!==(a.flags&2097155))throw new C.gb(2);if(1===(a.flags&2097155))throw new C.gb(2);
-if(!a.jb.Tb)throw new C.gb(43);if(!b)throw new C.gb(28);return a.jb.Tb(a,b,c,d,e)},ac(a,b,c,d,e){return a.jb.ac?a.jb.ac(a,b,c,d,e):0},uc(a,b,c){if(!a.jb.uc)throw new C.gb(59);return a.jb.uc(a,b,c)},readFile(a,b={}){b.flags=b.flags||0;b.encoding=b.encoding||"binary";"utf8"!==b.encoding&&"binary"!==b.encoding&&y(`Invalid encoding type "${b.encoding}"`);var c=C.open(a,b.flags);a=C.stat(a).size;var d=new Uint8Array(a);C.read(c,d,0,a,0);"utf8"===b.encoding&&(d=D(d));C.close(c);return d},writeFile(a,b,
-c={}){c.flags=c.flags||577;a=C.open(a,c.flags,c.mode);"string"==typeof b&&(b=new Uint8Array(Xa(b)));ArrayBuffer.isView(b)?C.write(a,b,0,b.byteLength,void 0,c.$d):y("Unsupported data type");C.close(a)},cwd:()=>C.Gc,chdir(a){a=M(a,{Bb:!0});if(null===a.node)throw new C.gb(44);if(!I(a.node.mode))throw new C.gb(54);var b=pb(a.node,"x");if(b)throw new C.gb(b);C.Gc=a.path},ue(){C.tc=!1;for(var a of C.streams)a&&C.close(a)},ge(a,b){try{var c=M(a,{Bb:!b});a=c.path}catch(f){}var d=!1,e=null;try{c=M(a,{parent:!0}),
-Na(a),c=M(a,{Bb:!b}),d=!0,e=c.node}catch(f){}return d?e:null},Kb(a,b,c,d){a=Oa("string"==typeof a?a:rb(a),b);b=eb(!!c,!!d);var e;(e=C.Kb).yc??(e.yc=64);e=C.Ob(C.Kb.yc++,0);$a(e,{open(f){f.seekable=!1},close(){d?.buffer?.length&&d(10)},read(f,g,k,m){for(var l=0,p=0;p<m;p++){try{var r=c()}catch(v){throw new C.gb(29);}if(void 0===r&&0===l)throw new C.gb(6);if(null===r||void 0===r)break;l++;g[k+p]=r}l&&(f.node.atime=Date.now());return l},write(f,g,k,m){for(var l=0;l<m;l++)try{d(g[k+l])}catch(p){throw new C.gb(29);
-}m&&(f.node.mtime=f.node.ctime=Date.now());return l}});return Cb(a,b,e)}},Ja=void 0,Jb={},Kb=a=>{for(;a.length;){var b=a.pop();a.pop()(b)}};function Lb(a){return this.nb(x[a>>2])}
+function M(a,b={}){if(!a)throw new C.ib(44);b.kc??(b.kc=!0);"/"===a.charAt(0)||(a=C.cwd()+"/"+a);var c=0;a:for(;40>c;c++){a=a.split("/").filter(k=>!!k);for(var d=C.root,e="/",f=0;f<a.length;f++){var g=f===a.length-1;if(g&&b.parent)break;if("."!==a[f])if(".."===a[f])if(e=Ma(e),C.xc(d)){a=e+"/"+a.slice(f+1).join("/");c--;continue a}else d=d.parent;else{e=La(e+"/"+a[f]);try{d=L(d,a[f])}catch(k){if(44===k?.Cb&&g&&b.Jd)return{path:e};throw k;}!d.Fb||g&&!b.kc||(d=d.Fb.root);if(40960===(d.mode&61440)&&(!g||
+b.Db)){if(!d.kb.readlink)throw new C.ib(52);d=d.kb.readlink(d);"/"===d.charAt(0)||(d=Ma(e)+"/"+d);a=d+"/"+a.slice(f+1).join("/");continue a}}}return{path:e,node:d}}throw new C.ib(32);}function rb(a){for(var b;;){if(C.xc(a))return a=a.qb.Xc,b?"/"!==a[a.length-1]?`${a}/${b}`:a+b:a;b=b?`${a.name}/${b}`:a.name;a=a.parent}}function qb(a,b){for(var c=0,d=0;d<b.length;d++)c=(c<<5)-c+b.charCodeAt(d)|0;return(a+c>>>0)%C.Kb.length}function sb(a){var b=qb(a.parent.id,a.name);a.Rb=C.Kb[b];C.Kb[b]=a}
+function tb(a){var b=["r","w","rw"][a&3];a&512&&(b+="w");return b}function pb(a,b){if(C.Rc)return 0;if(!b.includes("r")||a.mode&292){if(b.includes("w")&&!(a.mode&146)||b.includes("x")&&!(a.mode&73))return 2}else return 2;return 0}function ub(a,b){if(!I(a.mode))return 54;try{return L(a,b),20}catch(c){}return pb(a,"wx")}
+function vb(a,b,c){try{var d=L(a,b)}catch(e){return e.Cb}if(a=pb(a,"wx"))return a;if(c){if(!I(d.mode))return 54;if(C.xc(d)||rb(d)===C.cwd())return 10}else if(I(d.mode))return 31;return 0}function wb(a,b){if(!a)throw new C.ib(b);return a}function N(a){a=C.yd(a);if(!a)throw new C.ib(8);return a}function xb(a,b=-1){a=Object.assign(new C.kd,a);if(-1==b)a:{for(b=0;b<=C.md;b++)if(!C.streams[b])break a;throw new C.ib(33);}a.fd=b;return C.streams[b]=a}
+function yb(a,b=-1){a=xb(a,b);a.lb?.ee?.(a);return a}function zb(a,b,c){var d=a?.lb.Gb;a=d?a:b;d??=b.kb.Gb;wb(d,63);d(a,c)}function Ab(a){var b=[];for(a=[a];a.length;){var c=a.pop();b.push(c);a.push(...c.bc)}return b}function Bb(a){var b={Wd:4096,je:4096,blocks:1E6,Vd:5E5,Ud:5E5,files:C.Cc,he:C.Cc-1,ke:42,flags:2,se:255};a.kb.bd&&Object.assign(b,a.kb.bd(a.qb.Kd.root));return b}function Cb(a,b,c){"undefined"==typeof c&&(c=b,b=438);return C.Jb(a,b|8192,c)}
+function Db(a,b,c,d){zb(a,b,{mode:c&4095|b.mode&-4096,ctime:Date.now(),Nc:d})}function Eb(a,b,c){if(I(b.mode))throw new C.ib(31);if(!C.isFile(b.mode))throw new C.ib(28);var d=pb(b,"w");if(d)throw new C.ib(d);zb(a,b,{size:c,timestamp:Date.now()})}function Fb(a,b){a="string"==typeof a?a:rb(a);for(b=b.split("/").reverse();b.length;){var c=b.pop();if(c){var d=La(a+"/"+c);try{C.mkdir(d)}catch(e){if(20!=e.Cb)throw e;}a=d}}return d}
+function Gb(a,b,c,d){a="string"==typeof a?a:rb(a);b=La(a+"/"+b);return C.create(b,eb(c,d))}function Hb(a){if(!(a.Gd||a.Hd||a.link||a.mb))if(globalThis.XMLHttpRequest)y("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");else try{a.mb=ja(a.url)}catch(b){throw new C.ib(29);}}
+function Ib(a,b,c,d,e){class f{yc=!1;Ab=[];ac=void 0;Uc=0;Tc=0;get(l){if(!(l>this.length-1||0>l)){var p=l%this.chunkSize;return this.ac(l/this.chunkSize|0)[p]}}Id(l){this.ac=l}Wc(){var l=new XMLHttpRequest;l.open("HEAD",c,!1);l.send(null);200<=l.status&&300>l.status||304===l.status||y("Couldn't load "+c+". Status: "+l.status);var p=Number(l.getResponseHeader("Content-length")),r,v=(r=l.getResponseHeader("Accept-Ranges"))&&"bytes"===r;l=(r=l.getResponseHeader("Content-Encoding"))&&"gzip"===r;var z=
+1048576;v||(z=p);var B=this;B.Id(F=>{var J=F*z,P=(F+1)*z-1;P=Math.min(P,p-1);if("undefined"==typeof B.Ab[F]){var K=B.Ab;J>P&&y("invalid range ("+J+", "+P+") or no bytes requested!");P>p-1&&y("only "+p+" bytes available! programmer error!");var G=new XMLHttpRequest;G.open("GET",c,!1);p!==z&&G.setRequestHeader("Range","bytes="+J+"-"+P);G.responseType="arraybuffer";G.overrideMimeType&&G.overrideMimeType("text/plain; charset=x-user-defined");G.send(null);200<=G.status&&300>G.status||304===G.status||y("Couldn't load "+
+c+". Status: "+G.status);J=void 0!==G.response?new Uint8Array(G.response||[]):Xa(G.responseText||"");K[F]=J}"undefined"==typeof B.Ab[F]&&y("doXHR failed!");return B.Ab[F]});if(l||!p)z=p=1,z=p=this.ac(0).length,la("LazyFiles on gzip forces download of the whole file when length is accessed");this.Uc=p;this.Tc=z;this.yc=!0}get length(){this.yc||this.Wc();return this.Uc}get chunkSize(){this.yc||this.Wc();return this.Tc}}if(globalThis.XMLHttpRequest){ba||y("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");
+var g=new f;var k=void 0}else k=c,g=void 0;var m=Gb(a,b,d,e);g?m.mb=g:k&&(m.mb=null,m.url=k);Object.defineProperties(m,{sb:{get:function(){return this.mb.length}}});a={};for(const [l,p]of Object.entries(m.lb))a[l]=(...r)=>{Hb(m);return p(...r)};a.read=(l,p,r,v,z)=>{Hb(m);l=l.node.mb;if(z>=l.length)p=0;else{v=Math.min(l.length-z,v);if(l.slice)for(var B=0;B<v;B++)p[r+B]=l[z+B];else for(B=0;B<v;B++)p[r+B]=l.get(z+B);p=v}return p};a.Vb=()=>{Hb(m);y();throw new C.ib(48);};m.lb=a;return m}
+var C={root:null,bc:[],Lc:{},streams:[],Cc:1,Kb:null,Ic:"/",uc:!1,Rc:!0,ud:null,qc:0,$c:{},ib:class{name="ErrnoError";constructor(a){this.Cb=a}},kd:class{Ab={};node=null;get object(){return this.node}set object(a){this.node=a}get flags(){return this.Ab.flags}set flags(a){this.Ab.flags=a}get position(){return this.Ab.position}set position(a){this.Ab.position=a}},jd:class{kb={};lb={};Fb=null;constructor(a,b,c,d){a||=this;this.parent=a;this.qb=a.qb;this.id=C.Cc++;this.name=b;this.mode=c;this.rdev=d;
+this.atime=this.mtime=this.ctime=Date.now()}get read(){return 365===(this.mode&365)}set read(a){a?this.mode|=365:this.mode&=-366}get write(){return 146===(this.mode&146)}set write(a){a?this.mode|=146:this.mode&=-147}get Hd(){return I(this.mode)}get Gd(){return 8192===(this.mode&61440)}},createNode(a,b,c,d){a=new C.jd(a,b,c,d);sb(a);return a},xc(a){return a===a.parent},isFile(a){return 32768===(a&61440)},isFIFO(a){return 4096===(a&61440)},isSocket(a){return 49152===(a&49152)},md:4096,yd:a=>C.streams[a],
+nd:{open(a){a.lb=C.wd(a.node.rdev).lb;a.lb.open?.(a)},yb(){throw new C.ib(70);}},Ac:a=>a>>8,oe:a=>a&255,Qb:(a,b)=>a<<8|b,wd:a=>C.Lc[a],cd(a,b){function c(k){C.qc--;return b(k)}function d(k){if(k){if(!d.rd)return d.rd=!0,c(k)}else++f>=e.length&&c(null)}"function"==typeof a&&(b=a,a=!1);C.qc++;1<C.qc&&n(`warning: ${C.qc} FS.syncfs operations in flight at once, probably just doing extra work`);var e=Ab(C.root.qb),f=0,g;for(g of e)g.type.cd?g.type.cd(g,a,d):d(null)},qb(a,b,c){var d="/"===c;if(d&&C.root)throw new C.ib(10);
+if(!d&&c){var e=M(c,{kc:!1});c=e.path;e=e.node;if(e.Fb)throw new C.ib(10);if(!I(e.mode))throw new C.ib(54);}b={type:a,Kd:b,Xc:c,bc:[]};a=a.qb(b);a.qb=b;b.root=a;d?C.root=a:e&&(e.Fb=b,e.qb&&e.qb.bc.push(b));return a},Be(a){a=M(a,{kc:!1});if(!a.node.Fb)throw new C.ib(28);a=a.node;var b=a.Fb,c=Ab(b);for([,e]of Object.entries(C.Kb))for(;e;){var d=e.Rb;c.includes(e.qb)&&db(e);var e=d}a.Fb=null;a.qb.bc.splice(a.qb.bc.indexOf(b),1)},lookup(a,b){return a.kb.lookup(a,b)},Jb(a,b,c){var d=M(a,{parent:!0}).node;
+a=Na(a);if(!a)throw new C.ib(28);if("."===a||".."===a)throw new C.ib(20);var e=ub(d,a);if(e)throw new C.ib(e);if(!d.kb.Jb)throw new C.ib(63);return d.kb.Jb(d,a,b,c)},bd(a){return Bb(M(a,{Db:!0}).node)},ze(a){return Bb(a.node)},create(a,b=438){return C.Jb(a,b&4095|32768,0)},mkdir(a,b=511){return C.Jb(a,b&1023|16384,0)},qe(a,b){var c=a.split("/"),d="",e;for(e of c)if(e){if(d||"/"===a.charAt(0))d+="/";d+=e;try{C.mkdir(d,b)}catch(f){if(20!=f.Cb)throw f;}}},symlink(a,b){if(!Ra(a))throw new C.ib(44);var c=
+M(b,{parent:!0}).node;if(!c)throw new C.ib(44);b=Na(b);var d=ub(c,b);if(d)throw new C.ib(d);if(!c.kb.symlink)throw new C.ib(63);return c.kb.symlink(c,b,a)},rename(a,b){var c=Ma(a),d=Ma(b),e=Na(a),f=Na(b);var g=M(a,{parent:!0});var k=g.node;g=M(b,{parent:!0});g=g.node;if(!k||!g)throw new C.ib(44);if(k.qb!==g.qb)throw new C.ib(75);var m=L(k,e);a=Sa(a,d);if("."!==a.charAt(0))throw new C.ib(28);a=Sa(b,c);if("."!==a.charAt(0))throw new C.ib(55);try{var l=L(g,f)}catch(p){}if(m!==l){b=I(m.mode);if(e=vb(k,
+e,b))throw new C.ib(e);if(e=l?vb(g,f,b):ub(g,f))throw new C.ib(e);if(!k.kb.rename)throw new C.ib(63);if(m.Fb||l&&l.Fb)throw new C.ib(10);if(g!==k&&(e=pb(k,"w")))throw new C.ib(e);db(m);try{k.kb.rename(m,g,f),m.parent=g}catch(p){throw p;}finally{sb(m)}}},rmdir(a){var b=M(a,{parent:!0}).node;a=Na(a);var c=L(b,a),d=vb(b,a,!0);if(d)throw new C.ib(d);if(!b.kb.rmdir)throw new C.ib(63);if(c.Fb)throw new C.ib(10);b.kb.rmdir(b,a);db(c)},readdir(a){a=M(a,{Db:!0}).node;return wb(a.kb.readdir,54)(a)},unlink(a){var b=
+M(a,{parent:!0}).node;if(!b)throw new C.ib(44);a=Na(a);var c=L(b,a),d=vb(b,a,!1);if(d)throw new C.ib(d);if(!b.kb.unlink)throw new C.ib(63);if(c.Fb)throw new C.ib(10);b.kb.unlink(b,a);db(c)},readlink(a){a=M(a).node;if(!a)throw new C.ib(44);if(!a.kb.readlink)throw new C.ib(28);return a.kb.readlink(a)},stat(a,b){a=M(a,{Db:!b}).node;return wb(a.kb.Eb,63)(a)},fstat(a){var b=N(a);a=b.node;var c=b.lb.Eb;b=c?b:a;c??=a.kb.Eb;wb(c,63);return c(b)},lstat(a){return C.stat(a,!0)},chmod(a,b,c){a="string"==typeof a?
+M(a,{Db:!c}).node:a;Db(null,a,b,c)},lchmod(a,b){C.chmod(a,b,!0)},fchmod(a,b){a=N(a);Db(a,a.node,b,!1)},chown(a,b,c,d){a="string"==typeof a?M(a,{Db:!d}).node:a;zb(null,a,{timestamp:Date.now(),Nc:d})},lchown(a,b,c){C.chown(a,b,c,!0)},fchown(a){a=N(a);zb(a,a.node,{timestamp:Date.now(),Nc:!1})},truncate(a,b){if(0>b)throw new C.ib(28);a="string"==typeof a?M(a,{Db:!0}).node:a;Eb(null,a,b)},le(a,b){a=N(a);if(0>b||0===(a.flags&2097155))throw new C.ib(28);Eb(a,a.node,b)},Ce(a,b,c){a=M(a,{Db:!0}).node;wb(a.kb.Gb,
+63)(a,{atime:b,mtime:c})},open(a,b,c=438){if(""===a)throw new C.ib(44);if("string"==typeof b){var d={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[b];if("undefined"==typeof d)throw Error(`Unknown file open mode: ${b}`);b=d}c=b&64?c&4095|32768:0;if("object"==typeof a)d=a;else{var e=a.endsWith("/");a=M(a,{Db:!(b&131072),Jd:!0});d=a.node;a=a.path}var f=!1;if(b&64)if(d){if(b&128)throw new C.ib(20);}else{if(e)throw new C.ib(31);d=C.Jb(a,c|511,0);f=!0}if(!d)throw new C.ib(44);8192===(d.mode&61440)&&(b&=-513);
+if(b&65536&&!I(d.mode))throw new C.ib(54);if(!f&&(e=d?40960===(d.mode&61440)?32:I(d.mode)&&("r"!==tb(b)||b&576)?31:pb(d,tb(b)):44))throw new C.ib(e);b&512&&!f&&C.truncate(d,0);b&=-131713;e=xb({node:d,path:rb(d),flags:b,seekable:!0,position:0,lb:d.lb,Sd:[],error:!1});e.lb.open&&e.lb.open(e);f&&C.chmod(d,c&511);!h.logReadFiles||b&1||a in C.$c||(C.$c[a]=1);return e},close(a){if(null===a.fd)throw new C.ib(8);a.tc&&(a.tc=null);try{a.lb.close&&a.lb.close(a)}catch(b){throw b;}finally{C.streams[a.fd]=null}a.fd=
+null},yb(a,b,c){if(null===a.fd)throw new C.ib(8);if(!a.seekable||!a.lb.yb)throw new C.ib(70);if(0!=c&&1!=c&&2!=c)throw new C.ib(28);a.position=a.lb.yb(a,b,c);a.Sd=[];return a.position},read(a,b,c,d,e){if(0>d||0>e)throw new C.ib(28);if(null===a.fd)throw new C.ib(8);if(1===(a.flags&2097155))throw new C.ib(8);if(I(a.node.mode))throw new C.ib(31);if(!a.lb.read)throw new C.ib(28);var f="undefined"!=typeof e;if(!f)e=a.position;else if(!a.seekable)throw new C.ib(70);b=a.lb.read(a,b,c,d,e);f||(a.position+=
+b);return b},write(a,b,c,d,e,f){if(0>d||0>e)throw new C.ib(28);if(null===a.fd)throw new C.ib(8);if(0===(a.flags&2097155))throw new C.ib(8);if(I(a.node.mode))throw new C.ib(31);if(!a.lb.write)throw new C.ib(28);a.seekable&&a.flags&1024&&C.yb(a,0,2);var g="undefined"!=typeof e;if(!g)e=a.position;else if(!a.seekable)throw new C.ib(70);b=a.lb.write(a,b,c,d,e,f);g||(a.position+=b);return b},Vb(a,b,c,d,e){if(0!==(d&2)&&0===(e&2)&&2!==(a.flags&2097155))throw new C.ib(2);if(1===(a.flags&2097155))throw new C.ib(2);
+if(!a.lb.Vb)throw new C.ib(43);if(!b)throw new C.ib(28);return a.lb.Vb(a,b,c,d,e)},cc(a,b,c,d,e){return a.lb.cc?a.lb.cc(a,b,c,d,e):0},vc(a,b,c){if(!a.lb.vc)throw new C.ib(59);return a.lb.vc(a,b,c)},readFile(a,b={}){b.flags=b.flags||0;b.encoding=b.encoding||"binary";"utf8"!==b.encoding&&"binary"!==b.encoding&&y(`Invalid encoding type "${b.encoding}"`);var c=C.open(a,b.flags);a=C.stat(a).size;var d=new Uint8Array(a);C.read(c,d,0,a,0);"utf8"===b.encoding&&(d=D(d));C.close(c);return d},writeFile(a,b,
+c={}){c.flags=c.flags||577;a=C.open(a,c.flags,c.mode);"string"==typeof b&&(b=new Uint8Array(Xa(b)));ArrayBuffer.isView(b)?C.write(a,b,0,b.byteLength,void 0,c.be):y("Unsupported data type");C.close(a)},cwd:()=>C.Ic,chdir(a){a=M(a,{Db:!0});if(null===a.node)throw new C.ib(44);if(!I(a.node.mode))throw new C.ib(54);var b=pb(a.node,"x");if(b)throw new C.ib(b);C.Ic=a.path},we(){C.uc=!1;for(var a of C.streams)a&&C.close(a)},ie(a,b){try{var c=M(a,{Db:!b});a=c.path}catch(f){}var d=!1,e=null;try{c=M(a,{parent:!0}),
+Na(a),c=M(a,{Db:!b}),d=!0,e=c.node}catch(f){}return d?e:null},Mb(a,b,c,d){a=Oa("string"==typeof a?a:rb(a),b);b=eb(!!c,!!d);var e;(e=C.Mb).Ac??(e.Ac=64);e=C.Qb(C.Mb.Ac++,0);$a(e,{open(f){f.seekable=!1},close(){d?.buffer?.length&&d(10)},read(f,g,k,m){for(var l=0,p=0;p<m;p++){try{var r=c()}catch(v){throw new C.ib(29);}if(void 0===r&&0===l)throw new C.ib(6);if(null===r||void 0===r)break;l++;g[k+p]=r}l&&(f.node.atime=Date.now());return l},write(f,g,k,m){for(var l=0;l<m;l++)try{d(g[k+l])}catch(p){throw new C.ib(29);
+}m&&(f.node.mtime=f.node.ctime=Date.now());return l}});return Cb(a,b,e)}},Ja=void 0,Jb={},Kb=a=>{for(;a.length;){var b=a.pop();a.pop()(b)}};function Lb(a){return this.pb(x[a>>2])}
var Mb={},Nb={},Ob={},Qb=class extends Error{constructor(a){super(a);this.name="InternalError"}},Rb=(a,b,c)=>{function d(k){k=c(k);if(k.length!==a.length)throw new Qb("Mismatched type converter count");for(var m=0;m<a.length;++m)O(a[m],k[m])}a.forEach(k=>Ob[k]=b);var e=Array(b.length),f=[],g=0;for(let [k,m]of b.entries())Nb.hasOwnProperty(m)?e[k]=Nb[m]:(f.push(m),Mb.hasOwnProperty(m)||(Mb[m]=[]),Mb[m].push(()=>{e[k]=Nb[m];++g;g===f.length&&d(e)}));0===f.length&&d(e)},Q=a=>{for(var b="";;){var c=t[a++];
-if(!c)return b;b+=String.fromCharCode(c)}},R=class extends Error{constructor(a){super(a);this.name="BindingError"}},Sb=a=>{throw new R(a);};function Tb(a,b,c={}){var d=b.name;if(!a)throw new R(`type "${d}" must have a positive integer typeid pointer`);if(Nb.hasOwnProperty(a)){if(c.zd)return;throw new R(`Cannot register type '${d}' twice`);}Nb[a]=b;delete Ob[a];Mb.hasOwnProperty(a)&&(b=Mb[a],delete Mb[a],b.forEach(e=>e()))}function O(a,b,c={}){return Tb(a,b,c)}
-var Ub=(a,b,c)=>{switch(b){case 1:return c?d=>q[d]:d=>t[d];case 2:return c?d=>u[d>>1]:d=>ra[d>>1];case 4:return c?d=>w[d>>2]:d=>x[d>>2];case 8:return c?d=>ua[d>>3]:d=>va[d>>3];default:throw new TypeError(`invalid integer width (${b}): ${a}`);}},Vb=a=>{throw new R(a.hb.pb.mb.name+" instance already deleted");},Wb=!1,Xb=()=>{},Yb=a=>{if(!globalThis.FinalizationRegistry)return Yb=b=>b,a;Wb=new FinalizationRegistry(b=>{b=b.hb;--b.count.value;0===b.count.value&&(b.ub?b.zb.Gb(b.ub):b.pb.mb.Gb(b.lb))});
-Yb=b=>{var c=b.hb;c.ub&&Wb.register(b,{hb:c},b);return b};Xb=b=>{Wb.unregister(b)};return Yb(a)},Zb=[];function $b(){}
-var ac=(a,b)=>Object.defineProperty(b,"name",{value:a}),bc={},cc=(a,b,c)=>{if(void 0===a[b].tb){var d=a[b];a[b]=function(...e){if(!a[b].tb.hasOwnProperty(e.length))throw new R(`Function '${c}' called with an invalid number of arguments (${e.length}) - expects one of (${a[b].tb})!`);return a[b].tb[e.length].apply(this,e)};a[b].tb=[];a[b].tb[d.Mb]=d}},dc=(a,b,c)=>{if(h.hasOwnProperty(a)){if(void 0===c||void 0!==h[a].tb&&void 0!==h[a].tb[c])throw new R(`Cannot register public name '${a}' twice`);cc(h,
-a,a);if(h[a].tb.hasOwnProperty(c))throw new R(`Cannot register multiple overloads of a function with the same number of arguments (${c})!`);h[a].tb[c]=b}else h[a]=b,h[a].Mb=c},ec=a=>{a=a.replace(/[^a-zA-Z0-9_]/g,"$");var b=a.charCodeAt(0);return 48<=b&&57>=b?`_${a}`:a};function fc(a,b,c,d,e,f,g,k){this.name=a;this.constructor=b;this.Sb=c;this.Gb=d;this.vb=e;this.td=f;this.ec=g;this.od=k;this.Kd=[]}
-var gc=(a,b,c)=>{for(;b!==c;){if(!b.ec)throw new R(`Expected null or instance of ${c.name}, got an instance of ${b.name}`);a=b.ec(a);b=b.vb}return a},hc=a=>{if(null===a)return"null";var b=typeof a;return"object"===b||"array"===b||"function"===b?a.toString():""+a};
-function ic(a,b){if(null===b){if(this.vc)throw new R(`null is not a valid ${this.name}`);return 0}if(!b.hb)throw new R(`Cannot pass "${hc(b)}" as a ${this.name}`);if(!b.hb.lb)throw new R(`Cannot pass deleted object as a pointer of type ${this.name}`);return gc(b.hb.lb,b.hb.pb.mb,this.mb)}
-function jc(a,b){if(null===b){if(this.vc)throw new R(`null is not a valid ${this.name}`);if(this.kc){var c=this.Cc();null!==a&&a.push(this.Gb,c);return c}return 0}if(!b||!b.hb)throw new R(`Cannot pass "${hc(b)}" as a ${this.name}`);if(!b.hb.lb)throw new R(`Cannot pass deleted object as a pointer of type ${this.name}`);if(!this.jc&&b.hb.pb.jc)throw new R(`Cannot convert argument of type ${b.hb.zb?b.hb.zb.name:b.hb.pb.name} to parameter type ${this.name}`);c=gc(b.hb.lb,b.hb.pb.mb,this.mb);if(this.kc){if(void 0===
-b.hb.ub)throw new R("Passing raw pointer to smart pointer is illegal");switch(this.Pd){case 0:if(b.hb.zb===this)c=b.hb.ub;else throw new R(`Cannot convert argument of type ${b.hb.zb?b.hb.zb.name:b.hb.pb.name} to parameter type ${this.name}`);break;case 1:c=b.hb.ub;break;case 2:if(b.hb.zb===this)c=b.hb.ub;else{var d=b.clone();c=this.Ld(c,kc(()=>d["delete"]()));null!==a&&a.push(this.Gb,c)}break;default:throw new R("Unsupported sharing policy");}}return c}
-function lc(a,b){if(null===b){if(this.vc)throw new R(`null is not a valid ${this.name}`);return 0}if(!b.hb)throw new R(`Cannot pass "${hc(b)}" as a ${this.name}`);if(!b.hb.lb)throw new R(`Cannot pass deleted object as a pointer of type ${this.name}`);if(b.hb.pb.jc)throw new R(`Cannot convert argument of type ${b.hb.pb.name} to parameter type ${this.name}`);return gc(b.hb.lb,b.hb.pb.mb,this.mb)}
-var mc=(a,b,c)=>{if(b===c)return a;if(void 0===c.vb)return null;a=mc(a,b,c.vb);return null===a?null:c.od(a)},nc={},oc=(a,b)=>{if(void 0===b)throw new R("ptr should not be undefined");for(;a.vb;)b=a.ec(b),a=a.vb;return nc[b]},pc=(a,b)=>{if(!b.pb||!b.lb)throw new Qb("makeClassHandle requires ptr and ptrType");if(!!b.zb!==!!b.ub)throw new Qb("Both smartPtrType and smartPtr must be specified");b.count={value:1};return Yb(Object.create(a,{hb:{value:b,writable:!0}}))};
-function qc(a,b,c,d,e,f,g,k,m,l,p){this.name=a;this.mb=b;this.vc=c;this.jc=d;this.kc=e;this.Jd=f;this.Pd=g;this.Xc=k;this.Cc=m;this.Ld=l;this.Gb=p;e||void 0!==b.vb?this.rb=jc:(this.rb=d?ic:lc,this.sb=null)}
-var rc=(a,b,c)=>{if(!h.hasOwnProperty(a))throw new Qb("Replacing nonexistent public symbol");void 0!==h[a].tb&&void 0!==c?h[a].tb[c]=b:(h[a]=b,h[a].Mb=c)},sc=[],tc=a=>{var b=sc[a];b||(sc[a]=b=S.get(a));return b},T=(a,b)=>{a=Q(a);var c=tc(b);if("function"!=typeof c)throw new R(`unknown function pointer with signature ${a}: ${b}`);return c};class uc extends Error{}
-var wc=a=>{a=vc(a);var b=Q(a);U(a);return b},xc=(a,b)=>{function c(f){e[f]||Nb[f]||(Ob[f]?Ob[f].forEach(c):(d.push(f),e[f]=!0))}var d=[],e={};b.forEach(c);throw new uc(`${a}: `+d.map(wc).join([", "]));},yc=(a,b)=>{for(var c=[],d=0;d<a;d++)c.push(x[b+4*d>>2]);return c};function zc(a){for(var b=1;b<a.length;++b)if(null!==a[b]&&void 0===a[b].sb)return!0;return!1}
-function Ac(a,b,c,d,e,f){var g=b.length;if(2>g)throw new R("argTypes array size mismatch! Must at least get return value and 'this' types!");var k=null!==b[1]&&null!==c,m=zc(b);c=!b[0].Rc;var l=b[0],p=b[1];d=[a,Sb,d,e,Kb,l.nb.bind(l),p?.rb.bind(p)];for(e=2;e<g;++e)l=b[e],d.push(l.rb.bind(l));if(!m)for(e=k?1:2;e<b.length;++e)null!==b[e].sb&&d.push(b[e].sb);m=zc(b);e=b.length-2;p=[];l=["fn"];k&&l.push("thisWired");for(g=0;g<e;++g)p.push(`arg${g}`),l.push(`arg${g}Wired`);p=p.join(",");l=l.join(",");
+if(!c)return b;b+=String.fromCharCode(c)}},R=class extends Error{constructor(a){super(a);this.name="BindingError"}},Sb=a=>{throw new R(a);};function Tb(a,b,c={}){var d=b.name;if(!a)throw new R(`type "${d}" must have a positive integer typeid pointer`);if(Nb.hasOwnProperty(a)){if(c.Bd)return;throw new R(`Cannot register type '${d}' twice`);}Nb[a]=b;delete Ob[a];Mb.hasOwnProperty(a)&&(b=Mb[a],delete Mb[a],b.forEach(e=>e()))}function O(a,b,c={}){return Tb(a,b,c)}
+var Ub=(a,b,c)=>{switch(b){case 1:return c?d=>q[d]:d=>t[d];case 2:return c?d=>u[d>>1]:d=>ra[d>>1];case 4:return c?d=>w[d>>2]:d=>x[d>>2];case 8:return c?d=>ua[d>>3]:d=>va[d>>3];default:throw new TypeError(`invalid integer width (${b}): ${a}`);}},Vb=a=>{throw new R(a.jb.rb.ob.name+" instance already deleted");},Wb=!1,Xb=()=>{},Yb=a=>{if(!globalThis.FinalizationRegistry)return Yb=b=>b,a;Wb=new FinalizationRegistry(b=>{b=b.jb;--b.count.value;0===b.count.value&&(b.wb?b.Bb.Ib(b.wb):b.rb.ob.Ib(b.nb))});
+Yb=b=>{var c=b.jb;c.wb&&Wb.register(b,{jb:c},b);return b};Xb=b=>{Wb.unregister(b)};return Yb(a)},Zb=[];function $b(){}
+var ac=(a,b)=>Object.defineProperty(b,"name",{value:a}),bc={},cc=(a,b,c)=>{if(void 0===a[b].vb){var d=a[b];a[b]=function(...e){if(!a[b].vb.hasOwnProperty(e.length))throw new R(`Function '${c}' called with an invalid number of arguments (${e.length}) - expects one of (${a[b].vb})!`);return a[b].vb[e.length].apply(this,e)};a[b].vb=[];a[b].vb[d.Ob]=d}},dc=(a,b,c)=>{if(h.hasOwnProperty(a)){if(void 0===c||void 0!==h[a].vb&&void 0!==h[a].vb[c])throw new R(`Cannot register public name '${a}' twice`);cc(h,
+a,a);if(h[a].vb.hasOwnProperty(c))throw new R(`Cannot register multiple overloads of a function with the same number of arguments (${c})!`);h[a].vb[c]=b}else h[a]=b,h[a].Ob=c},ec=a=>{a=a.replace(/[^a-zA-Z0-9_]/g,"$");var b=a.charCodeAt(0);return 48<=b&&57>=b?`_${a}`:a};function fc(a,b,c,d,e,f,g,k){this.name=a;this.constructor=b;this.Ub=c;this.Ib=d;this.xb=e;this.vd=f;this.hc=g;this.qd=k;this.Md=[]}
+var gc=(a,b,c)=>{for(;b!==c;){if(!b.hc)throw new R(`Expected null or instance of ${c.name}, got an instance of ${b.name}`);a=b.hc(a);b=b.xb}return a},hc=a=>{if(null===a)return"null";var b=typeof a;return"object"===b||"array"===b||"function"===b?a.toString():""+a};
+function ic(a,b){if(null===b){if(this.wc)throw new R(`null is not a valid ${this.name}`);return 0}if(!b.jb)throw new R(`Cannot pass "${hc(b)}" as a ${this.name}`);if(!b.jb.nb)throw new R(`Cannot pass deleted object as a pointer of type ${this.name}`);return gc(b.jb.nb,b.jb.rb.ob,this.ob)}
+function jc(a,b){if(null===b){if(this.wc)throw new R(`null is not a valid ${this.name}`);if(this.mc){var c=this.Ec();null!==a&&a.push(this.Ib,c);return c}return 0}if(!b||!b.jb)throw new R(`Cannot pass "${hc(b)}" as a ${this.name}`);if(!b.jb.nb)throw new R(`Cannot pass deleted object as a pointer of type ${this.name}`);if(!this.lc&&b.jb.rb.lc)throw new R(`Cannot convert argument of type ${b.jb.Bb?b.jb.Bb.name:b.jb.rb.name} to parameter type ${this.name}`);c=gc(b.jb.nb,b.jb.rb.ob,this.ob);if(this.mc){if(void 0===
+b.jb.wb)throw new R("Passing raw pointer to smart pointer is illegal");switch(this.Rd){case 0:if(b.jb.Bb===this)c=b.jb.wb;else throw new R(`Cannot convert argument of type ${b.jb.Bb?b.jb.Bb.name:b.jb.rb.name} to parameter type ${this.name}`);break;case 1:c=b.jb.wb;break;case 2:if(b.jb.Bb===this)c=b.jb.wb;else{var d=b.clone();c=this.Nd(c,kc(()=>d["delete"]()));null!==a&&a.push(this.Ib,c)}break;default:throw new R("Unsupported sharing policy");}}return c}
+function lc(a,b){if(null===b){if(this.wc)throw new R(`null is not a valid ${this.name}`);return 0}if(!b.jb)throw new R(`Cannot pass "${hc(b)}" as a ${this.name}`);if(!b.jb.nb)throw new R(`Cannot pass deleted object as a pointer of type ${this.name}`);if(b.jb.rb.lc)throw new R(`Cannot convert argument of type ${b.jb.rb.name} to parameter type ${this.name}`);return gc(b.jb.nb,b.jb.rb.ob,this.ob)}
+var mc=(a,b,c)=>{if(b===c)return a;if(void 0===c.xb)return null;a=mc(a,b,c.xb);return null===a?null:c.qd(a)},nc={},oc=(a,b)=>{if(void 0===b)throw new R("ptr should not be undefined");for(;a.xb;)b=a.hc(b),a=a.xb;return nc[b]},pc=(a,b)=>{if(!b.rb||!b.nb)throw new Qb("makeClassHandle requires ptr and ptrType");if(!!b.Bb!==!!b.wb)throw new Qb("Both smartPtrType and smartPtr must be specified");b.count={value:1};return Yb(Object.create(a,{jb:{value:b,writable:!0}}))};
+function qc(a,b,c,d,e,f,g,k,m,l,p){this.name=a;this.ob=b;this.wc=c;this.lc=d;this.mc=e;this.Ld=f;this.Rd=g;this.Zc=k;this.Ec=m;this.Nd=l;this.Ib=p;e||void 0!==b.xb?this.tb=jc:(this.tb=d?ic:lc,this.ub=null)}
+var rc=(a,b,c)=>{if(!h.hasOwnProperty(a))throw new Qb("Replacing nonexistent public symbol");void 0!==h[a].vb&&void 0!==c?h[a].vb[c]=b:(h[a]=b,h[a].Ob=c)},sc=[],tc=a=>{var b=sc[a];b||(sc[a]=b=S.get(a));return b},T=(a,b)=>{a=Q(a);var c=tc(b);if("function"!=typeof c)throw new R(`unknown function pointer with signature ${a}: ${b}`);return c};class uc extends Error{}
+var wc=a=>{a=vc(a);var b=Q(a);U(a);return b},xc=(a,b)=>{function c(f){e[f]||Nb[f]||(Ob[f]?Ob[f].forEach(c):(d.push(f),e[f]=!0))}var d=[],e={};b.forEach(c);throw new uc(`${a}: `+d.map(wc).join([", "]));},yc=(a,b)=>{for(var c=[],d=0;d<a;d++)c.push(x[b+4*d>>2]);return c};function zc(a){for(var b=1;b<a.length;++b)if(null!==a[b]&&void 0===a[b].ub)return!0;return!1}
+function Ac(a,b,c,d,e,f){var g=b.length;if(2>g)throw new R("argTypes array size mismatch! Must at least get return value and 'this' types!");var k=null!==b[1]&&null!==c,m=zc(b);c=!b[0].Sc;var l=b[0],p=b[1];d=[a,Sb,d,e,Kb,l.pb.bind(l),p?.tb.bind(p)];for(e=2;e<g;++e)l=b[e],d.push(l.tb.bind(l));if(!m)for(e=k?1:2;e<b.length;++e)null!==b[e].ub&&d.push(b[e].ub);m=zc(b);e=b.length-2;p=[];l=["fn"];k&&l.push("thisWired");for(g=0;g<e;++g)p.push(`arg${g}`),l.push(`arg${g}Wired`);p=p.join(",");l=l.join(",");
p=`return function (${p}) {\n`;m&&(p+="var destructors = [];\n");var r=m?"destructors":"null",v="humanName throwBindingError invoker fn runDestructors fromRetWire toClassParamWire".split(" ");k&&(p+=`var thisWired = toClassParamWire(${r}, this);\n`);for(g=0;g<e;++g){var z=`toArg${g}Wire`;p+=`var arg${g}Wired = ${z}(${r}, arg${g});\n`;v.push(z)}p+=(c||f?"var rv = ":"")+`invoker(${l});\n`;if(m)p+="runDestructors(destructors);\n";else for(g=k?1:2;g<b.length;++g)f=1===g?"thisWired":"arg"+(g-2)+"Wired",
-null!==b[g].sb&&(p+=`${f}_dtor(${f});\n`,v.push(`${f}_dtor`));c&&(p+="var ret = fromRetWire(rv);\nreturn ret;\n");b=(new Function(v,p+"}\n"))(...d);return ac(a,b)}
-var Bc=a=>{a=a.trim();const b=a.indexOf("(");return-1===b?a:a.slice(0,b)},Cc=[],Dc=[0,1,,1,null,1,!0,1,!1,1],Ec=a=>{9<a&&0===--Dc[a+1]&&(Dc[a]=void 0,Cc.push(a))},Fc=a=>{if(!a)throw new R(`Cannot use deleted val. handle = ${a}`);return Dc[a]},kc=a=>{switch(a){case void 0:return 2;case null:return 4;case !0:return 6;case !1:return 8;default:const b=Cc.pop()||Dc.length;Dc[b]=a;Dc[b+1]=1;return b}},Gc={name:"emscripten::val",nb:a=>{var b=Fc(a);Ec(a);return b},rb:(a,b)=>kc(b),xb:Lb,sb:null},Hc=(a,b,c)=>
-{switch(b){case 1:return c?function(d){return this.nb(q[d])}:function(d){return this.nb(t[d])};case 2:return c?function(d){return this.nb(u[d>>1])}:function(d){return this.nb(ra[d>>1])};case 4:return c?function(d){return this.nb(w[d>>2])}:function(d){return this.nb(x[d>>2])};default:throw new TypeError(`invalid integer width (${b}): ${a}`);}},Ic=(a,b)=>{var c=Nb[a];if(void 0===c)throw a=`${b} has unknown type ${wc(a)}`,new R(a);return c},Jc=(a,b)=>{switch(b){case 4:return function(c){return this.nb(sa[c>>
-2])};case 8:return function(c){return this.nb(ta[c>>3])};default:throw new TypeError(`invalid float width (${b}): ${a}`);}},Kc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Lc=(a,b,c)=>{a>>=1;b=Ua(ra,a,b/2,c);if(16<b-a&&Kc)return Kc.decode(ra.subarray(a,b));for(c="";a<b;++a)c+=String.fromCharCode(ra[a]);return c},Mc=(a,b,c)=>{c??=2147483647;if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var e=0;e<c;++e)u[b>>1]=a.charCodeAt(e),b+=2;u[b>>1]=0;return b-d},Nc=a=>2*a.length,Oc=
+null!==b[g].ub&&(p+=`${f}_dtor(${f});\n`,v.push(`${f}_dtor`));c&&(p+="var ret = fromRetWire(rv);\nreturn ret;\n");b=(new Function(v,p+"}\n"))(...d);return ac(a,b)}
+var Bc=a=>{a=a.trim();const b=a.indexOf("(");return-1===b?a:a.slice(0,b)},Cc=[],Dc=[0,1,,1,null,1,!0,1,!1,1],Ec=a=>{9<a&&0===--Dc[a+1]&&(Dc[a]=void 0,Cc.push(a))},Fc=a=>{if(!a)throw new R(`Cannot use deleted val. handle = ${a}`);return Dc[a]},kc=a=>{switch(a){case void 0:return 2;case null:return 4;case !0:return 6;case !1:return 8;default:const b=Cc.pop()||Dc.length;Dc[b]=a;Dc[b+1]=1;return b}},Gc={name:"emscripten::val",pb:a=>{var b=Fc(a);Ec(a);return b},tb:(a,b)=>kc(b),zb:Lb,ub:null},Hc=(a,b,c)=>
+{switch(b){case 1:return c?function(d){return this.pb(q[d])}:function(d){return this.pb(t[d])};case 2:return c?function(d){return this.pb(u[d>>1])}:function(d){return this.pb(ra[d>>1])};case 4:return c?function(d){return this.pb(w[d>>2])}:function(d){return this.pb(x[d>>2])};default:throw new TypeError(`invalid integer width (${b}): ${a}`);}},Ic=(a,b)=>{var c=Nb[a];if(void 0===c)throw a=`${b} has unknown type ${wc(a)}`,new R(a);return c},Jc=(a,b)=>{switch(b){case 4:return function(c){return this.pb(sa[c>>
+2])};case 8:return function(c){return this.pb(ta[c>>3])};default:throw new TypeError(`invalid float width (${b}): ${a}`);}},Kc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,Lc=(a,b,c)=>{a>>=1;b=Ua(ra,a,b/2,c);if(16<b-a&&Kc)return Kc.decode(ra.subarray(a,b));for(c="";a<b;++a)c+=String.fromCharCode(ra[a]);return c},Mc=(a,b,c)=>{c??=2147483647;if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var e=0;e<c;++e)u[b>>1]=a.charCodeAt(e),b+=2;u[b>>1]=0;return b-d},Nc=a=>2*a.length,Oc=
(a,b,c)=>{var d="";a>>=2;for(var e=0;!(e>=b/4);e++){var f=x[a+e];if(!f&&!c)break;d+=String.fromCodePoint(f)}return d},Pc=(a,b,c)=>{c??=2147483647;if(4>c)return 0;var d=b;c=d+c-4;for(var e=0;e<a.length;++e){var f=a.codePointAt(e);65535<f&&e++;w[b>>2]=f;b+=4;if(b+4>c)break}w[b>>2]=0;return b-d},Qc=a=>{for(var b=0,c=0;c<a.length;++c)65535<a.codePointAt(c)&&c++,b+=4;return b},Rc=0,Sc=[],Tc=a=>{var b=Sc.length;Sc.push(a);return b},Uc=(a,b)=>{for(var c=Array(a),d=0;d<a;++d)c[d]=Ic(x[b+4*d>>2],`parameter ${d}`);
-return c},Vc=(a,b,c)=>{var d=[];a=a(d,c);d.length&&(x[b>>2]=kc(d));return a},Wc={},Xc=a=>{var b=Wc[a];return void 0===b?Q(a):b},Zc={},$c=a=>{oa=a;Ia||0<Rc||(h.onExit?.(a),na=!0);ea(a,new Da(a))},ad=a=>{if(!na)try{a()}catch(b){b instanceof Da||"unwind"==b||ea(1,b)}finally{if(!(Ia||0<Rc))try{oa=a=oa,$c(a)}catch(b){b instanceof Da||"unwind"==b||ea(1,b)}}},V,bd=a=>{var b=a.getExtension("ANGLE_instanced_arrays");b&&(a.vertexAttribDivisor=(c,d)=>b.vertexAttribDivisorANGLE(c,d),a.drawArraysInstanced=(c,
+return c},Vc=(a,b,c)=>{var d=[];a=a(d,c);d.length&&(x[b>>2]=kc(d));return a},Wc={},Xc=a=>{var b=Wc[a];return void 0===b?Q(a):b},Yc={},$c=a=>{oa=a;Ia||0<Rc||(h.onExit?.(a),na=!0);ea(a,new Da(a))},ad=a=>{if(!na)try{a()}catch(b){b instanceof Da||"unwind"==b||ea(1,b)}finally{if(!(Ia||0<Rc))try{oa=a=oa,$c(a)}catch(b){b instanceof Da||"unwind"==b||ea(1,b)}}},V,bd=a=>{var b=a.getExtension("ANGLE_instanced_arrays");b&&(a.vertexAttribDivisor=(c,d)=>b.vertexAttribDivisorANGLE(c,d),a.drawArraysInstanced=(c,
d,e,f)=>b.drawArraysInstancedANGLE(c,d,e,f),a.drawElementsInstanced=(c,d,e,f,g)=>b.drawElementsInstancedANGLE(c,d,e,f,g))},cd=a=>{var b=a.getExtension("OES_vertex_array_object");b&&(a.createVertexArray=()=>b.createVertexArrayOES(),a.deleteVertexArray=c=>b.deleteVertexArrayOES(c),a.bindVertexArray=c=>b.bindVertexArrayOES(c),a.isVertexArray=c=>b.isVertexArrayOES(c))},dd=a=>{var b=a.getExtension("WEBGL_draw_buffers");b&&(a.drawBuffers=(c,d)=>b.drawBuffersWEBGL(c,d))},ed=a=>{var b="ANGLE_instanced_arrays EXT_blend_minmax EXT_disjoint_timer_query EXT_frag_depth EXT_shader_texture_lod EXT_sRGB OES_element_index_uint OES_fbo_render_mipmap OES_standard_derivatives OES_texture_float OES_texture_half_float OES_texture_half_float_linear OES_vertex_array_object WEBGL_color_buffer_float WEBGL_depth_texture WEBGL_draw_buffers EXT_color_buffer_float EXT_conservative_depth EXT_disjoint_timer_query_webgl2 EXT_texture_norm16 NV_shader_noperspective_interpolation WEBGL_clip_cull_distance EXT_clip_control EXT_color_buffer_half_float EXT_depth_clamp EXT_float_blend EXT_polygon_offset_clamp EXT_texture_compression_bptc EXT_texture_compression_rgtc EXT_texture_filter_anisotropic KHR_parallel_shader_compile OES_texture_float_linear WEBGL_blend_func_extended WEBGL_compressed_texture_astc WEBGL_compressed_texture_etc WEBGL_compressed_texture_etc1 WEBGL_compressed_texture_s3tc WEBGL_compressed_texture_s3tc_srgb WEBGL_debug_renderer_info WEBGL_debug_shaders WEBGL_lose_context WEBGL_multi_draw WEBGL_polygon_mode".split(" ");
-return(a.getSupportedExtensions()||[]).filter(c=>b.includes(c))},fd=1,gd=[],W=[],hd=[],jd=[],X=[],kd=[],ld=[],md=[1,1,2,2,4,4,4,2,3,4,8],nd={},od=4,pd=0,qd=a=>{for(var b=fd++,c=a.length;c<b;c++)a[c]=null;for(;a[b];)b=fd++;return b},rd=(a,b,c,d)=>{for(var e=0;e<a;e++){var f=V[c](),g=f&&qd(d);f?(f.name=g,d[g]=f):Y||=1282;w[b+4*e>>2]=g}},sd=a=>{a=32-Math.clz32(0===a?0:a-1);var b=Z.Ub[a];if(b)return b;b=V.getParameter(34965);Z.Ub[a]=V.createBuffer();V.bindBuffer(34963,Z.Ub[a]);V.bufferData(34963,1<<a,
-35048);V.bindBuffer(34963,b);return Z.Ub[a]},ud=a=>{td=!1;for(var b=0;b<Z.zc;++b){var c=Z.Rb[b];if(c.fc&&c.enabled){td=!0;var d=c.size;var e=c.type,f=c.stride;d=0<f?a*f:d*md[e-5120]*a;e=32-Math.clz32(0===d?0:d-1);f=Z.Vb[e];var g=Z.Lb[e];Z.Lb[e]=Z.Lb[e]+1&63;var k=f[g];k?e=k:(k=V.getParameter(34964),f[g]=V.createBuffer(),V.bindBuffer(34962,f[g]),V.bufferData(34962,1<<e,35048),V.bindBuffer(34962,k),e=f[g]);V.bindBuffer(34962,e);V.bufferSubData(34962,0,t.subarray(c.lb,c.lb+d));c.ed.call(V,b,c.size,c.type,
-c.Wc,c.stride,0)}}},wd=(a,b)=>{a.yb||(a.yb=a.getContext,a.getContext=function(d,e){e=a.yb(d,e);return"webgl"==d==e instanceof WebGLRenderingContext?e:null});var c=1<b.Uc?a.getContext("webgl2",b):a.getContext("webgl",b);return c?vd(c,b):0},vd=(a,b)=>{var c=qd(ld),d={handle:c,attributes:b,version:b.Uc,Qb:a};a.canvas&&(a.canvas.jd=d);ld[c]=d;if("undefined"==typeof b.Mc||b.Mc)if((a=d)||(a=Z),!a.Ad){a.Ad=!0;b=a.Qb;b.pe=b.getExtension("WEBGL_multi_draw");b.ee=b.getExtension("EXT_polygon_offset_clamp");
-b.de=b.getExtension("EXT_clip_control");b.Be=b.getExtension("WEBGL_polygon_mode");bd(b);cd(b);dd(b);b.be=b.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");b.le=b.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");2<=a.version&&(b.Kc=b.getExtension("EXT_disjoint_timer_query_webgl2"));if(2>a.version||!b.Kc)b.Kc=b.getExtension("EXT_disjoint_timer_query");for(var e of ed(b))e.includes("lose_context")||e.includes("debug")||b.getExtension(e)}d.zc=d.Qb.getParameter(34921);
-d.Rb=[];for(e=0;e<d.zc;e++)d.Rb[e]={enabled:!1,fc:!1,size:0,type:0,Wc:0,stride:0,lb:0,ed:null};d.Lb=[];d.pc=[];d.Lb.length=d.pc.length=22;d.Vb=[];d.cc=[];d.Vb.length=d.cc.length=22;d.Ub=[];d.Ub.length=22;for(e=0;21>=e;++e){d.Ub[e]=null;d.Lb[e]=d.pc[e]=0;d.Vb[e]=[];d.cc[e]=[];a=d.Vb[e];b=d.cc[e];a.length=b.length=64;for(var f=0;64>f;++f)a[f]=b[f]=null}return c},Y,Z,td,xd=["default","low-power","high-performance"],yd=[0,globalThis.document??0,globalThis.window??0],zd={},Bd=()=>{if(!Ad){var a={USER:"web_user",
+return(a.getSupportedExtensions()||[]).filter(c=>b.includes(c))},fd=1,gd=[],W=[],hd=[],jd=[],X=[],kd=[],ld=[],md=[1,1,2,2,4,4,4,2,3,4,8],nd={},od=4,pd=0,qd=a=>{for(var b=fd++,c=a.length;c<b;c++)a[c]=null;for(;a[b];)b=fd++;return b},rd=(a,b,c,d)=>{for(var e=0;e<a;e++){var f=V[c](),g=f&&qd(d);f?(f.name=g,d[g]=f):Y||=1282;w[b+4*e>>2]=g}},sd=a=>{a=32-Math.clz32(0===a?0:a-1);var b=Z.Wb[a];if(b)return b;b=V.getParameter(34965);Z.Wb[a]=V.createBuffer();V.bindBuffer(34963,Z.Wb[a]);V.bufferData(34963,1<<a,
+35048);V.bindBuffer(34963,b);return Z.Wb[a]},ud=a=>{td=!1;for(var b=0;b<Z.Bc;++b){var c=Z.Tb[b];if(c.ic&&c.enabled){td=!0;var d=c.size;var e=c.type,f=c.stride;d=0<f?a*f:d*md[e-5120]*a;e=32-Math.clz32(0===d?0:d-1);f=Z.Xb[e];var g=Z.Nb[e];Z.Nb[e]=Z.Nb[e]+1&63;var k=f[g];k?e=k:(k=V.getParameter(34964),f[g]=V.createBuffer(),V.bindBuffer(34962,f[g]),V.bufferData(34962,1<<e,35048),V.bindBuffer(34962,k),e=f[g]);V.bindBuffer(34962,e);V.bufferSubData(34962,0,t.subarray(c.nb,c.nb+d));c.hd.call(V,b,c.size,c.type,
+c.Yc,c.stride,0)}}},wd=(a,b)=>{a.Ab||(a.Ab=a.getContext,a.getContext=function(d,e){e=a.Ab(d,e);return"webgl"==d==e instanceof WebGLRenderingContext?e:null});var c=1<b.Vc?a.getContext("webgl2",b):a.getContext("webgl",b);return c?vd(c,b):0},vd=(a,b)=>{var c=qd(ld),d={handle:c,attributes:b,version:b.Vc,Sb:a};a.canvas&&(a.canvas.ld=d);ld[c]=d;if("undefined"==typeof b.Oc||b.Oc)if((a=d)||(a=Z),!a.Cd){a.Cd=!0;b=a.Sb;b.re=b.getExtension("WEBGL_multi_draw");b.ge=b.getExtension("EXT_polygon_offset_clamp");
+b.fe=b.getExtension("EXT_clip_control");b.De=b.getExtension("WEBGL_polygon_mode");bd(b);cd(b);dd(b);b.de=b.getExtension("WEBGL_draw_instanced_base_vertex_base_instance");b.ne=b.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance");2<=a.version&&(b.Mc=b.getExtension("EXT_disjoint_timer_query_webgl2"));if(2>a.version||!b.Mc)b.Mc=b.getExtension("EXT_disjoint_timer_query");for(var e of ed(b))e.includes("lose_context")||e.includes("debug")||b.getExtension(e)}d.Bc=d.Sb.getParameter(34921);
+d.Tb=[];for(e=0;e<d.Bc;e++)d.Tb[e]={enabled:!1,ic:!1,size:0,type:0,Yc:0,stride:0,nb:0,hd:null};d.Nb=[];d.rc=[];d.Nb.length=d.rc.length=22;d.Xb=[];d.ec=[];d.Xb.length=d.ec.length=22;d.Wb=[];d.Wb.length=22;for(e=0;21>=e;++e){d.Wb[e]=null;d.Nb[e]=d.rc[e]=0;d.Xb[e]=[];d.ec[e]=[];a=d.Xb[e];b=d.ec[e];a.length=b.length=64;for(var f=0;64>f;++f)a[f]=b[f]=null}return c},Y,Z,td,xd=["default","low-power","high-performance"],yd=[0,globalThis.document??0,globalThis.window??0],zd={},Bd=()=>{if(!Ad){var a={USER:"web_user",
LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:da||"./this.program"},b;for(b in zd)void 0===zd[b]?delete a[b]:a[b]=zd[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);Ad=c}return Ad},Ad,Cd=()=>{var a=ed(V);return a=a.concat(a.map(b=>"GL_"+b))},Dd=(a,b)=>{if(b){var c=void 0;switch(a){case 36346:c=1;break;case 36344:return;case 34814:case 36345:c=0;break;case 34466:var d=V.getParameter(34467);c=d?d.length:0;break;case 33309:if(2>
Z.version){Y||=1282;return}c=Cd().length;break;case 33307:case 33308:if(2>Z.version){Y||=1280;return}c=33307==a?3:0}if(void 0===c)switch(d=V.getParameter(a),typeof d){case "number":c=d;break;case "boolean":c=d?1:0;break;case "string":Y||=1280;return;case "object":if(null===d)switch(a){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:c=0;break;
default:Y||=1280;return}else{if(d instanceof Float32Array||d instanceof Uint32Array||d instanceof Int32Array||d instanceof Array){for(a=0;a<d.length;++a)w[b+4*a>>2]=d[a];return}try{c=d.name|0}catch(e){Y||=1280;n(`GL_INVALID_ENUM in glGet${0}v: Unknown object returned from WebGL getParameter(${a})! (error: ${e})`);return}}break;default:Y||=1280;n(`GL_INVALID_ENUM in glGet${0}v: Native code calling glGet${0}v(${a}) and it returns ${d} of type ${typeof d}!`);return}w[b>>2]=c}else Y||=1281},Fd=a=>{var b=
-Wa(a)+1,c=Ed(b);c&&E(a,t,c,b);return c},Gd=a=>"]"==a.slice(-1)&&a.lastIndexOf("["),Hd=a=>{a-=5120;return 0==a?q:1==a?t:2==a?u:4==a?w:6==a?sa:5==a||28922==a||28520==a||30779==a||30782==a?x:ra},Id=(a,b,c,d,e)=>{a=Hd(a);b=d*((pd||c)*({5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4}[b-6402]||1)*a.BYTES_PER_ELEMENT+od-1&-od);return a.subarray(e>>>31-Math.clz32(a.BYTES_PER_ELEMENT),e+b>>>31-Math.clz32(a.BYTES_PER_ELEMENT))},Jd=a=>{var b=V.nd;if(b){var c=b.dc[a];"number"==typeof c&&(b.dc[a]=
-c=V.getUniformLocation(b,b.bd[a]+(0<c?`[${c}]`:"")));return c}Y||=1282},Kd=[],Od=(a,b,c,d)=>{var e={string:l=>{var p=0;if(null!==l&&void 0!==l&&0!==l){p=Wa(l)+1;var r=Ld(p);E(l,t,r,p);p=r}return p},array:l=>{var p=Ld(l.length);q.set(l,p);return p}};a=h["_"+a];var f=[],g=0;if(d)for(var k=0;k<d.length;k++){var m=e[c[k]];m?(0===g&&(g=Md()),f[k]=m(d[k])):f[k]=d[k]}c=a(...f);return c=function(l){0!==g&&Nd(g);return"string"===b?l?D(t,l):"":"boolean"===b?!!l:l}(c)},Pd,Qd=[],Rd=a=>{const b=a.length;return[b%
-128|128,b>>7,...a]},Sd={i:127,p:127,j:126,f:125,d:124,e:111},Td=a=>Rd(Array.from(a,b=>Sd[b]));C.ae=(a,b,c,d,e,f,g,k,m,l)=>{ob(a,b,c,d,e,k,m,l).then(f).catch(g)};C.se=ob;C.Ib=Array(4096);C.ob(H,{},"/");C.mkdir("/tmp");C.mkdir("/home");C.mkdir("/home/web_user");
-(function(){C.mkdir("/dev");$a(C.Ob(1,3),{read:()=>0,write:(d,e,f,g)=>g,wb:()=>0});Cb("/dev/null",C.Ob(1,3));Za(C.Ob(5,0),bb);Za(C.Ob(6,0),cb);Cb("/dev/tty",C.Ob(5,0));Cb("/dev/tty1",C.Ob(6,0));var a=new Uint8Array(1024),b=0,c=()=>{0===b&&(Qa(a),b=a.byteLength);return a[--b]};C.Kb("/dev","random",c);C.Kb("/dev","urandom",c);C.mkdir("/dev/shm");C.mkdir("/dev/shm/tmp")})();
-(function(){C.mkdir("/proc");var a=C.mkdir("/proc/self");C.mkdir("/proc/self/fd");C.ob({ob(){var b=C.createNode(a,"fd",16895,73);b.jb={wb:H.jb.wb};b.ib={lookup(c,d){c=+d;var e=N(c);c={parent:null,ob:{Vc:"fake"},ib:{readlink:()=>e.path},id:c+1};return c.parent=c},readdir(){return Array.from(C.streams.entries()).filter(([,c])=>c).map(([c])=>c.toString())}};return b}},{},"/proc/self/fd")})();C.sd={MEMFS:H};
-(()=>{let a=$b.prototype;Object.assign(a,{isAliasOf:function(c){if(!(this instanceof $b&&c instanceof $b))return!1;var d=this.hb.pb.mb,e=this.hb.lb;c.hb=c.hb;var f=c.hb.pb.mb;for(c=c.hb.lb;d.vb;)e=d.ec(e),d=d.vb;for(;f.vb;)c=f.ec(c),f=f.vb;return d===f&&e===c},clone:function(){this.hb.lb||Vb(this);if(this.hb.bc)return this.hb.count.value+=1,this;var c=Yb,d=Object,e=d.create,f=Object.getPrototypeOf(this),g=this.hb;c=c(e.call(d,f,{hb:{value:{count:g.count,Yb:g.Yb,bc:g.bc,lb:g.lb,pb:g.pb,ub:g.ub,zb:g.zb}}}));
-c.hb.count.value+=1;c.hb.Yb=!1;return c},["delete"](){this.hb.lb||Vb(this);if(this.hb.Yb&&!this.hb.bc)throw new R("Object already scheduled for deletion");Xb(this);var c=this.hb;--c.count.value;0===c.count.value&&(c.ub?c.zb.Gb(c.ub):c.pb.mb.Gb(c.lb));this.hb.bc||(this.hb.ub=void 0,this.hb.lb=void 0)},isDeleted:function(){return!this.hb.lb},deleteLater:function(){this.hb.lb||Vb(this);if(this.hb.Yb&&!this.hb.bc)throw new R("Object already scheduled for deletion");Zb.push(this);this.hb.Yb=!0;return this}});
+Wa(a)+1,c=Ed(b);c&&E(a,t,c,b);return c},Gd=a=>"]"==a.slice(-1)&&a.lastIndexOf("["),Hd=a=>{a-=5120;return 0==a?q:1==a?t:2==a?u:4==a?w:6==a?sa:5==a||28922==a||28520==a||30779==a||30782==a?x:ra},Id=(a,b,c,d,e)=>{a=Hd(a);b=d*((pd||c)*({5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4}[b-6402]||1)*a.BYTES_PER_ELEMENT+od-1&-od);return a.subarray(e>>>31-Math.clz32(a.BYTES_PER_ELEMENT),e+b>>>31-Math.clz32(a.BYTES_PER_ELEMENT))},Jd=a=>{var b=V.pd;if(b){var c=b.fc[a];"number"==typeof c&&(b.fc[a]=
+c=V.getUniformLocation(b,b.dd[a]+(0<c?`[${c}]`:"")));return c}Y||=1282},Kd=[],Od=(a,b,c,d)=>{var e={string:l=>{var p=0;if(null!==l&&void 0!==l&&0!==l){p=Wa(l)+1;var r=Ld(p);E(l,t,r,p);p=r}return p},array:l=>{var p=Ld(l.length);q.set(l,p);return p}};a=h["_"+a];var f=[],g=0;if(d)for(var k=0;k<d.length;k++){var m=e[c[k]];m?(0===g&&(g=Md()),f[k]=m(d[k])):f[k]=d[k]}c=a(...f);return c=function(l){0!==g&&Nd(g);return"string"===b?l?D(t,l):"":"boolean"===b?!!l:l}(c)},Pd,Qd=[],Rd=a=>{const b=a.length;return[b%
+128|128,b>>7,...a]},Sd={i:127,p:127,j:126,f:125,d:124,e:111},Td=a=>Rd(Array.from(a,b=>Sd[b]));C.ce=(a,b,c,d,e,f,g,k,m,l)=>{ob(a,b,c,d,e,k,m,l).then(f).catch(g)};C.ue=ob;C.Kb=Array(4096);C.qb(H,{},"/");C.mkdir("/tmp");C.mkdir("/home");C.mkdir("/home/web_user");
+(function(){C.mkdir("/dev");$a(C.Qb(1,3),{read:()=>0,write:(d,e,f,g)=>g,yb:()=>0});Cb("/dev/null",C.Qb(1,3));Za(C.Qb(5,0),bb);Za(C.Qb(6,0),cb);Cb("/dev/tty",C.Qb(5,0));Cb("/dev/tty1",C.Qb(6,0));var a=new Uint8Array(1024),b=0,c=()=>{0===b&&(Qa(a),b=a.byteLength);return a[--b]};C.Mb("/dev","random",c);C.Mb("/dev","urandom",c);C.mkdir("/dev/shm");C.mkdir("/dev/shm/tmp")})();
+(function(){C.mkdir("/proc");var a=C.mkdir("/proc/self");C.mkdir("/proc/self/fd");C.qb({qb(){var b=C.createNode(a,"fd",16895,73);b.lb={yb:H.lb.yb};b.kb={lookup(c,d){c=+d;var e=N(c);c={parent:null,qb:{Xc:"fake"},kb:{readlink:()=>e.path},id:c+1};return c.parent=c},readdir(){return Array.from(C.streams.entries()).filter(([,c])=>c).map(([c])=>c.toString())}};return b}},{},"/proc/self/fd")})();C.ud={MEMFS:H};
+(()=>{let a=$b.prototype;Object.assign(a,{isAliasOf:function(c){if(!(this instanceof $b&&c instanceof $b))return!1;var d=this.jb.rb.ob,e=this.jb.nb;c.jb=c.jb;var f=c.jb.rb.ob;for(c=c.jb.nb;d.xb;)e=d.hc(e),d=d.xb;for(;f.xb;)c=f.hc(c),f=f.xb;return d===f&&e===c},clone:function(){this.jb.nb||Vb(this);if(this.jb.dc)return this.jb.count.value+=1,this;var c=Yb,d=Object,e=d.create,f=Object.getPrototypeOf(this),g=this.jb;c=c(e.call(d,f,{jb:{value:{count:g.count,$b:g.$b,dc:g.dc,nb:g.nb,rb:g.rb,wb:g.wb,Bb:g.Bb}}}));
+c.jb.count.value+=1;c.jb.$b=!1;return c},["delete"](){this.jb.nb||Vb(this);if(this.jb.$b&&!this.jb.dc)throw new R("Object already scheduled for deletion");Xb(this);var c=this.jb;--c.count.value;0===c.count.value&&(c.wb?c.Bb.Ib(c.wb):c.rb.ob.Ib(c.nb));this.jb.dc||(this.jb.wb=void 0,this.jb.nb=void 0)},isDeleted:function(){return!this.jb.nb},deleteLater:function(){this.jb.nb||Vb(this);if(this.jb.$b&&!this.jb.dc)throw new R("Object already scheduled for deletion");Zb.push(this);this.jb.$b=!0;return this}});
const b=Symbol.dispose;b&&(a[b]=a["delete"])})();
-Object.assign(qc.prototype,{vd(a){this.Xc&&(a=this.Xc(a));return a},Ic(a){this.Gb?.(a)},xb:Lb,nb:function(a){function b(){return this.kc?pc(this.mb.Sb,{pb:this.Jd,lb:c,zb:this,ub:a}):pc(this.mb.Sb,{pb:this,lb:a})}var c=this.vd(a);if(!c)return this.Ic(a),null;var d=oc(this.mb,c);if(void 0!==d){if(0===d.hb.count.value)return d.hb.lb=c,d.hb.ub=a,d.clone();d=d.clone();this.Ic(a);return d}d=this.mb.td(c);d=bc[d];if(!d)return b.call(this);d=this.jc?d.md:d.pointerType;var e=mc(c,this.mb,d.mb);return null===
-e?b.call(this):this.kc?pc(d.mb.Sb,{pb:d,lb:e,zb:this,ub:a}):pc(d.mb.Sb,{pb:d,lb:e})}});var Ud=()=>{if(Z){var a=Z.Vb;Z.Vb=Z.cc;Z.cc=a;a=Z.Lb;Z.Lb=Z.pc;Z.pc=a;for(a=0;21>=a;++a)Z.Lb[a]=0}};"undefined"!=typeof MainLoop&&MainLoop.re.push(Ud);for(var Vd=new Float32Array(288),Wd=0;288>=Wd;++Wd)Kd[Wd]=Vd.subarray(0,Wd);h.noExitRuntime&&(Ia=h.noExitRuntime);h.preloadPlugins&&(kb=h.preloadPlugins);h.print&&(la=h.print);h.printErr&&(n=h.printErr);h.wasmBinary&&(ma=h.wasmBinary);h.thisProgram&&(da=h.thisProgram);
+Object.assign(qc.prototype,{xd(a){this.Zc&&(a=this.Zc(a));return a},Kc(a){this.Ib?.(a)},zb:Lb,pb:function(a){function b(){return this.mc?pc(this.ob.Ub,{rb:this.Ld,nb:c,Bb:this,wb:a}):pc(this.ob.Ub,{rb:this,nb:a})}var c=this.xd(a);if(!c)return this.Kc(a),null;var d=oc(this.ob,c);if(void 0!==d){if(0===d.jb.count.value)return d.jb.nb=c,d.jb.wb=a,d.clone();d=d.clone();this.Kc(a);return d}d=this.ob.vd(c);d=bc[d];if(!d)return b.call(this);d=this.lc?d.od:d.pointerType;var e=mc(c,this.ob,d.ob);return null===
+e?b.call(this):this.mc?pc(d.ob.Ub,{rb:d,nb:e,Bb:this,wb:a}):pc(d.ob.Ub,{rb:d,nb:e})}});var Ud=()=>{if(Z){var a=Z.Xb;Z.Xb=Z.ec;Z.ec=a;a=Z.Nb;Z.Nb=Z.rc;Z.rc=a;for(a=0;21>=a;++a)Z.Nb[a]=0}};"undefined"!=typeof MainLoop&&MainLoop.te.push(Ud);for(var Vd=new Float32Array(288),Wd=0;288>=Wd;++Wd)Kd[Wd]=Vd.subarray(0,Wd);h.noExitRuntime&&(Ia=h.noExitRuntime);h.preloadPlugins&&(kb=h.preloadPlugins);h.print&&(la=h.print);h.printErr&&(n=h.printErr);h.wasmBinary&&(ma=h.wasmBinary);h.thisProgram&&(da=h.thisProgram);
if(h.preInit)for("function"==typeof h.preInit&&(h.preInit=[h.preInit]);0<h.preInit.length;)h.preInit.shift()();h.addRunDependency=jb;h.removeRunDependency=ib;h.ccall=Od;h.cwrap=(a,b,c,d)=>{var e=!c||c.every(f=>"number"===f||"boolean"===f);return"string"!==b&&e&&!d?h["_"+a]:(...f)=>Od(a,b,c,f,d)};
h.addFunction=(a,b)=>{if(!Pd){Pd=new WeakMap;var c=S.length;if(Pd)for(var d=0;d<0+c;d++){var e=tc(d);e&&Pd.set(e,d)}}if(c=Pd.get(a)||0)return c;c=Qd.length?Qd.pop():S.grow(1);try{S.set(c,a),sc[c]=S.get(c)}catch(f){if(!(f instanceof TypeError))throw f;b=Uint8Array.of(0,97,115,109,1,0,0,0,1,...Rd([1,96,...Td(b.slice(1)),...Td("v"===b[0]?"":b[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);b=new WebAssembly.Module(b);b=(new WebAssembly.Instance(b,{e:{f:a}})).exports.f;S.set(c,b);sc[c]=S.get(c)}Pd.set(a,
-c);return c};h.FS_preloadFile=ob;h.FS_unlink=(...a)=>C.unlink(...a);h.FS_createPath=(...a)=>Fb(...a);h.FS_createDevice=(...a)=>C.Kb(...a);h.FS=C;h.FS_createDataFile=(...a)=>nb(...a);h.FS_createLazyFile=(...a)=>Ib(...a);
-var vc,Ed,U,Xd,Nd,Ld,Md,ya,S,Yd={X:function(a,b,c){Ja=c;try{var d=N(a);switch(b){case 0:var e=A();if(0>e)break;for(;C.streams[e];)e++;return yb(d,e).fd;case 1:case 2:return 0;case 3:return d.flags;case 4:return e=A(),d.flags|=e,0;case 12:return e=A(),u[e+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(f){if("undefined"==typeof C||"ErrnoError"!==f.name)throw f;return-f.Ab}},ta:function(a,b,c){Ja=c;try{var d=N(a);switch(b){case 21509:return d.tty?0:-59;case 21505:if(!d.tty)return-59;if(d.tty.Jb.Bd){a=
-[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var e=A();w[e>>2]=25856;w[e+4>>2]=5;w[e+8>>2]=191;w[e+12>>2]=35387;for(var f=0;32>f;f++)q[e+f+17]=a[f]||0}return 0;case 21510:case 21511:case 21512:return d.tty?0:-59;case 21506:case 21507:case 21508:if(!d.tty)return-59;if(d.tty.Jb.Cd)for(e=A(),a=[],f=0;32>f;f++)a.push(q[e+f+17]);return 0;case 21519:if(!d.tty)return-59;e=A();return w[e>>2]=0;case 21520:return d.tty?-28:-59;case 21537:case 21531:return e=A(),C.uc(d,b,e);case 21523:if(!d.tty)return-59;
-d.tty.Jb.Dd&&(f=[24,80],e=A(),u[e>>1]=f[0],u[e+2>>1]=f[1]);return 0;case 21524:return d.tty?0:-59;case 21515:return d.tty?0:-59;default:return-28}}catch(g){if("undefined"==typeof C||"ErrnoError"!==g.name)throw g;return-g.Ab}},ua:function(a,b,c,d){Ja=d;try{b=b?D(t,b):"";var e=b;if("/"===e.charAt(0))b=e;else{var f=-100===a?C.cwd():N(a).path;if(0==e.length)throw new C.gb(44);b=f+"/"+e}var g=d?A():0;return C.open(b,c,g).fd}catch(k){if("undefined"==typeof C||"ErrnoError"!==k.name)throw k;return-k.Ab}},
-ya:()=>y(""),e:a=>{var b=Jb[a];delete Jb[a];var c=b.Cc,d=b.Gb,e=b.Nc,f=e.map(g=>g.yd).concat(e.map(g=>g.Nd));Rb([a],f,g=>{var k={},m,l;for([m,l]of e.entries()){const p=g[m],r=l.Zb,v=l.xd,z=g[m+e.length],B=l.Md,F=l.Od;k[l.rd]={read:J=>p.nb(r(v,J)),write:(J,P)=>{var K=[];B(F,J,z.rb(K,P));Kb(K)},optional:p.optional}}return[{name:b.name,nb:p=>{var r={},v;for(v in k)r[v]=k[v].read(p);d(p);return r},rb:(p,r)=>{for(var v in k)if(!(v in r||k[v].optional))throw new TypeError(`Missing field: "${v}"`);var z=
-c();for(v in k)k[v].write(z,r[v]);null!==p&&p.push(d,z);return z},xb:Lb,sb:d}]})},ha:(a,b,c,d,e)=>{b=Q(b);d=0n===d;let f=g=>g;if(d){const g=8*c;f=k=>BigInt.asUintN(g,k);e=f(e)}O(a,{name:b,nb:f,rb:(g,k)=>{"number"==typeof k&&(k=BigInt(k));return k},xb:Ub(b,c,!d),sb:null})},Qa:(a,b,c,d)=>{b=Q(b);O(a,{name:b,nb:function(e){return!!e},rb:function(e,f){return f?c:d},xb:function(e){return this.nb(t[e])},sb:null})},la:(a,b,c,d,e,f,g,k,m,l,p,r,v)=>{p=Q(p);f=T(e,f);k&&=T(g,k);l&&=T(m,l);v=T(r,v);var z=ec(p);
-dc(z,function(){xc(`Cannot construct ${p} due to unbound types`,[d])});Rb([a,b,c],d?[d]:[],B=>{B=B[0];if(d){var F=B.mb;var J=F.Sb}else J=$b.prototype;B=ac(p,function(...Pb){if(Object.getPrototypeOf(this)!==P)throw new R(`Use 'new' to construct ${p}`);if(void 0===K.Nb)throw new R(`${p} has no accessible constructor`);var Yc=K.Nb[Pb.length];if(void 0===Yc)throw new R(`Tried to invoke ctor of ${p} with invalid number of parameters (${Pb.length}) - expected (${Object.keys(K.Nb).toString()}) parameters instead!`);
-return Yc.apply(this,Pb)});var P=Object.create(J,{constructor:{value:B}});B.prototype=P;var K=new fc(p,B,P,v,F,f,k,l);if(K.vb){var G;(G=K.vb).Ec??(G.Ec=[]);K.vb.Ec.push(K)}F=new qc(p,K,!0,!1,!1);G=new qc(p+"*",K,!1,!1,!1);J=new qc(p+" const*",K,!1,!0,!1);bc[a]={pointerType:G,md:J};rc(z,B);return[F,G,J]})},Ma:(a,b,c,d,e,f)=>{var g=yc(b,c);e=T(d,e);Rb([],[a],k=>{k=k[0];var m=`constructor ${k.name}`;void 0===k.mb.Nb&&(k.mb.Nb=[]);if(void 0!==k.mb.Nb[b-1])throw new R(`Cannot register multiple constructors with identical number of parameters (${b-
-1}) for class '${k.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);k.mb.Nb[b-1]=()=>{xc(`Cannot construct ${k.name} due to unbound types`,g)};Rb([],g,l=>{l.splice(1,0,null);k.mb.Nb[b-1]=Ac(m,l,null,e,f);return[]});return[]})},c:(a,b,c,d,e,f,g,k,m)=>{var l=yc(c,d);b=Q(b);b=Bc(b);f=T(e,f);Rb([],[a],p=>{function r(){xc(`Cannot call ${v} due to unbound types`,l)}p=p[0];var v=`${p.name}.${b}`;b.startsWith("@@")&&(b=Symbol[b.substring(2)]);k&&p.mb.Kd.push(b);
-var z=p.mb.Sb,B=z[b];void 0===B||void 0===B.tb&&B.className!==p.name&&B.Mb===c-2?(r.Mb=c-2,r.className=p.name,z[b]=r):(cc(z,b,v),z[b].tb[c-2]=r);Rb([],l,F=>{F=Ac(v,F,p,f,g,m);void 0===z[b].tb?(F.Mb=c-2,z[b]=F):z[b].tb[c-2]=F;return[]});return[]})},Oa:a=>O(a,Gc),L:(a,b,c,d,e)=>{b=Q(b);e=0===e?"object":1===e?"number":"string";switch(e){case "object":function g(){}g.values={};O(a,{name:b,constructor:g,valueType:e,nb:function(k){return this.constructor.values[k]},rb:(k,m)=>m.value,xb:Hc(b,c,d),sb:null});
-dc(b,g);break;case "number":var f={};O(a,{name:b,xc:f,valueType:e,nb:k=>k,rb:(k,m)=>m,xb:Hc(b,c,d),sb:null});dc(b,f);delete h[b].Mb;break;case "string":f={},O(a,{name:b,dd:{},Zc:{},xc:f,valueType:e,nb:function(k){return this.Zc[k]},rb:function(k,m){return this.dd[m]},xb:Hc(b,c,d),sb:null}),dc(b,f),delete h[b].Mb}},l:(a,b,c)=>{var d=Ic(a,"enum");b=Q(b);switch(d.valueType){case "object":a=d.constructor;d=Object.create(d.constructor.prototype,{value:{value:c},constructor:{value:ac(`${d.name}_${b}`,function(){})}});
-a.values[c]=d;a[b]=d;break;case "number":d.xc[b]=c;break;case "string":d.dd[b]=c,d.Zc[c]=b,d.xc[b]=b}},ga:(a,b,c)=>{b=Q(b);O(a,{name:b,nb:d=>d,rb:(d,e)=>e,xb:Jc(b,c),sb:null})},b:(a,b,c,d,e,f,g)=>{var k=yc(b,c);a=Q(a);a=Bc(a);e=T(d,e);dc(a,function(){xc(`Cannot call ${a} due to unbound types`,k)},b-1);Rb([],k,m=>{m=[m[0],null].concat(m.slice(1));rc(a,Ac(a,m,null,e,f,g),b-1);return[]})},u:(a,b,c,d,e)=>{b=Q(b);let f=k=>k;if(0===d){var g=32-8*c;f=k=>k<<g>>>g;e=f(e)}O(a,{name:b,nb:f,rb:(k,m)=>m,xb:Ub(b,
-c,0!==d),sb:null})},g:(a,b,c)=>{function d(f){return new e(q.buffer,x[f+4>>2],x[f>>2])}var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];c=Q(c);O(a,{name:c,nb:d,xb:d},{zd:!0})},Pa:(a,b)=>{b=Q(b);O(a,{name:b,nb(c){var d=(d=c+4)?D(t,d,x[c>>2],!0):"";U(c);return d},rb(c,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var e="string"==typeof d;if(!(e||ArrayBuffer.isView(d)&&1==d.BYTES_PER_ELEMENT))throw new R("Cannot pass non-string to std::string");
-var f=e?Wa(d):d.length;var g=Ed(4+f+1),k=g+4;x[g>>2]=f;e?E(d,t,k,f+1):t.set(d,k);null!==c&&c.push(U,g);return g},xb:Lb,sb(c){U(c)}})},S:(a,b,c)=>{c=Q(c);if(2===b){var d=Lc;var e=Mc;var f=Nc}else d=Oc,e=Pc,f=Qc;O(a,{name:c,nb:g=>{var k=d(g+4,x[g>>2]*b,!0);U(g);return k},rb:(g,k)=>{if("string"!=typeof k)throw new R(`Cannot pass non-string to C++ string type ${c}`);var m=f(k),l=Ed(4+m+b);x[l>>2]=m/b;e(k,l+4,m+b);null!==g&&g.push(U,l);return l},xb:Lb,sb(g){U(g)}})},f:(a,b,c,d,e,f)=>{Jb[a]={name:Q(b),
-Cc:T(c,d),Gb:T(e,f),Nc:[]}},a:(a,b,c,d,e,f,g,k,m,l)=>{Jb[a].Nc.push({rd:Q(b),yd:c,Zb:T(d,e),xd:f,Nd:g,Md:T(k,m),Od:l})},Ra:(a,b)=>{b=Q(b);O(a,{Rc:!0,name:b,nb:()=>{},rb:()=>{}})},Ta:()=>{Ia=!1;Rc=0},ka:(a,b,c)=>{var [d,...e]=Uc(a,b);b=d.rb.bind(d);var f=e.map(m=>m.xb.bind(m));a--;var g={toValue:Fc};a=f.map((m,l)=>{var p=`argFromPtr${l}`;g[p]=m;return`${p}(args${l?"+"+8*l:""})`});switch(c){case 0:var k="toValue(handle)";break;case 2:k="new (toValue(handle))";break;case 3:k="";break;case 1:g.getStringOrSymbol=
-Xc,k="toValue(handle)[getStringOrSymbol(methodName)]"}k+=`(${a})`;d.Rc||(g.toReturnWire=b,g.emval_returnValue=Vc,k=`return emval_returnValue(toReturnWire, destructorsRef, ${k})`);k=`return function (handle, methodName, destructorsRef, args) {\n${k}\n}`;c=(new Function(Object.keys(g),k))(...Object.values(g));k=`methodCaller<(${e.map(m=>m.name)}) => ${d.name}>`;return Tc(ac(k,c))},ma:Ec,ja:(a,b,c,d,e)=>Sc[a](b,c,d,e),oa:()=>kc([]),ia:a=>{var b=Fc(a);Kb(b);Ec(a)},Na:(a,b,c)=>{a=Fc(a);b=Fc(b);c=Fc(c);
-a[b]=c},Ua:(a,b)=>{Zc[a]&&(clearTimeout(Zc[a].id),delete Zc[a]);if(!b)return 0;var c=setTimeout(()=>{delete Zc[a];ad(()=>Xd(a,performance.now()))},b);Zc[a]={id:c,ye:b};return 0},Va:(a,b,c,d)=>{var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();x[a>>2]=60*Math.max(f,e);w[b>>2]=Number(f!=e);b=g=>{var k=Math.abs(g);return`UTC${0<=g?"-":"+"}${String(Math.floor(k/60)).padStart(2,"0")}${String(k%60).padStart(2,"0")}`};a=b(f);b=b(e);e<f?(E(a,t,
-c,17),E(b,t,d,17)):(E(a,t,d,17),E(b,t,c,17))},Xa:function(a,b,c,d,e){var f=h.materialDataProvider;f?f(a,b,c,d,e):(x[b>>2]=0,x[c>>2]=0,x[d>>2]=0,x[e>>2]=0)},va:function(a,b,c){if(!(0<=a&&3>=a))return 28;ua[c>>3]=BigInt(Math.round(1E6*(0===a?Date.now():performance.now())));return 0},wa:a=>{var b=t.length;a>>>=0;if(2147483648<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(a,d)/65536))-ya.buffer.byteLength+65535)/65536|0;
-try{ya.grow(d);xa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1},Wa:(a,b)=>{var c=b>>2;b={alpha:!!q[b+0],depth:!!q[b+1],stencil:!!q[b+2],antialias:!!q[b+3],premultipliedAlpha:!!q[b+4],preserveDrawingBuffer:!!q[b+5],powerPreference:xd[w[c+2]],failIfMajorPerformanceCaveat:!!q[b+12],Uc:w[c+4],ne:w[c+5],Mc:q[b+24],qd:q[b+25],te:w[c+7],we:q[b+32]};a=2<a?a?D(t,a):"":a;a=yd[a]||globalThis.document?.querySelector(a);return!a||b.qd?0:wd(a,b)},La:a=>{Z==a&&(Z=0);Z===ld[a]&&(Z=null);"object"==
-typeof JSEvents&&JSEvents.ve(ld[a].Qb.canvas);ld[a]?.Qb.canvas&&(ld[a].Qb.canvas.jd=void 0);ld[a]=null},na:a=>{Z=ld[a];h.ctx=V=Z?.Qb;return!a||V?0:-5},pa:(a,b)=>{var c=0,d=0,e;for(e of Bd()){var f=b+c;x[a+d>>2]=f;c+=E(e,t,f,Infinity)+1;d+=4}return 0},qa:(a,b)=>{var c=Bd();x[a>>2]=c.length;a=0;for(var d of c)a+=Wa(d)+1;x[b>>2]=a;return 0},W:function(a){try{var b=N(a);C.close(b);return 0}catch(c){if("undefined"==typeof C||"ErrnoError"!==c.name)throw c;return c.Ab}},sa:function(a,b,c,d){try{a:{var e=
-N(a);a=b;for(var f,g=b=0;g<c;g++){var k=x[a>>2],m=x[a+4>>2];a+=8;var l=C.read(e,q,k,m,f);if(0>l){var p=-1;break a}b+=l;if(l<m)break;"undefined"!=typeof f&&(f+=l)}p=b}x[d>>2]=p;return 0}catch(r){if("undefined"==typeof C||"ErrnoError"!==r.name)throw r;return r.Ab}},ra:function(a,b,c,d){b=-9007199254740992>b||9007199254740992<b?NaN:Number(b);try{if(isNaN(b))return 61;var e=N(a);C.wb(e,b,c);ua[d>>3]=BigInt(e.position);e.rc&&0===b&&0===c&&(e.rc=null);return 0}catch(f){if("undefined"==typeof C||"ErrnoError"!==
-f.name)throw f;return f.Ab}},xa:function(a,b,c,d){try{a:{var e=N(a);a=b;for(var f,g=b=0;g<c;g++){var k=x[a>>2],m=x[a+4>>2];a+=8;var l=C.write(e,q,k,m,f);if(0>l){var p=-1;break a}b+=l;if(l<m)break;"undefined"!=typeof f&&(f+=l)}p=b}x[d>>2]=p;return 0}catch(r){if("undefined"==typeof C||"ErrnoError"!==r.name)throw r;return r.Ab}},i:a=>V.activeTexture(a),aa:(a,b)=>{V.attachShader(W[a],X[b])},B:(a,b,c)=>{V.bindAttribLocation(W[a],b,c?D(t,c):"")},d:(a,b)=>{if(b&&!gd[b]){var c=V.createBuffer();c.name=b;gd[b]=
-c}34962==a?V.Wb=b:34963==a&&(V.Xb=b);35051==a?V.Hc=b:35052==a&&(V.hc=b);V.bindBuffer(a,gd[b])},C:(a,b)=>{V.bindFramebuffer(a,hd[b])},h:(a,b)=>{V.bindTexture(a,jd[b])},k:a=>{V.bindVertexArray(kd[a]);a=V.getParameter(34965);V.Xb=a?a.name|0:0},T:(a,b)=>V.blendFunc(a,b),w:(a,b,c,d)=>V.blendFuncSeparate(a,b,c,d),q:(a,b,c,d)=>{2<=Z.version?c&&b?V.bufferData(a,t,d,c,b):V.bufferData(a,b,d):V.bufferData(a,c?t.subarray(c,c+b):b,d)},x:(a,b,c,d)=>{2<=Z.version?c&&V.bufferSubData(a,b,t,d,c):V.bufferSubData(a,
-b,t.subarray(d,d+c))},za:a=>V.checkFramebufferStatus(a),F:a=>V.clear(a),M:(a,b,c,d)=>V.clearColor(a,b,c,d),ca:a=>{V.compileShader(X[a])},Ka:()=>{var a=qd(W),b=V.createProgram();b.name=a;b.nc=b.lc=b.mc=0;b.Dc=1;W[a]=b;return a},ea:a=>{var b=qd(X);X[b]=V.createShader(a);return b},s:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=gd[d];e&&(V.deleteBuffer(e),e.name=0,gd[d]=null,d==V.Wb&&(V.Wb=0),d==V.Xb&&(V.Xb=0),d==V.Hc&&(V.Hc=0),d==V.hc&&(V.hc=0))}},Z:(a,b)=>{for(var c=0;c<a;++c){var d=w[b+4*c>>2],
-e=hd[d];e&&(V.deleteFramebuffer(e),e.name=0,hd[d]=null)}},fa:a=>{if(a){var b=W[a];b?(V.deleteProgram(b),b.name=0,W[a]=null):Y||=1281}},z:a=>{if(a){var b=X[a];b?(V.deleteShader(b),X[a]=null):Y||=1281}},E:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=jd[d];e&&(V.deleteTexture(e),e.name=0,jd[d]=null)}},G:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2];V.deleteVertexArray(kd[d]);kd[d]=null}},o:a=>V.disable(a),O:a=>{Z.Rb[a].enabled=!1;V.disableVertexAttribArray(a)},P:(a,b,c)=>{ud(b+c);V.drawArrays(a,
-b,c);td&&V.bindBuffer(34962,gd[V.Wb])},y:(a,b,c,d)=>{var e=0;if(!V.Xb){var f=1*md[c-5120]*b;var g=sd(f);V.bindBuffer(34963,g);V.bufferSubData(34963,0,t.subarray(d,d+f));if(0<b)for(g=0;g<Z.zc;++g)if(f=Z.Rb[g],f.fc&&f.enabled){switch(c){case 5121:e=Uint8Array;break;case 5123:e=Uint16Array;break;case 5125:e=Uint32Array;break;default:Y||=1282;return}e=(new e(t.buffer,d,b)).reduce((k,m)=>Math.max(k,m))+1;break}d=0}ud(e);V.drawElements(a,b,c,d);td&&V.bindBuffer(34962,gd[V.Wb]);V.Xb||V.bindBuffer(34963,
-null)},p:a=>V.enable(a),n:a=>{Z.Rb[a].enabled=!0;V.enableVertexAttribArray(a)},Y:(a,b,c,d,e)=>{V.framebufferTexture2D(a,b,c,jd[d],e)},r:(a,b)=>{rd(a,b,"createBuffer",gd)},Aa:(a,b)=>{rd(a,b,"createFramebuffer",hd)},K:(a,b)=>{rd(a,b,"createTexture",jd)},H:(a,b)=>{rd(a,b,"createVertexArray",kd)},Ba:a=>V.generateMipmap(a),Ca:(a,b)=>V.getAttribLocation(W[a],b?D(t,b):""),v:()=>{var a=V.getError()||Y;Y=0;return a},U:(a,b)=>Dd(a,b),Ja:(a,b,c,d)=>{a=V.getProgramInfoLog(W[a]);null===a&&(a="(unknown error)");
-b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},Q:(a,b,c)=>{if(c)if(a>=fd)Y||=1281;else if(a=W[a],35716==b)a=V.getProgramInfoLog(a),null===a&&(a="(unknown error)"),w[c>>2]=a.length+1;else if(35719==b){if(!a.nc){var d=V.getProgramParameter(a,35718);for(b=0;b<d;++b)a.nc=Math.max(a.nc,V.getActiveUniform(a,b).name.length+1)}w[c>>2]=a.nc}else if(35722==b){if(!a.lc)for(d=V.getProgramParameter(a,35721),b=0;b<d;++b)a.lc=Math.max(a.lc,V.getActiveAttrib(a,b).name.length+1);w[c>>2]=a.lc}else if(35381==b){if(!a.mc)for(d=
-V.getProgramParameter(a,35382),b=0;b<d;++b)a.mc=Math.max(a.mc,V.getActiveUniformBlockName(a,b).length+1);w[c>>2]=a.mc}else w[c>>2]=V.getProgramParameter(a,b);else Y||=1281},ba:(a,b,c,d)=>{a=V.getShaderInfoLog(X[a]);null===a&&(a="(unknown error)");b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},I:(a,b,c)=>{c?35716==b?(a=V.getShaderInfoLog(X[a]),null===a&&(a="(unknown error)"),w[c>>2]=a?a.length+1:0):35720==b?(a=V.getShaderSource(X[a]),w[c>>2]=a?a.length+1:0):w[c>>2]=V.getShaderParameter(X[a],b):Y||=1281},N:a=>
-{var b=nd[a];if(!b){switch(a){case 7939:b=Fd(Cd().join(" "));break;case 7936:case 7937:case 37445:case 37446:(b=V.getParameter(a))||(Y||=1280);b=b?Fd(b):0;break;case 7938:b=V.getParameter(7938);var c=`OpenGL ES 2.0 (${b})`;2<=Z.version&&(c=`OpenGL ES 3.0 (${b})`);b=Fd(c);break;case 35724:b=V.getParameter(35724);c=b.match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);null!==c&&(3==c[1].length&&(c[1]+="0"),b=`OpenGL ES GLSL ES ${c[1]} (${b})`);b=Fd(b);break;default:Y||=1280}nd[a]=b}return b},A:(a,
-b)=>{b=b?D(t,b):"";if(a=W[a]){var c=a,d=c.dc,e=c.cd,f;if(!d){c.dc=d={};c.bd={};var g=V.getProgramParameter(c,35718);for(f=0;f<g;++f){var k=V.getActiveUniform(c,f);var m=k.name;k=k.size;var l=Gd(m);l=0<l?m.slice(0,l):m;var p=c.Dc;c.Dc+=k;e[l]=[k,p];for(m=0;m<k;++m)d[p]=m,c.bd[p++]=l}}c=a.dc;d=0;e=b;f=Gd(b);0<f&&(d=parseInt(b.slice(f+1))>>>0,e=b.slice(0,f));if((e=a.cd[e])&&d<e[0]&&(d+=e[1],c[d]=c[d]||V.getUniformLocation(a,b)))return d}else Y||=1281;return-1},R:a=>{a=W[a];V.linkProgram(a);a.dc=0;a.cd=
-{}},$:(a,b)=>{3317==a?od=b:3314==a&&(pd=b);V.pixelStorei(a,b)},V:(a,b,c,d)=>V.scissor(a,b,c,d),da:(a,b,c,d)=>{for(var e="",f=0;f<b;++f){var g=(g=x[c+4*f>>2])?D(t,g,d?x[d+4*f>>2]:void 0):"";e+=g}V.shaderSource(X[a],e)},J:(a,b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.hc){V.texImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);m>>>=31-Math.clz32(l.BYTES_PER_ELEMENT);V.texImage2D(a,b,c,d,e,f,g,k,l,m);return}}l=m?Id(k,g,d,e,m):null;V.texImage2D(a,b,c,d,e,f,g,k,l)},m:(a,b,c)=>V.texParameteri(a,b,c),_:(a,
-b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.hc){V.texSubImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);V.texSubImage2D(a,b,c,d,e,f,g,k,l,m>>>31-Math.clz32(l.BYTES_PER_ELEMENT));return}}m=m?Id(k,g,e,f,m):null;V.texSubImage2D(a,b,c,d,e,f,g,k,m)},Ha:(a,b)=>{V.uniform1f(Jd(a),b)},t:(a,b)=>{V.uniform1i(Jd(a),b)},Ga:(a,b,c)=>{V.uniform2f(Jd(a),b,c)},Fa:(a,b,c,d)=>{V.uniform3f(Jd(a),b,c,d)},Ea:(a,b,c,d,e)=>{V.uniform4f(Jd(a),b,c,d,e)},Da:(a,b,c,d)=>{if(2<=Z.version)b&&V.uniformMatrix4fv(Jd(a),!!c,sa,d>>
-2,16*b);else{if(18>=b){var e=Kd[16*b],f=sa;d>>=2;b*=16;for(var g=0;g<b;g+=16){var k=d+g;e[g]=f[k];e[g+1]=f[k+1];e[g+2]=f[k+2];e[g+3]=f[k+3];e[g+4]=f[k+4];e[g+5]=f[k+5];e[g+6]=f[k+6];e[g+7]=f[k+7];e[g+8]=f[k+8];e[g+9]=f[k+9];e[g+10]=f[k+10];e[g+11]=f[k+11];e[g+12]=f[k+12];e[g+13]=f[k+13];e[g+14]=f[k+14];e[g+15]=f[k+15]}}else e=sa.subarray(d>>2,d+64*b>>2);V.uniformMatrix4fv(Jd(a),!!c,e)}},Ia:a=>{a=W[a];V.useProgram(a);V.nd=a},j:(a,b,c,d,e,f)=>{var g=Z.Rb[a];V.Wb?(g.fc=!1,V.vertexAttribPointer(a,b,c,
-!!d,e,f)):(g.size=b,g.type=c,g.Wc=d,g.stride=e,g.lb=f,g.fc=!0,g.ed=function(k,m,l,p,r,v){this.vertexAttribPointer(k,m,l,p,r,v)})},D:(a,b,c,d)=>V.viewport(a,b,c,d),Sa:$c};
-function Zd(){function a(){h.calledRun=!0;if(!na){wa=!0;h.noFSInit||C.tc||lb();$d.Za();C.Qc=!1;pa?.(h);h.onRuntimeInitialized?.();if(h.postRun)for("function"==typeof h.postRun&&(h.postRun=[h.postRun]);h.postRun.length;){var b=h.postRun.shift();Fa.push(b)}Ea(Fa)}}if(0<gb)hb=Zd;else{if(h.preRun)for("function"==typeof h.preRun&&(h.preRun=[h.preRun]);h.preRun.length;)Ha();Ea(Ga);0<gb?hb=Zd:h.setStatus?(h.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>h.setStatus(""),1);a()},1)):a()}}var $d;
-$d=await (async function(){function a(c){c=$d=c.exports;vc=c._a;Ed=h._malloc=c.$a;U=h._free=c.bb;Xd=c.cb;Nd=c.db;Ld=c.eb;Md=c.fb;ya=c.Ya;S=c.ab;xa();return $d}var b={a:Yd};if(h.instantiateWasm)return new Promise(c=>{h.instantiateWasm(b,(d,e)=>{c(a(d,e))})});za??=h.locateFile?h.locateFile?h.locateFile("esengine.wasm",ha):ha+"esengine.wasm":(new URL("esengine.wasm",import.meta.url)).href;return a((await Ca(b)).instance)}());Zd();
+c);return c};h.FS_preloadFile=ob;h.FS_unlink=(...a)=>C.unlink(...a);h.FS_createPath=(...a)=>Fb(...a);h.FS_createDevice=(...a)=>C.Mb(...a);h.FS=C;h.FS_createDataFile=(...a)=>nb(...a);h.FS_createLazyFile=(...a)=>Ib(...a);
+var vc,Ed,U,Xd,Nd,Ld,Md,ya,S,Yd={ba:function(a,b,c){Ja=c;try{var d=N(a);switch(b){case 0:var e=A();if(0>e)break;for(;C.streams[e];)e++;return yb(d,e).fd;case 1:case 2:return 0;case 3:return d.flags;case 4:return e=A(),d.flags|=e,0;case 12:return e=A(),u[e+0>>1]=2,0;case 13:case 14:return 0}return-28}catch(f){if("undefined"==typeof C||"ErrnoError"!==f.name)throw f;return-f.Cb}},ua:function(a,b,c){Ja=c;try{var d=N(a);switch(b){case 21509:return d.tty?0:-59;case 21505:if(!d.tty)return-59;if(d.tty.Lb.Dd){a=
+[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];var e=A();w[e>>2]=25856;w[e+4>>2]=5;w[e+8>>2]=191;w[e+12>>2]=35387;for(var f=0;32>f;f++)q[e+f+17]=a[f]||0}return 0;case 21510:case 21511:case 21512:return d.tty?0:-59;case 21506:case 21507:case 21508:if(!d.tty)return-59;if(d.tty.Lb.Ed)for(e=A(),a=[],f=0;32>f;f++)a.push(q[e+f+17]);return 0;case 21519:if(!d.tty)return-59;e=A();return w[e>>2]=0;case 21520:return d.tty?-28:-59;case 21537:case 21531:return e=A(),C.vc(d,b,e);case 21523:if(!d.tty)return-59;
+d.tty.Lb.Fd&&(f=[24,80],e=A(),u[e>>1]=f[0],u[e+2>>1]=f[1]);return 0;case 21524:return d.tty?0:-59;case 21515:return d.tty?0:-59;default:return-28}}catch(g){if("undefined"==typeof C||"ErrnoError"!==g.name)throw g;return-g.Cb}},va:function(a,b,c,d){Ja=d;try{b=b?D(t,b):"";var e=b;if("/"===e.charAt(0))b=e;else{var f=-100===a?C.cwd():N(a).path;if(0==e.length)throw new C.ib(44);b=f+"/"+e}var g=d?A():0;return C.open(b,c,g).fd}catch(k){if("undefined"==typeof C||"ErrnoError"!==k.name)throw k;return-k.Cb}},
+za:()=>y(""),g:a=>{var b=Jb[a];delete Jb[a];var c=b.Ec,d=b.Ib,e=b.Pc,f=e.map(g=>g.Ad).concat(e.map(g=>g.Pd));Rb([a],f,g=>{var k={},m,l;for([m,l]of e.entries()){const p=g[m],r=l.ac,v=l.zd,z=g[m+e.length],B=l.Od,F=l.Qd;k[l.td]={read:J=>p.pb(r(v,J)),write:(J,P)=>{var K=[];B(F,J,z.tb(K,P));Kb(K)},optional:p.optional}}return[{name:b.name,pb:p=>{var r={},v;for(v in k)r[v]=k[v].read(p);d(p);return r},tb:(p,r)=>{for(var v in k)if(!(v in r||k[v].optional))throw new TypeError(`Missing field: "${v}"`);var z=
+c();for(v in k)k[v].write(z,r[v]);null!==p&&p.push(d,z);return z},zb:Lb,ub:d}]})},na:(a,b,c,d,e)=>{b=Q(b);d=0n===d;let f=g=>g;if(d){const g=8*c;f=k=>BigInt.asUintN(g,k);e=f(e)}O(a,{name:b,pb:f,tb:(g,k)=>{"number"==typeof k&&(k=BigInt(k));return k},zb:Ub(b,c,!d),ub:null})},Qa:(a,b,c,d)=>{b=Q(b);O(a,{name:b,pb:function(e){return!!e},tb:function(e,f){return f?c:d},zb:function(e){return this.pb(t[e])},ub:null})},oa:(a,b,c,d,e,f,g,k,m,l,p,r,v)=>{p=Q(p);f=T(e,f);k&&=T(g,k);l&&=T(m,l);v=T(r,v);var z=ec(p);
+dc(z,function(){xc(`Cannot construct ${p} due to unbound types`,[d])});Rb([a,b,c],d?[d]:[],B=>{B=B[0];if(d){var F=B.ob;var J=F.Ub}else J=$b.prototype;B=ac(p,function(...Pb){if(Object.getPrototypeOf(this)!==P)throw new R(`Use 'new' to construct ${p}`);if(void 0===K.Pb)throw new R(`${p} has no accessible constructor`);var Zc=K.Pb[Pb.length];if(void 0===Zc)throw new R(`Tried to invoke ctor of ${p} with invalid number of parameters (${Pb.length}) - expected (${Object.keys(K.Pb).toString()}) parameters instead!`);
+return Zc.apply(this,Pb)});var P=Object.create(J,{constructor:{value:B}});B.prototype=P;var K=new fc(p,B,P,v,F,f,k,l);if(K.xb){var G;(G=K.xb).Gc??(G.Gc=[]);K.xb.Gc.push(K)}F=new qc(p,K,!0,!1,!1);G=new qc(p+"*",K,!1,!1,!1);J=new qc(p+" const*",K,!1,!0,!1);bc[a]={pointerType:G,od:J};rc(z,B);return[F,G,J]})},Na:(a,b,c,d,e,f)=>{var g=yc(b,c);e=T(d,e);Rb([],[a],k=>{k=k[0];var m=`constructor ${k.name}`;void 0===k.ob.Pb&&(k.ob.Pb=[]);if(void 0!==k.ob.Pb[b-1])throw new R(`Cannot register multiple constructors with identical number of parameters (${b-
+1}) for class '${k.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);k.ob.Pb[b-1]=()=>{xc(`Cannot construct ${k.name} due to unbound types`,g)};Rb([],g,l=>{l.splice(1,0,null);k.ob.Pb[b-1]=Ac(m,l,null,e,f);return[]});return[]})},c:(a,b,c,d,e,f,g,k,m)=>{var l=yc(c,d);b=Q(b);b=Bc(b);f=T(e,f);Rb([],[a],p=>{function r(){xc(`Cannot call ${v} due to unbound types`,l)}p=p[0];var v=`${p.name}.${b}`;b.startsWith("@@")&&(b=Symbol[b.substring(2)]);k&&p.ob.Md.push(b);
+var z=p.ob.Ub,B=z[b];void 0===B||void 0===B.vb&&B.className!==p.name&&B.Ob===c-2?(r.Ob=c-2,r.className=p.name,z[b]=r):(cc(z,b,v),z[b].vb[c-2]=r);Rb([],l,F=>{F=Ac(v,F,p,f,g,m);void 0===z[b].vb?(F.Ob=c-2,z[b]=F):z[b].vb[c-2]=F;return[]});return[]})},Oa:a=>O(a,Gc),S:(a,b,c,d,e)=>{b=Q(b);e=0===e?"object":1===e?"number":"string";switch(e){case "object":function g(){}g.values={};O(a,{name:b,constructor:g,valueType:e,pb:function(k){return this.constructor.values[k]},tb:(k,m)=>m.value,zb:Hc(b,c,d),ub:null});
+dc(b,g);break;case "number":var f={};O(a,{name:b,zc:f,valueType:e,pb:k=>k,tb:(k,m)=>m,zb:Hc(b,c,d),ub:null});dc(b,f);delete h[b].Ob;break;case "string":f={},O(a,{name:b,gd:{},ad:{},zc:f,valueType:e,pb:function(k){return this.ad[k]},tb:function(k,m){return this.gd[m]},zb:Hc(b,c,d),ub:null}),dc(b,f),delete h[b].Ob}},m:(a,b,c)=>{var d=Ic(a,"enum");b=Q(b);switch(d.valueType){case "object":a=d.constructor;d=Object.create(d.constructor.prototype,{value:{value:c},constructor:{value:ac(`${d.name}_${b}`,function(){})}});
+a.values[c]=d;a[b]=d;break;case "number":d.zc[b]=c;break;case "string":d.gd[b]=c,d.ad[c]=b,d.zc[b]=b}},ma:(a,b,c)=>{b=Q(b);O(a,{name:b,pb:d=>d,tb:(d,e)=>e,zb:Jc(b,c),ub:null})},b:(a,b,c,d,e,f,g)=>{var k=yc(b,c);a=Q(a);a=Bc(a);e=T(d,e);dc(a,function(){xc(`Cannot call ${a} due to unbound types`,k)},b-1);Rb([],k,m=>{m=[m[0],null].concat(m.slice(1));rc(a,Ac(a,m,null,e,f,g),b-1);return[]})},w:(a,b,c,d,e)=>{b=Q(b);let f=k=>k;if(0===d){var g=32-8*c;f=k=>k<<g>>>g;e=f(e)}O(a,{name:b,pb:f,tb:(k,m)=>m,zb:Ub(b,
+c,0!==d),ub:null})},i:(a,b,c)=>{function d(f){return new e(q.buffer,x[f+4>>2],x[f>>2])}var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];c=Q(c);O(a,{name:c,pb:d,zb:d},{Bd:!0})},Pa:(a,b)=>{b=Q(b);O(a,{name:b,pb(c){var d=(d=c+4)?D(t,d,x[c>>2],!0):"";U(c);return d},tb(c,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var e="string"==typeof d;if(!(e||ArrayBuffer.isView(d)&&1==d.BYTES_PER_ELEMENT))throw new R("Cannot pass non-string to std::string");
+var f=e?Wa(d):d.length;var g=Ed(4+f+1),k=g+4;x[g>>2]=f;e?E(d,t,k,f+1):t.set(d,k);null!==c&&c.push(U,g);return g},zb:Lb,ub(c){U(c)}})},Y:(a,b,c)=>{c=Q(c);if(2===b){var d=Lc;var e=Mc;var f=Nc}else d=Oc,e=Pc,f=Qc;O(a,{name:c,pb:g=>{var k=d(g+4,x[g>>2]*b,!0);U(g);return k},tb:(g,k)=>{if("string"!=typeof k)throw new R(`Cannot pass non-string to C++ string type ${c}`);var m=f(k),l=Ed(4+m+b);x[l>>2]=m/b;e(k,l+4,m+b);null!==g&&g.push(U,l);return l},zb:Lb,ub(g){U(g)}})},h:(a,b,c,d,e,f)=>{Jb[a]={name:Q(b),
+Ec:T(c,d),Ib:T(e,f),Pc:[]}},a:(a,b,c,d,e,f,g,k,m,l)=>{Jb[a].Pc.push({td:Q(b),Ad:c,ac:T(d,e),zd:f,Pd:g,Od:T(k,m),Qd:l})},Ra:(a,b)=>{b=Q(b);O(a,{Sc:!0,name:b,pb:()=>{},tb:()=>{}})},Ta:()=>{Ia=!1;Rc=0},J:(a,b,c)=>{var [d,...e]=Uc(a,b);b=d.tb.bind(d);var f=e.map(m=>m.zb.bind(m));a--;var g={toValue:Fc};a=f.map((m,l)=>{var p=`argFromPtr${l}`;g[p]=m;return`${p}(args${l?"+"+8*l:""})`});switch(c){case 0:var k="toValue(handle)";break;case 2:k="new (toValue(handle))";break;case 3:k="";break;case 1:g.getStringOrSymbol=
+Xc,k="toValue(handle)[getStringOrSymbol(methodName)]"}k+=`(${a})`;d.Sc||(g.toReturnWire=b,g.emval_returnValue=Vc,k=`return emval_returnValue(toReturnWire, destructorsRef, ${k})`);k=`return function (handle, methodName, destructorsRef, args) {\n${k}\n}`;c=(new Function(Object.keys(g),k))(...Object.values(g));k=`methodCaller<(${e.map(m=>m.name)}) => ${d.name}>`;return Tc(ac(k,c))},v:Ec,I:(a,b,c,d,e)=>Sc[a](b,c,d,e),pa:()=>kc([]),T:a=>kc(Xc(a)),ra:()=>kc({}),H:a=>{var b=Fc(a);Kb(b);Ec(a)},K:(a,b,c)=>
+{a=Fc(a);b=Fc(b);c=Fc(c);a[b]=c},Ua:(a,b)=>{Yc[a]&&(clearTimeout(Yc[a].id),delete Yc[a]);if(!b)return 0;var c=setTimeout(()=>{delete Yc[a];ad(()=>Xd(a,performance.now()))},b);Yc[a]={id:c,Ae:b};return 0},Va:(a,b,c,d)=>{var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();x[a>>2]=60*Math.max(f,e);w[b>>2]=Number(f!=e);b=g=>{var k=Math.abs(g);return`UTC${0<=g?"-":"+"}${String(Math.floor(k/60)).padStart(2,"0")}${String(k%60).padStart(2,"0")}`};
+a=b(f);b=b(e);e<f?(E(a,t,c,17),E(b,t,d,17)):(E(a,t,d,17),E(b,t,c,17))},Za:function(a,b,c,d,e){var f=h.materialDataProvider;f?f(a,b,c,d,e):(x[b>>2]=0,x[c>>2]=0,x[d>>2]=0,x[e>>2]=0)},wa:function(a,b,c){if(!(0<=a&&3>=a))return 28;ua[c>>3]=BigInt(Math.round(1E6*(0===a?Date.now():performance.now())));return 0},xa:a=>{var b=t.length;a>>>=0;if(2147483648<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(a,d)/65536))-ya.buffer.byteLength+
+65535)/65536|0;try{ya.grow(d);xa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1},Ya:(a,b)=>{var c=b>>2;b={alpha:!!q[b+0],depth:!!q[b+1],stencil:!!q[b+2],antialias:!!q[b+3],premultipliedAlpha:!!q[b+4],preserveDrawingBuffer:!!q[b+5],powerPreference:xd[w[c+2]],failIfMajorPerformanceCaveat:!!q[b+12],Vc:w[c+4],pe:w[c+5],Oc:q[b+24],sd:q[b+25],ve:w[c+7],ye:q[b+32]};a=2<a?a?D(t,a):"":a;a=yd[a]||globalThis.document?.querySelector(a);return!a||b.sd?0:wd(a,b)},Ma:a=>{Z==a&&(Z=0);Z===ld[a]&&(Z=null);
+"object"==typeof JSEvents&&JSEvents.xe(ld[a].Sb.canvas);ld[a]?.Sb.canvas&&(ld[a].Sb.canvas.ld=void 0);ld[a]=null},qa:a=>{Z=ld[a];h.ctx=V=Z?.Sb;return!a||V?0:-5},Wa:(a,b)=>{var c=0,d=0,e;for(e of Bd()){var f=b+c;x[a+d>>2]=f;c+=E(e,t,f,Infinity)+1;d+=4}return 0},Xa:(a,b)=>{var c=Bd();x[a>>2]=c.length;a=0;for(var d of c)a+=Wa(d)+1;x[b>>2]=a;return 0},aa:function(a){try{var b=N(a);C.close(b);return 0}catch(c){if("undefined"==typeof C||"ErrnoError"!==c.name)throw c;return c.Cb}},ta:function(a,b,c,d){try{a:{var e=
+N(a);a=b;for(var f,g=b=0;g<c;g++){var k=x[a>>2],m=x[a+4>>2];a+=8;var l=C.read(e,q,k,m,f);if(0>l){var p=-1;break a}b+=l;if(l<m)break;"undefined"!=typeof f&&(f+=l)}p=b}x[d>>2]=p;return 0}catch(r){if("undefined"==typeof C||"ErrnoError"!==r.name)throw r;return r.Cb}},sa:function(a,b,c,d){b=-9007199254740992>b||9007199254740992<b?NaN:Number(b);try{if(isNaN(b))return 61;var e=N(a);C.yb(e,b,c);ua[d>>3]=BigInt(e.position);e.tc&&0===b&&0===c&&(e.tc=null);return 0}catch(f){if("undefined"==typeof C||"ErrnoError"!==
+f.name)throw f;return f.Cb}},ya:function(a,b,c,d){try{a:{var e=N(a);a=b;for(var f,g=b=0;g<c;g++){var k=x[a>>2],m=x[a+4>>2];a+=8;var l=C.write(e,q,k,m,f);if(0>l){var p=-1;break a}b+=l;if(l<m)break;"undefined"!=typeof f&&(f+=l)}p=b}x[d>>2]=p;return 0}catch(r){if("undefined"==typeof C||"ErrnoError"!==r.name)throw r;return r.Cb}},e:a=>V.activeTexture(a),ga:(a,b)=>{V.attachShader(W[a],X[b])},p:(a,b,c)=>{V.bindAttribLocation(W[a],b,c?D(t,c):"")},f:(a,b)=>{if(b&&!gd[b]){var c=V.createBuffer();c.name=b;gd[b]=
+c}34962==a?V.Yb=b:34963==a&&(V.Zb=b);35051==a?V.Jc=b:35052==a&&(V.jc=b);V.bindBuffer(a,gd[b])},D:(a,b)=>{V.bindFramebuffer(a,hd[b])},d:(a,b)=>{V.bindTexture(a,jd[b])},l:a=>{V.bindVertexArray(kd[a]);a=V.getParameter(34965);V.Zb=a?a.name|0:0},Z:(a,b)=>V.blendFunc(a,b),z:(a,b,c,d)=>V.blendFuncSeparate(a,b,c,d),s:(a,b,c,d)=>{2<=Z.version?c&&b?V.bufferData(a,t,d,c,b):V.bufferData(a,b,d):V.bufferData(a,c?t.subarray(c,c+b):b,d)},A:(a,b,c,d)=>{2<=Z.version?c&&V.bufferSubData(a,b,t,d,c):V.bufferSubData(a,
+b,t.subarray(d,d+c))},Aa:a=>V.checkFramebufferStatus(a),G:a=>V.clear(a),U:(a,b,c,d)=>V.clearColor(a,b,c,d),ia:a=>{V.compileShader(X[a])},La:()=>{var a=qd(W),b=V.createProgram();b.name=a;b.pc=b.nc=b.oc=0;b.Fc=1;W[a]=b;return a},ka:a=>{var b=qd(X);X[b]=V.createShader(a);return b},u:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=gd[d];e&&(V.deleteBuffer(e),e.name=0,gd[d]=null,d==V.Yb&&(V.Yb=0),d==V.Zb&&(V.Zb=0),d==V.Jc&&(V.Jc=0),d==V.jc&&(V.jc=0))}},da:(a,b)=>{for(var c=0;c<a;++c){var d=w[b+4*c>>2],
+e=hd[d];e&&(V.deleteFramebuffer(e),e.name=0,hd[d]=null)}},la:a=>{if(a){var b=W[a];b?(V.deleteProgram(b),b.name=0,W[a]=null):Y||=1281}},C:a=>{if(a){var b=X[a];b?(V.deleteShader(b),X[a]=null):Y||=1281}},F:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2],e=jd[d];e&&(V.deleteTexture(e),e.name=0,jd[d]=null)}},L:(a,b)=>{for(var c=0;c<a;c++){var d=w[b+4*c>>2];V.deleteVertexArray(kd[d]);kd[d]=null}},q:a=>V.disable(a),W:a=>{Z.Tb[a].enabled=!1;V.disableVertexAttribArray(a)},X:(a,b,c)=>{ud(b+c);V.drawArrays(a,
+b,c);td&&V.bindBuffer(34962,gd[V.Yb])},B:(a,b,c,d)=>{var e=0;if(!V.Zb){var f=1*md[c-5120]*b;var g=sd(f);V.bindBuffer(34963,g);V.bufferSubData(34963,0,t.subarray(d,d+f));if(0<b)for(g=0;g<Z.Bc;++g)if(f=Z.Tb[g],f.ic&&f.enabled){switch(c){case 5121:e=Uint8Array;break;case 5123:e=Uint16Array;break;case 5125:e=Uint32Array;break;default:Y||=1282;return}e=(new e(t.buffer,d,b)).reduce((k,m)=>Math.max(k,m))+1;break}d=0}ud(e);V.drawElements(a,b,c,d);td&&V.bindBuffer(34962,gd[V.Yb]);V.Zb||V.bindBuffer(34963,
+null)},r:a=>V.enable(a),n:a=>{Z.Tb[a].enabled=!0;V.enableVertexAttribArray(a)},ca:(a,b,c,d,e)=>{V.framebufferTexture2D(a,b,c,jd[d],e)},t:(a,b)=>{rd(a,b,"createBuffer",gd)},Ba:(a,b)=>{rd(a,b,"createFramebuffer",hd)},R:(a,b)=>{rd(a,b,"createTexture",jd)},M:(a,b)=>{rd(a,b,"createVertexArray",kd)},Ca:a=>V.generateMipmap(a),Da:(a,b)=>V.getAttribLocation(W[a],b?D(t,b):""),x:()=>{var a=V.getError()||Y;Y=0;return a},_:(a,b)=>Dd(a,b),Ka:(a,b,c,d)=>{a=V.getProgramInfoLog(W[a]);null===a&&(a="(unknown error)");
+b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},O:(a,b,c)=>{if(c)if(a>=fd)Y||=1281;else if(a=W[a],35716==b)a=V.getProgramInfoLog(a),null===a&&(a="(unknown error)"),w[c>>2]=a.length+1;else if(35719==b){if(!a.pc){var d=V.getProgramParameter(a,35718);for(b=0;b<d;++b)a.pc=Math.max(a.pc,V.getActiveUniform(a,b).name.length+1)}w[c>>2]=a.pc}else if(35722==b){if(!a.nc)for(d=V.getProgramParameter(a,35721),b=0;b<d;++b)a.nc=Math.max(a.nc,V.getActiveAttrib(a,b).name.length+1);w[c>>2]=a.nc}else if(35381==b){if(!a.oc)for(d=
+V.getProgramParameter(a,35382),b=0;b<d;++b)a.oc=Math.max(a.oc,V.getActiveUniformBlockName(a,b).length+1);w[c>>2]=a.oc}else w[c>>2]=V.getProgramParameter(a,b);else Y||=1281},ha:(a,b,c,d)=>{a=V.getShaderInfoLog(X[a]);null===a&&(a="(unknown error)");b=0<b&&d?E(a,t,d,b):0;c&&(w[c>>2]=b)},N:(a,b,c)=>{c?35716==b?(a=V.getShaderInfoLog(X[a]),null===a&&(a="(unknown error)"),w[c>>2]=a?a.length+1:0):35720==b?(a=V.getShaderSource(X[a]),w[c>>2]=a?a.length+1:0):w[c>>2]=V.getShaderParameter(X[a],b):Y||=1281},V:a=>
+{var b=nd[a];if(!b){switch(a){case 7939:b=Fd(Cd().join(" "));break;case 7936:case 7937:case 37445:case 37446:(b=V.getParameter(a))||(Y||=1280);b=b?Fd(b):0;break;case 7938:b=V.getParameter(7938);var c=`OpenGL ES 2.0 (${b})`;2<=Z.version&&(c=`OpenGL ES 3.0 (${b})`);b=Fd(c);break;case 35724:b=V.getParameter(35724);c=b.match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);null!==c&&(3==c[1].length&&(c[1]+="0"),b=`OpenGL ES GLSL ES ${c[1]} (${b})`);b=Fd(b);break;default:Y||=1280}nd[a]=b}return b},y:(a,
+b)=>{b=b?D(t,b):"";if(a=W[a]){var c=a,d=c.fc,e=c.ed,f;if(!d){c.fc=d={};c.dd={};var g=V.getProgramParameter(c,35718);for(f=0;f<g;++f){var k=V.getActiveUniform(c,f);var m=k.name;k=k.size;var l=Gd(m);l=0<l?m.slice(0,l):m;var p=c.Fc;c.Fc+=k;e[l]=[k,p];for(m=0;m<k;++m)d[p]=m,c.dd[p++]=l}}c=a.fc;d=0;e=b;f=Gd(b);0<f&&(d=parseInt(b.slice(f+1))>>>0,e=b.slice(0,f));if((e=a.ed[e])&&d<e[0]&&(d+=e[1],c[d]=c[d]||V.getUniformLocation(a,b)))return d}else Y||=1281;return-1},P:a=>{a=W[a];V.linkProgram(a);a.fc=0;a.ed=
+{}},fa:(a,b)=>{3317==a?od=b:3314==a&&(pd=b);V.pixelStorei(a,b)},$:(a,b,c,d)=>V.scissor(a,b,c,d),ja:(a,b,c,d)=>{for(var e="",f=0;f<b;++f){var g=(g=x[c+4*f>>2])?D(t,g,d?x[d+4*f>>2]:void 0):"";e+=g}V.shaderSource(X[a],e)},Q:(a,b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.jc){V.texImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);m>>>=31-Math.clz32(l.BYTES_PER_ELEMENT);V.texImage2D(a,b,c,d,e,f,g,k,l,m);return}}l=m?Id(k,g,d,e,m):null;V.texImage2D(a,b,c,d,e,f,g,k,l)},o:(a,b,c)=>V.texParameteri(a,b,c),ea:(a,
+b,c,d,e,f,g,k,m)=>{if(2<=Z.version){if(V.jc){V.texSubImage2D(a,b,c,d,e,f,g,k,m);return}if(m){var l=Hd(k);V.texSubImage2D(a,b,c,d,e,f,g,k,l,m>>>31-Math.clz32(l.BYTES_PER_ELEMENT));return}}m=m?Id(k,g,e,f,m):null;V.texSubImage2D(a,b,c,d,e,f,g,k,m)},Ia:(a,b)=>{V.uniform1f(Jd(a),b)},j:(a,b)=>{V.uniform1i(Jd(a),b)},Ha:(a,b,c)=>{V.uniform2f(Jd(a),b,c)},Ga:(a,b,c,d)=>{V.uniform3f(Jd(a),b,c,d)},Fa:(a,b,c,d,e)=>{V.uniform4f(Jd(a),b,c,d,e)},Ea:(a,b,c,d)=>{if(2<=Z.version)b&&V.uniformMatrix4fv(Jd(a),!!c,sa,d>>
+2,16*b);else{if(18>=b){var e=Kd[16*b],f=sa;d>>=2;b*=16;for(var g=0;g<b;g+=16){var k=d+g;e[g]=f[k];e[g+1]=f[k+1];e[g+2]=f[k+2];e[g+3]=f[k+3];e[g+4]=f[k+4];e[g+5]=f[k+5];e[g+6]=f[k+6];e[g+7]=f[k+7];e[g+8]=f[k+8];e[g+9]=f[k+9];e[g+10]=f[k+10];e[g+11]=f[k+11];e[g+12]=f[k+12];e[g+13]=f[k+13];e[g+14]=f[k+14];e[g+15]=f[k+15]}}else e=sa.subarray(d>>2,d+64*b>>2);V.uniformMatrix4fv(Jd(a),!!c,e)}},Ja:a=>{a=W[a];V.useProgram(a);V.pd=a},k:(a,b,c,d,e,f)=>{var g=Z.Tb[a];V.Yb?(g.ic=!1,V.vertexAttribPointer(a,b,c,
+!!d,e,f)):(g.size=b,g.type=c,g.Yc=d,g.stride=e,g.nb=f,g.ic=!0,g.hd=function(k,m,l,p,r,v){this.vertexAttribPointer(k,m,l,p,r,v)})},E:(a,b,c,d)=>V.viewport(a,b,c,d),Sa:$c};
+function Zd(){function a(){h.calledRun=!0;if(!na){wa=!0;h.noFSInit||C.uc||lb();$d.$a();C.Rc=!1;pa?.(h);h.onRuntimeInitialized?.();if(h.postRun)for("function"==typeof h.postRun&&(h.postRun=[h.postRun]);h.postRun.length;){var b=h.postRun.shift();Fa.push(b)}Ea(Fa)}}if(0<gb)hb=Zd;else{if(h.preRun)for("function"==typeof h.preRun&&(h.preRun=[h.preRun]);h.preRun.length;)Ha();Ea(Ga);0<gb?hb=Zd:h.setStatus?(h.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>h.setStatus(""),1);a()},1)):a()}}var $d;
+$d=await (async function(){function a(c){c=$d=c.exports;vc=c.ab;Ed=h._malloc=c.bb;U=h._free=c.db;Xd=c.eb;Nd=c.fb;Ld=c.gb;Md=c.hb;ya=c._a;S=c.cb;xa();return $d}var b={a:Yd};if(h.instantiateWasm)return new Promise(c=>{h.instantiateWasm(b,(d,e)=>{c(a(d,e))})});za??=h.locateFile?h.locateFile?h.locateFile("esengine.wasm",ha):ha+"esengine.wasm":(new URL("esengine.wasm",import.meta.url)).href;return a((await Ca(b)).instance)}());Zd();
wa?moduleRtn=h:moduleRtn=new Promise((a,b)=>{pa=a;qa=b});
;return moduleRtn}export default ESEngineModule;
diff --git a/desktop/public/wasm/esengine.single.js b/desktop/public/wasm/esengine.single.js
index 5363029df..be3aa0f23 100644
Binary files a/desktop/public/wasm/esengine.single.js and b/desktop/public/wasm/esengine.single.js differ
diff --git a/desktop/public/wasm/esengine.wxgame.js b/desktop/public/wasm/esengine.wxgame.js
index 390ac7e77..b1a345a92 100644
--- a/desktop/public/wasm/esengine.wxgame.js
+++ b/desktop/public/wasm/esengine.wxgame.js
@@ -1,2 +1,2 @@
-var ESEngineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else{}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["Wa"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("esengine.wxgame.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&&registeredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this.fromWireType(HEAP8[pointer])}:function(pointer){return this.fromWireType(HEAPU8[pointer])};case 2:return signed?function(pointer){return this.fromWireType(HEAP16[pointer>>1])}:function(pointer){return this.fromWireType(HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this.fromWireType(HEAP32[pointer>>2])}:function(pointer){return this.fromWireType(HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};function getEnumValueType(rawValueType){return rawValueType===0?"object":rawValueType===1?"number":"string"}var __embind_register_enum=(rawType,name,size,isSigned,rawValueType)=>{name=AsciiToString(name);const valueType=getEnumValueType(rawValueType);switch(valueType){case"object":{function ctor(){}ctor.values={};registerType(rawType,{name,constructor:ctor,valueType,fromWireType:function(c){return this.constructor.values[c]},toWireType:(destructors,c)=>c.value,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor);break}case"number":{var keysMap={};registerType(rawType,{name,keysMap,valueType,fromWireType:c=>c,toWireType:(destructors,c)=>c,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}case"string":{var valuesMap={};var reverseMap={};var keysMap={};registerType(rawType,{name,valuesMap,reverseMap,keysMap,valueType,fromWireType:function(c){return this.reverseMap[c]},toWireType:function(destructors,c){return this.valuesMap[c]},readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}}};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=AsciiToString(name);switch(enumType.valueType){case"object":{var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value;break}case"number":{enumType.keysMap[name]=enumValue;break}case"string":{enumType.valuesMap[name]=enumValue;enumType.reverseMap[enumValue]=name;enumType.keysMap[name]=name;break}}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var argN=new Array(argCount);var invokerFunction=(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=GenericWireTypeSize}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)};var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_array=()=>Emval.toHandle([]);var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_get_now=()=>performance.now();var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}for(var ext of getEmscriptenSupportedExtensions(GLctx)){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}}}};var webglPowerPreferences=["default","low-power","high-performance"];var maybeCStringToJsString=cString=>cString>2?UTF8ToString(cString):cString;var specialHTMLTargets=[0,globalThis.document??0,globalThis.window??0];var findEventTarget=target=>{target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||globalThis.document?.querySelector(target);return domElement};var findCanvasEventTarget=findEventTarget;var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBlendFuncSeparate=(x0,x1,x2,x3)=>GLctx.blendFuncSeparate(x0,x1,x2,x3);var _glBlendFuncSeparate=_emscripten_glBlendFuncSeparate;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glBufferSubData=(target,offset,size,data)=>{if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))};var _glBufferSubData=_emscripten_glBufferSubData;var _emscripten_glCheckFramebufferStatus=x0=>GLctx.checkFramebufferStatus(x0);var _glCheckFramebufferStatus=_emscripten_glCheckFramebufferStatus;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDisableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=false;GLctx.disableVertexAttribArray(index)};var _glDisableVertexAttribArray=_emscripten_glDisableVertexAttribArray;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var _emscripten_glDrawElements=(mode,count,type,indices)=>{var buf;var vertexes=0;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));if(count>0){for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(cb.clientside&&cb.enabled){let arrayClass;switch(type){case 5121:arrayClass=Uint8Array;break;case 5123:arrayClass=Uint16Array;break;case 5125:arrayClass=Uint32Array;break;default:GL.recordError(1282);return}vertexes=new arrayClass(HEAPU8.buffer,indices,count).reduce((max,current)=>Math.max(max,current))+1;break}}}indices=0}GL.preDrawHandleClientVertexAttribBindings(vertexes);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}};var _glDrawElements=_emscripten_glDrawElements;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGenerateMipmap=x0=>GLctx.generateMipmap(x0);var _glGenerateMipmap=_emscripten_glGenerateMipmap;var _emscripten_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramInfoLog=(program,maxLength,length,infoLog)=>{var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetProgramInfoLog=_emscripten_glGetProgramInfoLog;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var _emscripten_glScissor=(x0,x1,x2,x3)=>GLctx.scissor(x0,x1,x2,x3);var _glScissor=_emscripten_glScissor;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();registerPreMainLoop(()=>GL.newRenderingFrameStarted());var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;Module["GL"]=GL;function callMaterialProvider(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr){var fn=Module["materialDataProvider"];if(fn){fn(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr)}else{HEAPU32[outShaderIdPtr>>2]=0;HEAPU32[outBlendModePtr>>2]=0;HEAPU32[outUniformBufPtr>>2]=0;HEAPU32[outUniformCountPtr>>2]=0}}var ___getTypeName,_malloc,_free,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["Xa"];_malloc=Module["_malloc"]=wasmExports["Za"];_free=Module["_free"]=wasmExports["_a"];__emscripten_stack_restore=wasmExports["$a"];__emscripten_stack_alloc=wasmExports["ab"];_emscripten_stack_get_current=wasmExports["bb"];memory=wasmMemory=wasmExports["Va"];__indirect_function_table=wasmTable=wasmExports["Ya"]}var wasmImports={X:___syscall_fcntl64,ua:___syscall_ioctl,va:___syscall_openat,ya:__abort_js,e:__embind_finalize_value_object,ia:__embind_register_bigint,Pa:__embind_register_bool,ja:__embind_register_class,Ma:__embind_register_class_constructor,c:__embind_register_class_function,Na:__embind_register_emval,L:__embind_register_enum,m:__embind_register_enum_value,ha:__embind_register_float,b:__embind_register_function,v:__embind_register_integer,g:__embind_register_memory_view,Oa:__embind_register_std_string,S:__embind_register_std_wstring,f:__embind_register_value_object,a:__embind_register_value_object_field,Qa:__embind_register_void,na:__emval_create_invoker,ka:__emval_decref,ma:__emval_invoke,pa:__emval_new_array,la:__emval_run_destructors,Ra:__emval_set_property,Sa:__tzset_js,Ua:callMaterialProvider,wa:_clock_time_get,xa:_emscripten_resize_heap,Ta:_emscripten_webgl_create_context,La:_emscripten_webgl_destroy_context,oa:_emscripten_webgl_make_context_current,qa:_environ_get,ra:_environ_sizes_get,W:_fd_close,sa:_fd_read,ta:_fd_seek,Y:_fd_write,j:_glActiveTexture,ba:_glAttachShader,B:_glBindAttribLocation,d:_glBindBuffer,C:_glBindFramebuffer,h:_glBindTexture,l:_glBindVertexArray,V:_glBlendFunc,w:_glBlendFuncSeparate,r:_glBufferData,y:_glBufferSubData,za:_glCheckFramebufferStatus,F:_glClear,M:_glClearColor,da:_glCompileShader,Ka:_glCreateProgram,fa:_glCreateShader,t:_glDeleteBuffers,_:_glDeleteFramebuffers,ga:_glDeleteProgram,z:_glDeleteShader,E:_glDeleteTextures,G:_glDeleteVertexArrays,p:_glDisable,P:_glDisableVertexAttribArray,O:_glDrawArrays,x:_glDrawElements,q:_glEnable,o:_glEnableVertexAttribArray,Z:_glFramebufferTexture2D,s:_glGenBuffers,Aa:_glGenFramebuffers,K:_glGenTextures,H:_glGenVertexArrays,Ba:_glGenerateMipmap,Ca:_glGetAttribLocation,i:_glGetError,T:_glGetIntegerv,Ja:_glGetProgramInfoLog,Q:_glGetProgramiv,ca:_glGetShaderInfoLog,I:_glGetShaderiv,N:_glGetString,A:_glGetUniformLocation,R:_glLinkProgram,aa:_glPixelStorei,U:_glScissor,ea:_glShaderSource,J:_glTexImage2D,n:_glTexParameteri,$:_glTexSubImage2D,Ha:_glUniform1f,u:_glUniform1i,Ga:_glUniform2f,Fa:_glUniform3f,Ea:_glUniform4f,Da:_glUniformMatrix4fv,Ia:_glUseProgram,k:_glVertexAttribPointer,D:_glViewport};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
+var ESEngineModule=(()=>{var _scriptName=globalThis.document?.currentScript?.src;return async function(moduleArg={}){var moduleRtn;var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else{}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");var readyPromiseResolve,readyPromiseReject;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;var HEAP64,HEAPU64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU16=new Uint16Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();wasmExports["Ya"]();FS.ignorePermissions=false}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject?.(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("esengine.wxgame.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){return new Promise((resolve,reject)=>{Module["instantiateWasm"](info,(inst,mod)=>{resolve(receiveInstance(inst,mod))})})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var addOnPostRun=cb=>onPostRuns.push(cb);var onPreRuns=[];var addOnPreRun=cb=>onPreRuns.push(cb);var noExitRuntime=true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>2];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.slice(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.slice(0,-1)}return root+dir},basename:path=>path&&path.match(/([^\/]+|\/)\/*$/)[1],join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(ENVIRONMENT_IS_NODE){var nodeCrypto=require("node:crypto");return view=>nodeCrypto.randomFillSync(view)}return view=>crypto.getRandomValues(view)};var randomFill=view=>{(randomFill=initRandomFill())(view)};var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).slice(1);to=PATH_FS.resolve(to).slice(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")}};var UTF8Decoder=globalThis.TextDecoder&&new TextDecoder;var findStringEnd=(heapOrArray,idx,maxBytesToRead,ignoreNul)=>{var maxIdx=idx+maxBytesToRead;if(ignoreNul)return maxIdx;while(heapOrArray[idx]&&!(idx>=maxIdx))++idx;return idx};var UTF8ArrayToString=(heapOrArray,idx=0,maxBytesToRead,ignoreNul)=>{var endPtr=findStringEnd(heapOrArray,idx,maxBytesToRead,ignoreNul);if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx<endPtr){var u0=heapOrArray[idx++];if(!(u0&128)){str+=String.fromCharCode(u0);continue}var u1=heapOrArray[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}var u2=heapOrArray[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u0=(u0&7)<<18|u1<<12|u2<<6|heapOrArray[idx++]&63}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i<str.length;++i){var c=str.charCodeAt(i);if(c<=127){len++}else if(c<=2047){len+=2}else if(c>=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var intArrayFromString=(stringy,dontAddNull,length)=>{var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array};var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(globalThis.window?.prompt){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=stream.tty.ops.get_char(stream.tty)}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.put_char){throw new FS.ErrnoError(60)}try{for(var i=0;i<length;i++){stream.tty.ops.put_char(stream.tty,buffer[offset+i])}}catch(e){throw new FS.ErrnoError(29)}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}},default_tty_ops:{get_char(tty){return FS_stdin_getChar()},put_char(tty,val){if(val===null||val===10){out(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output?.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var mmapAlloc=size=>{abort()};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity<CAPACITY_DOUBLING_MAX?2:1.125)>>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]!=null){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){if(!MEMFS.doesNotExistError){MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="<generic error, no stack>"}throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i<size;i++)buffer[offset+i]=contents[position+i]}return size},write(stream,buffer,offset,length,position,canOwn){if(buffer.buffer===HEAP8.buffer){canOwn=false}if(!length)return 0;var node=stream.node;node.mtime=node.ctime=Date.now();if(buffer.subarray&&(!node.contents||node.contents.subarray)){if(canOwn){node.contents=buffer.subarray(offset,offset+length);node.usedBytes=length;return length}else if(node.usedBytes===0&&position===0){node.contents=buffer.slice(offset,offset+length);node.usedBytes=length;return length}else if(position+length<=node.usedBytes){node.contents.set(buffer.subarray(offset,offset+length),position);return length}}MEMFS.expandFileStorage(node,position+length);if(node.contents.subarray&&buffer.subarray){node.contents.set(buffer.subarray(offset,offset+length),position)}else{for(var i=0;i<length;i++){node.contents[position+i]=buffer[offset+i]}}node.usedBytes=Math.max(node.usedBytes,position+length);return length},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){position+=stream.node.usedBytes}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr;var allocated;var contents=stream.node.contents;if(!(flags&2)&&contents&&contents.buffer===HEAP8.buffer){allocated=false;ptr=contents.byteOffset}else{allocated=true;ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}if(contents){if(position>0||position+length<contents.length){if(contents.subarray){contents=contents.subarray(position,position+length)}else{contents=Array.prototype.slice.call(contents,position,position+length)}}HEAP8.set(contents,ptr)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(...args)=>FS.createDataFile(...args);var getUniqueRunDependency=id=>id;var runDependencies=0;var dependenciesFulfilled=null;var removeRunDependency=id=>{runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}};var addRunDependency=id=>{runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)};var preloadPlugins=[];var FS_handledByPreloadPlugin=async(byteArray,fullname)=>{if(typeof Browser!="undefined")Browser.init();for(var plugin of preloadPlugins){if(plugin["canHandle"](fullname)){return plugin["handle"](byteArray,fullname)}}return byteArray};var FS_preloadFile=async(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);addRunDependency(dep);try{var byteArray=url;if(typeof url=="string"){byteArray=await asyncLoad(url)}byteArray=await FS_handledByPreloadPlugin(byteArray,fullname);preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}}finally{removeRunDependency(dep)}};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{FS_preloadFile(parent,name,url,canRead,canWrite,dontCreateFile,canOwn,preFinish).then(onload).catch(onerror)};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,filesystems:null,syncFSRequests:0,readFiles:{},ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path){throw new FS.ErrnoError(44)}opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p);var current=FS.root;var current_path="/";for(var i=0;i<parts.length;i++){var islast=i===parts.length-1;if(islast&&opts.parent){break}if(parts[i]==="."){continue}if(parts[i]===".."){current_path=PATH.dirname(current_path);if(FS.isRoot(current)){path=current_path+"/"+parts.slice(i+1).join("/");nlinks--;continue linkloop}else{current=current.parent}continue}current_path=PATH.join2(current_path,parts[i]);try{current=FS.lookupNode(current,parts[i])}catch(e){if(e?.errno===44&&islast&&opts.noent_okay){return{path:current_path}}throw e}if(FS.isMountpoint(current)&&(!islast||opts.follow_mount)){current=current.mounted.root}if(FS.isLink(current.mode)&&(!islast||opts.follow)){if(!current.node_ops.readlink){throw new FS.ErrnoError(52)}var link=current.node_ops.readlink(current);if(!PATH.isAbs(link)){link=PATH.dirname(current_path)+"/"+link}path=link+"/"+parts.slice(i+1).join("/");continue linkloop}}return{path:current_path,node:current}}throw new FS.ErrnoError(32)},getPath(node){var path;while(true){if(FS.isRoot(node)){var mount=node.mount.mountpoint;if(!path)return mount;return mount[mount.length-1]!=="/"?`${mount}/${path}`:mount+path}path=path?`${node.name}/${path}`:node.name;node=node.parent}},hashName(parentid,name){var hash=0;for(var i=0;i<name.length;i++){hash=(hash<<5)-hash+name.charCodeAt(i)|0}return(parentid+hash>>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&(512|64)){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},checkOpExists(op,err){if(!op){throw new FS.ErrnoError(err)}return op},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},doSetAttr(stream,node,attr){var setattr=stream?.stream_ops.setattr;var arg=setattr?stream:node;setattr??=node.node_ops.setattr;FS.checkOpExists(setattr,63);setattr(arg,attr)},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}for(var mount of mounts){if(mount.type.syncfs){mount.type.syncfs(mount,populate,done)}else{done(null)}}},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);for(var[hash,current]of Object.entries(FS.nameTable)){while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}}node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name){throw new FS.ErrnoError(28)}if(name==="."||name===".."){throw new FS.ErrnoError(20)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){return FS.statfsNode(FS.lookupPath(path,{follow:true}).node)},statfsStream(stream){return FS.statfsNode(stream.node)},statfsNode(node){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};if(node.node_ops.statfs){Object.assign(rtn,node.node_ops.statfs(node.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var dir of dirs){if(!dir)continue;if(d||PATH.isAbs(path))d+="/";d+=dir;try{FS.mkdir(d,mode)}catch(e){if(e.errno!=20)throw e}}},mkdev(path,mode,dev){if(typeof dev=="undefined"){dev=mode;mode=438}mode|=8192;return FS.mknod(path,mode,dev)},symlink(oldpath,newpath){if(!PATH_FS.resolve(oldpath)){throw new FS.ErrnoError(44)}var lookup=FS.lookupPath(newpath,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var newname=PATH.basename(newpath);var errCode=FS.mayCreate(parent,newname);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.symlink){throw new FS.ErrnoError(63)}return parent.node_ops.symlink(parent,newname,oldpath)},rename(old_path,new_path){var old_dirname=PATH.dirname(old_path);var new_dirname=PATH.dirname(new_path);var old_name=PATH.basename(old_path);var new_name=PATH.basename(new_path);var lookup,old_dir,new_dir;lookup=FS.lookupPath(old_path,{parent:true});old_dir=lookup.node;lookup=FS.lookupPath(new_path,{parent:true});new_dir=lookup.node;if(!old_dir||!new_dir)throw new FS.ErrnoError(44);if(old_dir.mount!==new_dir.mount){throw new FS.ErrnoError(75)}var old_node=FS.lookupNode(old_dir,old_name);var relative=PATH_FS.relative(old_path,new_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(28)}relative=PATH_FS.relative(new_path,old_dirname);if(relative.charAt(0)!=="."){throw new FS.ErrnoError(55)}var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(old_node===new_node){return}var isdir=FS.isDir(old_node.mode);var errCode=FS.mayDelete(old_dir,old_name,isdir);if(errCode){throw new FS.ErrnoError(errCode)}errCode=new_node?FS.mayDelete(new_dir,new_name,isdir):FS.mayCreate(new_dir,new_name);if(errCode){throw new FS.ErrnoError(errCode)}if(!old_dir.node_ops.rename){throw new FS.ErrnoError(63)}if(FS.isMountpoint(old_node)||new_node&&FS.isMountpoint(new_node)){throw new FS.ErrnoError(10)}if(new_dir!==old_dir){errCode=FS.nodePermissions(old_dir,"w");if(errCode){throw new FS.ErrnoError(errCode)}}FS.hashRemoveNode(old_node);try{old_dir.node_ops.rename(old_node,new_dir,new_name);old_node.parent=new_dir}catch(e){throw e}finally{FS.hashAddNode(old_node)}},rmdir(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,true);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.rmdir){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.rmdir(parent,name);FS.destroyNode(node)},readdir(path){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var readdir=FS.checkOpExists(node.node_ops.readdir,54);return readdir(node)},unlink(path){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;if(!parent){throw new FS.ErrnoError(44)}var name=PATH.basename(path);var node=FS.lookupNode(parent,name);var errCode=FS.mayDelete(parent,name,false);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.unlink){throw new FS.ErrnoError(63)}if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}parent.node_ops.unlink(parent,name);FS.destroyNode(node)},readlink(path){var lookup=FS.lookupPath(path);var link=lookup.node;if(!link){throw new FS.ErrnoError(44)}if(!link.node_ops.readlink){throw new FS.ErrnoError(28)}return link.node_ops.readlink(link)},stat(path,dontFollow){var lookup=FS.lookupPath(path,{follow:!dontFollow});var node=lookup.node;var getattr=FS.checkOpExists(node.node_ops.getattr,63);return getattr(node)},fstat(fd){var stream=FS.getStreamChecked(fd);var node=stream.node;var getattr=stream.stream_ops.getattr;var arg=getattr?stream:node;getattr??=node.node_ops.getattr;FS.checkOpExists(getattr,63);return getattr(arg)},lstat(path){return FS.stat(path,true)},doChmod(stream,node,mode,dontFollow){FS.doSetAttr(stream,node,{mode:mode&4095|node.mode&~4095,ctime:Date.now(),dontFollow})},chmod(path,mode,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChmod(null,node,mode,dontFollow)},lchmod(path,mode){FS.chmod(path,mode,true)},fchmod(fd,mode){var stream=FS.getStreamChecked(fd);FS.doChmod(stream,stream.node,mode,false)},doChown(stream,node,dontFollow){FS.doSetAttr(stream,node,{timestamp:Date.now(),dontFollow})},chown(path,uid,gid,dontFollow){var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:!dontFollow});node=lookup.node}else{node=path}FS.doChown(null,node,dontFollow)},lchown(path,uid,gid){FS.chown(path,uid,gid,true)},fchown(fd,uid,gid){var stream=FS.getStreamChecked(fd);FS.doChown(stream,stream.node,false)},doTruncate(stream,node,len){if(FS.isDir(node.mode)){throw new FS.ErrnoError(31)}if(!FS.isFile(node.mode)){throw new FS.ErrnoError(28)}var errCode=FS.nodePermissions(node,"w");if(errCode){throw new FS.ErrnoError(errCode)}FS.doSetAttr(stream,node,{size:len,timestamp:Date.now()})},truncate(path,len){if(len<0){throw new FS.ErrnoError(28)}var node;if(typeof path=="string"){var lookup=FS.lookupPath(path,{follow:true});node=lookup.node}else{node=path}FS.doTruncate(null,node,len)},ftruncate(fd,len){var stream=FS.getStreamChecked(fd);if(len<0||(stream.flags&2097155)===0){throw new FS.ErrnoError(28)}FS.doTruncate(stream,stream.node,len)},utime(path,atime,mtime){var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;var setattr=FS.checkOpExists(node.node_ops.setattr,63);setattr(node,{atime,mtime})},open(path,flags,mode=438){if(path===""){throw new FS.ErrnoError(44)}flags=typeof flags=="string"?FS_modeStringToFlags(flags):flags;if(flags&64){mode=mode&4095|32768}else{mode=0}var node;var isDirPath;if(typeof path=="object"){node=path}else{isDirPath=path.endsWith("/");var lookup=FS.lookupPath(path,{follow:!(flags&131072),noent_okay:true});node=lookup.node;path=lookup.path}var created=false;if(flags&64){if(node){if(flags&128){throw new FS.ErrnoError(20)}}else if(isDirPath){throw new FS.ErrnoError(31)}else{node=FS.mknod(path,mode|511,0);created=true}}if(!node){throw new FS.ErrnoError(44)}if(FS.isChrdev(node.mode)){flags&=~512}if(flags&65536&&!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}if(!created){var errCode=FS.mayOpen(node,flags);if(errCode){throw new FS.ErrnoError(errCode)}}if(flags&512&&!created){FS.truncate(node,0)}flags&=~(128|512|131072);var stream=FS.createStream({node,path:FS.getPath(node),flags,seekable:true,position:0,stream_ops:node.stream_ops,ungotten:[],error:false});if(stream.stream_ops.open){stream.stream_ops.open(stream)}if(created){FS.chmod(node,mode&511)}if(Module["logReadFiles"]&&!(flags&1)){if(!(path in FS.readFiles)){FS.readFiles[path]=1}}return stream},close(stream){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(stream.getdents)stream.getdents=null;try{if(stream.stream_ops.close){stream.stream_ops.close(stream)}}catch(e){throw e}finally{FS.closeStream(stream.fd)}stream.fd=null},isClosed(stream){return stream.fd===null},llseek(stream,offset,whence){if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if(!stream.seekable||!stream.stream_ops.llseek){throw new FS.ErrnoError(70)}if(whence!=0&&whence!=1&&whence!=2){throw new FS.ErrnoError(28)}stream.position=stream.stream_ops.llseek(stream,offset,whence);stream.ungotten=[];return stream.position},read(stream,buffer,offset,length,position){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.read){throw new FS.ErrnoError(28)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesRead=stream.stream_ops.read(stream,buffer,offset,length,position);if(!seeking)stream.position+=bytesRead;return bytesRead},write(stream,buffer,offset,length,position,canOwn){if(length<0||position<0){throw new FS.ErrnoError(28)}if(FS.isClosed(stream)){throw new FS.ErrnoError(8)}if((stream.flags&2097155)===0){throw new FS.ErrnoError(8)}if(FS.isDir(stream.node.mode)){throw new FS.ErrnoError(31)}if(!stream.stream_ops.write){throw new FS.ErrnoError(28)}if(stream.seekable&&stream.flags&1024){FS.llseek(stream,0,2)}var seeking=typeof position!="undefined";if(!seeking){position=stream.position}else if(!stream.seekable){throw new FS.ErrnoError(70)}var bytesWritten=stream.stream_ops.write(stream,buffer,offset,length,position,canOwn);if(!seeking)stream.position+=bytesWritten;return bytesWritten},mmap(stream,length,position,prot,flags){if((prot&2)!==0&&(flags&2)===0&&(stream.flags&2097155)!==2){throw new FS.ErrnoError(2)}if((stream.flags&2097155)===1){throw new FS.ErrnoError(2)}if(!stream.stream_ops.mmap){throw new FS.ErrnoError(43)}if(!length){throw new FS.ErrnoError(28)}return stream.stream_ops.mmap(stream,length,position,prot,flags)},msync(stream,buffer,offset,length,mmapFlags){if(!stream.stream_ops.msync){return 0}return stream.stream_ops.msync(stream,buffer,offset,length,mmapFlags)},ioctl(stream,cmd,arg){if(!stream.stream_ops.ioctl){throw new FS.ErrnoError(59)}return stream.stream_ops.ioctl(stream,cmd,arg)},readFile(path,opts={}){opts.flags=opts.flags||0;opts.encoding=opts.encoding||"binary";if(opts.encoding!=="utf8"&&opts.encoding!=="binary"){abort(`Invalid encoding type "${opts.encoding}"`)}var stream=FS.open(path,opts.flags);var stat=FS.stat(path);var length=stat.size;var buf=new Uint8Array(length);FS.read(stream,buf,0,length,0);if(opts.encoding==="utf8"){buf=UTF8ArrayToString(buf)}FS.close(stream);return buf},writeFile(path,data,opts={}){opts.flags=opts.flags||577;var stream=FS.open(path,opts.flags,opts.mode);if(typeof data=="string"){data=new Uint8Array(intArrayFromString(data,true))}if(ArrayBuffer.isView(data)){FS.write(stream,data,0,data.byteLength,undefined,opts.canOwn)}else{abort("Unsupported data type")}FS.close(stream)},cwd:()=>FS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomFill(randomBuffer);randomLeft=randomBuffer.byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var stream of FS.streams){if(stream){FS.close(stream)}}},findObject(path,dontResolveLastLink){var ret=FS.analyzePath(path,dontResolveLastLink);if(!ret.exists){return null}return ret.object},analyzePath(path,dontResolveLastLink){try{var lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});path=lookup.path}catch(e){}var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};try{var lookup=FS.lookupPath(path,{parent:true});ret.parentExists=true;ret.parentPath=lookup.path;ret.parentObject=lookup.node;ret.name=PATH.basename(path);lookup=FS.lookupPath(path,{follow:!dontResolveLastLink});ret.exists=true;ret.path=lookup.path;ret.object=lookup.node;ret.name=lookup.node.name;ret.isRoot=lookup.path==="/"}catch(e){ret.error=e.errno}return ret},createPath(parent,path,canRead,canWrite){parent=typeof parent=="string"?parent:FS.getPath(parent);var parts=path.split("/").reverse();while(parts.length){var part=parts.pop();if(!part)continue;var current=PATH.join2(parent,part);try{FS.mkdir(current)}catch(e){if(e.errno!=20)throw e}parent=current}return current},createFile(parent,name,properties,canRead,canWrite){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(canRead,canWrite);return FS.create(path,mode)},createDataFile(parent,name,data,canRead,canWrite,canOwn){var path=name;if(parent){parent=typeof parent=="string"?parent:FS.getPath(parent);path=name?PATH.join2(parent,name):parent}var mode=FS_getMode(canRead,canWrite);var node=FS.create(path,mode);if(data){if(typeof data=="string"){var arr=new Array(data.length);for(var i=0,len=data.length;i<len;++i)arr[i]=data.charCodeAt(i);data=arr}FS.chmod(node,mode|146);var stream=FS.open(node,577);FS.write(stream,data,0,data.length,0,canOwn);FS.close(stream);FS.chmod(node,mode)}},createDevice(parent,name,input,output){var path=PATH.join2(typeof parent=="string"?parent:FS.getPath(parent),name);var mode=FS_getMode(!!input,!!output);FS.createDevice.major??=64;var dev=FS.makedev(FS.createDevice.major++,0);FS.registerDevice(dev,{open(stream){stream.seekable=false},close(stream){if(output?.buffer?.length){output(10)}},read(stream,buffer,offset,length,pos){var bytesRead=0;for(var i=0;i<length;i++){var result;try{result=input()}catch(e){throw new FS.ErrnoError(29)}if(result===undefined&&bytesRead===0){throw new FS.ErrnoError(6)}if(result===null||result===undefined)break;bytesRead++;buffer[offset+i]=result}if(bytesRead){stream.node.atime=Date.now()}return bytesRead},write(stream,buffer,offset,length,pos){for(var i=0;i<length;i++){try{output(buffer[offset+i])}catch(e){throw new FS.ErrnoError(29)}}if(length){stream.node.mtime=stream.node.ctime=Date.now()}return i}});return FS.mkdev(path,mode,dev)},forceLoadFile(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;if(globalThis.XMLHttpRequest){abort("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.")}else{try{obj.contents=readBinary(obj.url)}catch(e){throw new FS.ErrnoError(29)}}},createLazyFile(parent,name,url,canRead,canWrite){class LazyUint8Array{lengthKnown=false;chunks=[];get(idx){if(idx>this.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)abort("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)abort("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))abort("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")abort("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(globalThis.XMLHttpRequest){if(!ENVIRONMENT_IS_WORKER)abort("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};for(const[key,fn]of Object.entries(node.stream_ops)){stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}}function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i<size;i++){buffer[offset+i]=contents[position+i]}}else{for(var i=0;i<size;i++){buffer[offset+i]=contents.get(position+i)}}return size}stream_ops.read=(stream,buffer,offset,length,position)=>{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead,ignoreNul)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead,ignoreNul):"";var SYSCALLS={calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},writeStat(buf,stat){HEAPU32[buf>>2]=stat.dev;HEAPU32[buf+4>>2]=stat.mode;HEAPU32[buf+8>>2]=stat.nlink;HEAPU32[buf+12>>2]=stat.uid;HEAPU32[buf+16>>2]=stat.gid;HEAPU32[buf+20>>2]=stat.rdev;HEAP64[buf+24>>3]=BigInt(stat.size);HEAP32[buf+32>>2]=4096;HEAP32[buf+36>>2]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();HEAP64[buf+40>>3]=BigInt(Math.floor(atime/1e3));HEAPU32[buf+48>>2]=atime%1e3*1e3*1e3;HEAP64[buf+56>>3]=BigInt(Math.floor(mtime/1e3));HEAPU32[buf+64>>2]=mtime%1e3*1e3*1e3;HEAP64[buf+72>>3]=BigInt(Math.floor(ctime/1e3));HEAPU32[buf+80>>2]=ctime%1e3*1e3*1e3;HEAP64[buf+88>>3]=BigInt(stat.ino);return 0},writeStatFs(buf,stats){HEAPU32[buf+4>>2]=stats.bsize;HEAPU32[buf+60>>2]=stats.bsize;HEAP64[buf+8>>3]=BigInt(stats.blocks);HEAP64[buf+16>>3]=BigInt(stats.bfree);HEAP64[buf+24>>3]=BigInt(stats.bavail);HEAP64[buf+32>>3]=BigInt(stats.files);HEAP64[buf+40>>3]=BigInt(stats.ffree);HEAPU32[buf+48>>2]=stats.fsid;HEAPU32[buf+64>>2]=stats.flags;HEAPU32[buf+56>>2]=stats.namelen},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_fcntl64(fd,cmd,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>1]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>2]=termios.c_iflag||0;HEAP32[argp+4>>2]=termios.c_oflag||0;HEAP32[argp+8>>2]=termios.c_cflag||0;HEAP32[argp+12>>2]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>2];var c_oflag=HEAP32[argp+4>>2];var c_cflag=HEAP32[argp+8>>2];var c_lflag=HEAP32[argp+12>>2];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>2]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21537:case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>1]=winsize[0];HEAP16[argp+2>>1]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");var structRegistrations={};var runDestructors=destructors=>{while(destructors.length){var ptr=destructors.pop();var del=destructors.pop();del(ptr)}};function readPointer(pointer){return this.fromWireType(HEAPU32[pointer>>2])}var awaitingDependencies={};var registeredTypes={};var typeDependencies={};var InternalError=class InternalError extends Error{constructor(message){super(message);this.name="InternalError"}};var throwInternalError=message=>{throw new InternalError(message)};var whenDependentTypesAreResolved=(myTypes,dependentTypes,getTypeConverters)=>{myTypes.forEach(type=>typeDependencies[type]=dependentTypes);function onComplete(typeConverters){var myTypeConverters=getTypeConverters(typeConverters);if(myTypeConverters.length!==myTypes.length){throwInternalError("Mismatched type converter count")}for(var i=0;i<myTypes.length;++i){registerType(myTypes[i],myTypeConverters[i])}}var typeConverters=new Array(dependentTypes.length);var unregisteredTypes=[];var registered=0;for(let[i,dt]of dependentTypes.entries()){if(registeredTypes.hasOwnProperty(dt)){typeConverters[i]=registeredTypes[dt]}else{unregisteredTypes.push(dt);if(!awaitingDependencies.hasOwnProperty(dt)){awaitingDependencies[dt]=[]}awaitingDependencies[dt].push(()=>{typeConverters[i]=registeredTypes[dt];++registered;if(registered===unregisteredTypes.length){onComplete(typeConverters)}})}}if(0===unregisteredTypes.length){onComplete(typeConverters)}};var __embind_finalize_value_object=structType=>{var reg=structRegistrations[structType];delete structRegistrations[structType];var rawConstructor=reg.rawConstructor;var rawDestructor=reg.rawDestructor;var fieldRecords=reg.fields;var fieldTypes=fieldRecords.map(field=>field.getterReturnType).concat(fieldRecords.map(field=>field.setterArgumentType));whenDependentTypesAreResolved([structType],fieldTypes,fieldTypes=>{var fields={};for(var[i,field]of fieldRecords.entries()){const getterReturnType=fieldTypes[i];const getter=field.getter;const getterContext=field.getterContext;const setterArgumentType=fieldTypes[i+fieldRecords.length];const setter=field.setter;const setterContext=field.setterContext;fields[field.fieldName]={read:ptr=>getterReturnType.fromWireType(getter(getterContext,ptr)),write:(ptr,o)=>{var destructors=[];setter(setterContext,ptr,setterArgumentType.toWireType(destructors,o));runDestructors(destructors)},optional:getterReturnType.optional}}return[{name:reg.name,fromWireType:ptr=>{var rv={};for(var i in fields){rv[i]=fields[i].read(ptr)}rawDestructor(ptr);return rv},toWireType:(destructors,o)=>{for(var fieldName in fields){if(!(fieldName in o)&&!fields[fieldName].optional){throw new TypeError(`Missing field: "${fieldName}"`)}}var ptr=rawConstructor();for(fieldName in fields){fields[fieldName].write(ptr,o[fieldName])}if(destructors!==null){destructors.push(rawDestructor,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction:rawDestructor}]})};var AsciiToString=ptr=>{var str="";while(1){var ch=HEAPU8[ptr++];if(!ch)return str;str+=String.fromCharCode(ch)}};var BindingError=class BindingError extends Error{constructor(message){super(message);this.name="BindingError"}};var throwBindingError=message=>{throw new BindingError(message)};function sharedRegisterType(rawType,registeredInstance,options={}){var name=registeredInstance.name;if(!rawType){throwBindingError(`type "${name}" must have a positive integer typeid pointer`)}if(registeredTypes.hasOwnProperty(rawType)){if(options.ignoreDuplicateRegistrations){return}else{throwBindingError(`Cannot register type '${name}' twice`)}}registeredTypes[rawType]=registeredInstance;delete typeDependencies[rawType];if(awaitingDependencies.hasOwnProperty(rawType)){var callbacks=awaitingDependencies[rawType];delete awaitingDependencies[rawType];callbacks.forEach(cb=>cb())}}function registerType(rawType,registeredInstance,options={}){return sharedRegisterType(rawType,registeredInstance,options)}var integerReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?pointer=>HEAP8[pointer]:pointer=>HEAPU8[pointer];case 2:return signed?pointer=>HEAP16[pointer>>1]:pointer=>HEAPU16[pointer>>1];case 4:return signed?pointer=>HEAP32[pointer>>2]:pointer=>HEAPU32[pointer>>2];case 8:return signed?pointer=>HEAP64[pointer>>3]:pointer=>HEAPU64[pointer>>3];default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};var __embind_register_bigint=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0n;let fromWireType=value=>value;if(isUnsignedType){const bitSize=size*8;fromWireType=value=>BigInt.asUintN(bitSize,value);maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>{if(typeof value=="number"){value=BigInt(value)}return value},readValueFromPointer:integerReadValueFromPointer(name,size,!isUnsignedType),destructorFunction:null})};var __embind_register_bool=(rawType,name,trueValue,falseValue)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:function(wt){return!!wt},toWireType:function(destructors,o){return o?trueValue:falseValue},readValueFromPointer:function(pointer){return this.fromWireType(HEAPU8[pointer])},destructorFunction:null})};var shallowCopyInternalPointer=o=>({count:o.count,deleteScheduled:o.deleteScheduled,preservePointerOnDelete:o.preservePointerOnDelete,ptr:o.ptr,ptrType:o.ptrType,smartPtr:o.smartPtr,smartPtrType:o.smartPtrType});var throwInstanceAlreadyDeleted=obj=>{function getInstanceTypeName(handle){return handle.$$.ptrType.registeredClass.name}throwBindingError(getInstanceTypeName(obj)+" instance already deleted")};var finalizationRegistry=false;var detachFinalizer=handle=>{};var runDestructor=$$=>{if($$.smartPtr){$$.smartPtrType.rawDestructor($$.smartPtr)}else{$$.ptrType.registeredClass.rawDestructor($$.ptr)}};var releaseClassHandle=$$=>{$$.count.value-=1;var toDelete=0===$$.count.value;if(toDelete){runDestructor($$)}};var attachFinalizer=handle=>{if(!globalThis.FinalizationRegistry){attachFinalizer=handle=>handle;return handle}finalizationRegistry=new FinalizationRegistry(info=>{releaseClassHandle(info.$$)});attachFinalizer=handle=>{var $$=handle.$$;var hasSmartPtr=!!$$.smartPtr;if(hasSmartPtr){var info={$$};finalizationRegistry.register(handle,info,handle)}return handle};detachFinalizer=handle=>finalizationRegistry.unregister(handle);return attachFinalizer(handle)};var deletionQueue=[];var flushPendingDeletes=()=>{while(deletionQueue.length){var obj=deletionQueue.pop();obj.$$.deleteScheduled=false;obj["delete"]()}};var delayFunction;var init_ClassHandle=()=>{let proto=ClassHandle.prototype;Object.assign(proto,{isAliasOf(other){if(!(this instanceof ClassHandle)){return false}if(!(other instanceof ClassHandle)){return false}var leftClass=this.$$.ptrType.registeredClass;var left=this.$$.ptr;other.$$=other.$$;var rightClass=other.$$.ptrType.registeredClass;var right=other.$$.ptr;while(leftClass.baseClass){left=leftClass.upcast(left);leftClass=leftClass.baseClass}while(rightClass.baseClass){right=rightClass.upcast(right);rightClass=rightClass.baseClass}return leftClass===rightClass&&left===right},clone(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.preservePointerOnDelete){this.$$.count.value+=1;return this}else{var clone=attachFinalizer(Object.create(Object.getPrototypeOf(this),{$$:{value:shallowCopyInternalPointer(this.$$)}}));clone.$$.count.value+=1;clone.$$.deleteScheduled=false;return clone}},delete(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}detachFinalizer(this);releaseClassHandle(this.$$);if(!this.$$.preservePointerOnDelete){this.$$.smartPtr=undefined;this.$$.ptr=undefined}},isDeleted(){return!this.$$.ptr},deleteLater(){if(!this.$$.ptr){throwInstanceAlreadyDeleted(this)}if(this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete){throwBindingError("Object already scheduled for deletion")}deletionQueue.push(this);if(deletionQueue.length===1&&delayFunction){delayFunction(flushPendingDeletes)}this.$$.deleteScheduled=true;return this}});const symbolDispose=Symbol.dispose;if(symbolDispose){proto[symbolDispose]=proto["delete"]}};function ClassHandle(){}var createNamedFunction=(name,func)=>Object.defineProperty(func,"name",{value:name});var registeredPointers={};var ensureOverloadTable=(proto,methodName,humanName)=>{if(undefined===proto[methodName].overloadTable){var prevFunc=proto[methodName];proto[methodName]=function(...args){if(!proto[methodName].overloadTable.hasOwnProperty(args.length)){throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`)}return proto[methodName].overloadTable[args.length].apply(this,args)};proto[methodName].overloadTable=[];proto[methodName].overloadTable[prevFunc.argCount]=prevFunc}};var exposePublicSymbol=(name,value,numArguments)=>{if(Module.hasOwnProperty(name)){if(undefined===numArguments||undefined!==Module[name].overloadTable&&undefined!==Module[name].overloadTable[numArguments]){throwBindingError(`Cannot register public name '${name}' twice`)}ensureOverloadTable(Module,name,name);if(Module[name].overloadTable.hasOwnProperty(numArguments)){throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`)}Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var char_0=48;var char_9=57;var makeLegalFunctionName=name=>{name=name.replace(/[^a-zA-Z0-9_]/g,"$");var f=name.charCodeAt(0);if(f>=char_0&&f<=char_9){return`_${name}`}return name};function RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast){this.name=name;this.constructor=constructor;this.instancePrototype=instancePrototype;this.rawDestructor=rawDestructor;this.baseClass=baseClass;this.getActualType=getActualType;this.upcast=upcast;this.downcast=downcast;this.pureVirtualFunctions=[]}var upcastPointer=(ptr,ptrClass,desiredClass)=>{while(ptrClass!==desiredClass){if(!ptrClass.upcast){throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`)}ptr=ptrClass.upcast(ptr);ptrClass=ptrClass.baseClass}return ptr};var embindRepr=v=>{if(v===null){return"null"}var t=typeof v;if(t==="object"||t==="array"||t==="function"){return v.toString()}else{return""+v}};function constNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}function genericPointerToWireType(destructors,handle){var ptr;if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}if(this.isSmartPointer){ptr=this.rawConstructor();if(destructors!==null){destructors.push(this.rawDestructor,ptr)}return ptr}else{return 0}}if(!handle||!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(!this.isConst&&handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);if(this.isSmartPointer){if(undefined===handle.$$.smartPtr){throwBindingError("Passing raw pointer to smart pointer is illegal")}switch(this.sharingPolicy){case 0:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType?handle.$$.smartPtrType.name:handle.$$.ptrType.name} to parameter type ${this.name}`)}break;case 1:ptr=handle.$$.smartPtr;break;case 2:if(handle.$$.smartPtrType===this){ptr=handle.$$.smartPtr}else{var clonedHandle=handle["clone"]();ptr=this.rawShare(ptr,Emval.toHandle(()=>clonedHandle["delete"]()));if(destructors!==null){destructors.push(this.rawDestructor,ptr)}}break;default:throwBindingError("Unsupported sharing policy")}}return ptr}function nonConstNoSmartPtrRawPointerToWireType(destructors,handle){if(handle===null){if(this.isReference){throwBindingError(`null is not a valid ${this.name}`)}return 0}if(!handle.$$){throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`)}if(!handle.$$.ptr){throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`)}if(handle.$$.ptrType.isConst){throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`)}var handleClass=handle.$$.ptrType.registeredClass;var ptr=upcastPointer(handle.$$.ptr,handleClass,this.registeredClass);return ptr}var downcastPointer=(ptr,ptrClass,desiredClass)=>{if(ptrClass===desiredClass){return ptr}if(undefined===desiredClass.baseClass){return null}var rv=downcastPointer(ptr,ptrClass,desiredClass.baseClass);if(rv===null){return null}return desiredClass.downcast(rv)};var registeredInstances={};var getBasestPointer=(class_,ptr)=>{if(ptr===undefined){throwBindingError("ptr should not be undefined")}while(class_.baseClass){ptr=class_.upcast(ptr);class_=class_.baseClass}return ptr};var getInheritedInstance=(class_,ptr)=>{ptr=getBasestPointer(class_,ptr);return registeredInstances[ptr]};var makeClassHandle=(prototype,record)=>{if(!record.ptrType||!record.ptr){throwInternalError("makeClassHandle requires ptr and ptrType")}var hasSmartPtrType=!!record.smartPtrType;var hasSmartPtr=!!record.smartPtr;if(hasSmartPtrType!==hasSmartPtr){throwInternalError("Both smartPtrType and smartPtr must be specified")}record.count={value:1};return attachFinalizer(Object.create(prototype,{$$:{value:record,writable:true}}))};function RegisteredPointer_fromWireType(ptr){var rawPointer=this.getPointee(ptr);if(!rawPointer){this.destructor(ptr);return null}var registeredInstance=getInheritedInstance(this.registeredClass,rawPointer);if(undefined!==registeredInstance){if(0===registeredInstance.$$.count.value){registeredInstance.$$.ptr=rawPointer;registeredInstance.$$.smartPtr=ptr;return registeredInstance["clone"]()}else{var rv=registeredInstance["clone"]();this.destructor(ptr);return rv}}function makeDefaultHandle(){if(this.isSmartPointer){return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:rawPointer,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(this.registeredClass.instancePrototype,{ptrType:this,ptr})}}var actualType=this.registeredClass.getActualType(rawPointer);var registeredPointerRecord=registeredPointers[actualType];if(!registeredPointerRecord){return makeDefaultHandle.call(this)}var toType;if(this.isConst){toType=registeredPointerRecord.constPointerType}else{toType=registeredPointerRecord.pointerType}var dp=downcastPointer(rawPointer,this.registeredClass,toType.registeredClass);if(dp===null){return makeDefaultHandle.call(this)}if(this.isSmartPointer){return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp,smartPtrType:this,smartPtr:ptr})}else{return makeClassHandle(toType.registeredClass.instancePrototype,{ptrType:toType,ptr:dp})}}var init_RegisteredPointer=()=>{Object.assign(RegisteredPointer.prototype,{getPointee(ptr){if(this.rawGetPointee){ptr=this.rawGetPointee(ptr)}return ptr},destructor(ptr){this.rawDestructor?.(ptr)},readValueFromPointer:readPointer,fromWireType:RegisteredPointer_fromWireType})};function RegisteredPointer(name,registeredClass,isReference,isConst,isSmartPointer,pointeeType,sharingPolicy,rawGetPointee,rawConstructor,rawShare,rawDestructor){this.name=name;this.registeredClass=registeredClass;this.isReference=isReference;this.isConst=isConst;this.isSmartPointer=isSmartPointer;this.pointeeType=pointeeType;this.sharingPolicy=sharingPolicy;this.rawGetPointee=rawGetPointee;this.rawConstructor=rawConstructor;this.rawShare=rawShare;this.rawDestructor=rawDestructor;if(!isSmartPointer&&registeredClass.baseClass===undefined){if(isConst){this.toWireType=constNoSmartPtrRawPointerToWireType;this.destructorFunction=null}else{this.toWireType=nonConstNoSmartPtrRawPointerToWireType;this.destructorFunction=null}}else{this.toWireType=genericPointerToWireType}}var replacePublicSymbol=(name,value,numArguments)=>{if(!Module.hasOwnProperty(name)){throwInternalError("Replacing nonexistent public symbol")}if(undefined!==Module[name].overloadTable&&undefined!==numArguments){Module[name].overloadTable[numArguments]=value}else{Module[name]=value;Module[name].argCount=numArguments}};var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var embind__requireFunction=(signature,rawFunction,isAsync=false)=>{signature=AsciiToString(signature);function makeDynCaller(){var rtn=getWasmTableEntry(rawFunction);return rtn}var fp=makeDynCaller();if(typeof fp!="function"){throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`)}return fp};class UnboundTypeError extends Error{}var getTypeName=type=>{var ptr=___getTypeName(type);var rv=AsciiToString(ptr);_free(ptr);return rv};var throwUnboundTypeError=(message,types)=>{var unboundTypes=[];var seen={};function visit(type){if(seen[type]){return}if(registeredTypes[type]){return}if(typeDependencies[type]){typeDependencies[type].forEach(visit);return}unboundTypes.push(type);seen[type]=true}types.forEach(visit);throw new UnboundTypeError(`${message}: `+unboundTypes.map(getTypeName).join([", "]))};var __embind_register_class=(rawType,rawPointerType,rawConstPointerType,baseClassRawType,getActualTypeSignature,getActualType,upcastSignature,upcast,downcastSignature,downcast,name,destructorSignature,rawDestructor)=>{name=AsciiToString(name);getActualType=embind__requireFunction(getActualTypeSignature,getActualType);upcast&&=embind__requireFunction(upcastSignature,upcast);downcast&&=embind__requireFunction(downcastSignature,downcast);rawDestructor=embind__requireFunction(destructorSignature,rawDestructor);var legalFunctionName=makeLegalFunctionName(name);exposePublicSymbol(legalFunctionName,function(){throwUnboundTypeError(`Cannot construct ${name} due to unbound types`,[baseClassRawType])});whenDependentTypesAreResolved([rawType,rawPointerType,rawConstPointerType],baseClassRawType?[baseClassRawType]:[],base=>{base=base[0];var baseClass;var basePrototype;if(baseClassRawType){baseClass=base.registeredClass;basePrototype=baseClass.instancePrototype}else{basePrototype=ClassHandle.prototype}var constructor=createNamedFunction(name,function(...args){if(Object.getPrototypeOf(this)!==instancePrototype){throw new BindingError(`Use 'new' to construct ${name}`)}if(undefined===registeredClass.constructor_body){throw new BindingError(`${name} has no accessible constructor`)}var body=registeredClass.constructor_body[args.length];if(undefined===body){throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`)}return body.apply(this,args)});var instancePrototype=Object.create(basePrototype,{constructor:{value:constructor}});constructor.prototype=instancePrototype;var registeredClass=new RegisteredClass(name,constructor,instancePrototype,rawDestructor,baseClass,getActualType,upcast,downcast);if(registeredClass.baseClass){registeredClass.baseClass.__derivedClasses??=[];registeredClass.baseClass.__derivedClasses.push(registeredClass)}var referenceConverter=new RegisteredPointer(name,registeredClass,true,false,false);var pointerConverter=new RegisteredPointer(name+"*",registeredClass,false,false,false);var constPointerConverter=new RegisteredPointer(name+" const*",registeredClass,false,true,false);registeredPointers[rawType]={pointerType:pointerConverter,constPointerType:constPointerConverter};replacePublicSymbol(legalFunctionName,constructor);return[referenceConverter,pointerConverter,constPointerConverter]})};var heap32VectorToArray=(count,firstElement)=>{var array=[];for(var i=0;i<count;i++){array.push(HEAPU32[firstElement+i*4>>2])}return array};function usesDestructorStack(argTypes){for(var i=1;i<argTypes.length;++i){if(argTypes[i]!==null&&argTypes[i].destructorFunction===undefined){return true}}return false}function craftInvokerFunction(humanName,argTypes,classType,cppInvokerFunc,cppTargetFunc,isAsync){var argCount=argTypes.length;if(argCount<2){throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!")}var isClassMethodFunc=argTypes[1]!==null&&classType!==null;var needsDestructorStack=usesDestructorStack(argTypes);var returns=!argTypes[0].isVoid;var expectedArgCount=argCount-2;var argsWired=new Array(expectedArgCount);var invokerFuncArgs=[];var destructors=[];var invokerFn=function(...args){destructors.length=0;var thisWired;invokerFuncArgs.length=isClassMethodFunc?2:1;invokerFuncArgs[0]=cppTargetFunc;if(isClassMethodFunc){thisWired=argTypes[1].toWireType(destructors,this);invokerFuncArgs[1]=thisWired}for(var i=0;i<expectedArgCount;++i){argsWired[i]=argTypes[i+2].toWireType(destructors,args[i]);invokerFuncArgs.push(argsWired[i])}var rv=cppInvokerFunc(...invokerFuncArgs);function onDone(rv){if(needsDestructorStack){runDestructors(destructors)}else{for(var i=isClassMethodFunc?1:2;i<argTypes.length;i++){var param=i===1?thisWired:argsWired[i-2];if(argTypes[i].destructorFunction!==null){argTypes[i].destructorFunction(param)}}}if(returns){return argTypes[0].fromWireType(rv)}}return onDone(rv)};return createNamedFunction(humanName,invokerFn)}var __embind_register_class_constructor=(rawClassType,argCount,rawArgTypesAddr,invokerSignature,invoker,rawConstructor)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);invoker=embind__requireFunction(invokerSignature,invoker);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`constructor ${classType.name}`;if(undefined===classType.registeredClass.constructor_body){classType.registeredClass.constructor_body=[]}if(undefined!==classType.registeredClass.constructor_body[argCount-1]){throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount-1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`)}classType.registeredClass.constructor_body[argCount-1]=()=>{throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`,rawArgTypes)};whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{argTypes.splice(1,0,null);classType.registeredClass.constructor_body[argCount-1]=craftInvokerFunction(humanName,argTypes,null,invoker,rawConstructor);return[]});return[]})};var getFunctionName=signature=>{signature=signature.trim();const argsIndex=signature.indexOf("(");if(argsIndex===-1)return signature;return signature.slice(0,argsIndex)};var __embind_register_class_function=(rawClassType,methodName,argCount,rawArgTypesAddr,invokerSignature,rawInvoker,context,isPureVirtual,isAsync,isNonnullReturn)=>{var rawArgTypes=heap32VectorToArray(argCount,rawArgTypesAddr);methodName=AsciiToString(methodName);methodName=getFunctionName(methodName);rawInvoker=embind__requireFunction(invokerSignature,rawInvoker,isAsync);whenDependentTypesAreResolved([],[rawClassType],classType=>{classType=classType[0];var humanName=`${classType.name}.${methodName}`;if(methodName.startsWith("@@")){methodName=Symbol[methodName.substring(2)]}if(isPureVirtual){classType.registeredClass.pureVirtualFunctions.push(methodName)}function unboundTypesHandler(){throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`,rawArgTypes)}var proto=classType.registeredClass.instancePrototype;var method=proto[methodName];if(undefined===method||undefined===method.overloadTable&&method.className!==classType.name&&method.argCount===argCount-2){unboundTypesHandler.argCount=argCount-2;unboundTypesHandler.className=classType.name;proto[methodName]=unboundTypesHandler}else{ensureOverloadTable(proto,methodName,humanName);proto[methodName].overloadTable[argCount-2]=unboundTypesHandler}whenDependentTypesAreResolved([],rawArgTypes,argTypes=>{var memberFunction=craftInvokerFunction(humanName,argTypes,classType,rawInvoker,context,isAsync);if(undefined===proto[methodName].overloadTable){memberFunction.argCount=argCount-2;proto[methodName]=memberFunction}else{proto[methodName].overloadTable[argCount-2]=memberFunction}return[]});return[]})};var emval_freelist=[];var emval_handles=[0,1,,1,null,1,true,1,false,1];var __emval_decref=handle=>{if(handle>9&&0===--emval_handles[handle+1]){emval_handles[handle]=undefined;emval_freelist.push(handle)}};var Emval={toValue:handle=>{if(!handle){throwBindingError(`Cannot use deleted val. handle = ${handle}`)}return emval_handles[handle]},toHandle:value=>{switch(value){case undefined:return 2;case null:return 4;case true:return 6;case false:return 8;default:{const handle=emval_freelist.pop()||emval_handles.length;emval_handles[handle]=value;emval_handles[handle+1]=1;return handle}}}};var EmValType={name:"emscripten::val",fromWireType:handle=>{var rv=Emval.toValue(handle);__emval_decref(handle);return rv},toWireType:(destructors,value)=>Emval.toHandle(value),readValueFromPointer:readPointer,destructorFunction:null};var __embind_register_emval=rawType=>registerType(rawType,EmValType);var enumReadValueFromPointer=(name,width,signed)=>{switch(width){case 1:return signed?function(pointer){return this.fromWireType(HEAP8[pointer])}:function(pointer){return this.fromWireType(HEAPU8[pointer])};case 2:return signed?function(pointer){return this.fromWireType(HEAP16[pointer>>1])}:function(pointer){return this.fromWireType(HEAPU16[pointer>>1])};case 4:return signed?function(pointer){return this.fromWireType(HEAP32[pointer>>2])}:function(pointer){return this.fromWireType(HEAPU32[pointer>>2])};default:throw new TypeError(`invalid integer width (${width}): ${name}`)}};function getEnumValueType(rawValueType){return rawValueType===0?"object":rawValueType===1?"number":"string"}var __embind_register_enum=(rawType,name,size,isSigned,rawValueType)=>{name=AsciiToString(name);const valueType=getEnumValueType(rawValueType);switch(valueType){case"object":{function ctor(){}ctor.values={};registerType(rawType,{name,constructor:ctor,valueType,fromWireType:function(c){return this.constructor.values[c]},toWireType:(destructors,c)=>c.value,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,ctor);break}case"number":{var keysMap={};registerType(rawType,{name,keysMap,valueType,fromWireType:c=>c,toWireType:(destructors,c)=>c,readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}case"string":{var valuesMap={};var reverseMap={};var keysMap={};registerType(rawType,{name,valuesMap,reverseMap,keysMap,valueType,fromWireType:function(c){return this.reverseMap[c]},toWireType:function(destructors,c){return this.valuesMap[c]},readValueFromPointer:enumReadValueFromPointer(name,size,isSigned),destructorFunction:null});exposePublicSymbol(name,keysMap);delete Module[name].argCount;break}}};var requireRegisteredType=(rawType,humanName)=>{var impl=registeredTypes[rawType];if(undefined===impl){throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`)}return impl};var __embind_register_enum_value=(rawEnumType,name,enumValue)=>{var enumType=requireRegisteredType(rawEnumType,"enum");name=AsciiToString(name);switch(enumType.valueType){case"object":{var Enum=enumType.constructor;var Value=Object.create(enumType.constructor.prototype,{value:{value:enumValue},constructor:{value:createNamedFunction(`${enumType.name}_${name}`,function(){})}});Enum.values[enumValue]=Value;Enum[name]=Value;break}case"number":{enumType.keysMap[name]=enumValue;break}case"string":{enumType.valuesMap[name]=enumValue;enumType.reverseMap[enumValue]=name;enumType.keysMap[name]=name;break}}};var floatReadValueFromPointer=(name,width)=>{switch(width){case 4:return function(pointer){return this.fromWireType(HEAPF32[pointer>>2])};case 8:return function(pointer){return this.fromWireType(HEAPF64[pointer>>3])};default:throw new TypeError(`invalid float width (${width}): ${name}`)}};var __embind_register_float=(rawType,name,size)=>{name=AsciiToString(name);registerType(rawType,{name,fromWireType:value=>value,toWireType:(destructors,value)=>value,readValueFromPointer:floatReadValueFromPointer(name,size),destructorFunction:null})};var __embind_register_function=(name,argCount,rawArgTypesAddr,signature,rawInvoker,fn,isAsync,isNonnullReturn)=>{var argTypes=heap32VectorToArray(argCount,rawArgTypesAddr);name=AsciiToString(name);name=getFunctionName(name);rawInvoker=embind__requireFunction(signature,rawInvoker,isAsync);exposePublicSymbol(name,function(){throwUnboundTypeError(`Cannot call ${name} due to unbound types`,argTypes)},argCount-1);whenDependentTypesAreResolved([],argTypes,argTypes=>{var invokerArgsArray=[argTypes[0],null].concat(argTypes.slice(1));replacePublicSymbol(name,craftInvokerFunction(name,invokerArgsArray,null,rawInvoker,fn,isAsync),argCount-1);return[]})};var __embind_register_integer=(primitiveType,name,size,minRange,maxRange)=>{name=AsciiToString(name);const isUnsignedType=minRange===0;let fromWireType=value=>value;if(isUnsignedType){var bitshift=32-8*size;fromWireType=value=>value<<bitshift>>>bitshift;maxRange=fromWireType(maxRange)}registerType(primitiveType,{name,fromWireType,toWireType:(destructors,value)=>value,readValueFromPointer:integerReadValueFromPointer(name,size,minRange!==0),destructorFunction:null})};var __embind_register_memory_view=(rawType,dataTypeIndex,name)=>{var typeMapping=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array];var TA=typeMapping[dataTypeIndex];function decodeMemoryView(handle){var size=HEAPU32[handle>>2];var data=HEAPU32[handle+4>>2];return new TA(HEAP8.buffer,data,size)}name=AsciiToString(name);registerType(rawType,{name,fromWireType:decodeMemoryView,readValueFromPointer:decodeMemoryView},{ignoreDuplicateRegistrations:true})};var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var __embind_register_std_string=(rawType,name)=>{name=AsciiToString(name);var stdStringIsUTF8=true;registerType(rawType,{name,fromWireType(value){var length=HEAPU32[value>>2];var payload=value+4;var str;if(stdStringIsUTF8){str=UTF8ToString(payload,length,true)}else{str="";for(var i=0;i<length;++i){str+=String.fromCharCode(HEAPU8[payload+i])}}_free(value);return str},toWireType(destructors,value){if(value instanceof ArrayBuffer){value=new Uint8Array(value)}var length;var valueIsOfTypeString=typeof value=="string";if(!(valueIsOfTypeString||ArrayBuffer.isView(value)&&value.BYTES_PER_ELEMENT==1)){throwBindingError("Cannot pass non-string to std::string")}if(stdStringIsUTF8&&valueIsOfTypeString){length=lengthBytesUTF8(value)}else{length=value.length}var base=_malloc(4+length+1);var ptr=base+4;HEAPU32[base>>2]=length;if(valueIsOfTypeString){if(stdStringIsUTF8){stringToUTF8(value,ptr,length+1)}else{for(var i=0;i<length;++i){var charCode=value.charCodeAt(i);if(charCode>255){_free(base);throwBindingError("String has UTF-16 code units that do not fit in 8 bits")}HEAPU8[ptr+i]=charCode}}}else{HEAPU8.set(value,ptr)}if(destructors!==null){destructors.push(_free,base)}return base},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var UTF16Decoder=globalThis.TextDecoder?new TextDecoder("utf-16le"):undefined;var UTF16ToString=(ptr,maxBytesToRead,ignoreNul)=>{var idx=ptr>>1;var endIdx=findStringEnd(HEAPU16,idx,maxBytesToRead/2,ignoreNul);if(endIdx-idx>16&&UTF16Decoder)return UTF16Decoder.decode(HEAPU16.subarray(idx,endIdx));var str="";for(var i=idx;i<endIdx;++i){var codeUnit=HEAPU16[i];str+=String.fromCharCode(codeUnit)}return str};var stringToUTF16=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<2)return 0;maxBytesToWrite-=2;var startPtr=outPtr;var numCharsToWrite=maxBytesToWrite<str.length*2?maxBytesToWrite/2:str.length;for(var i=0;i<numCharsToWrite;++i){var codeUnit=str.charCodeAt(i);HEAP16[outPtr>>1]=codeUnit;outPtr+=2}HEAP16[outPtr>>1]=0;return outPtr-startPtr};var lengthBytesUTF16=str=>str.length*2;var UTF32ToString=(ptr,maxBytesToRead,ignoreNul)=>{var str="";var startIdx=ptr>>2;for(var i=0;!(i>=maxBytesToRead/4);i++){var utf32=HEAPU32[startIdx+i];if(!utf32&&!ignoreNul)break;str+=String.fromCodePoint(utf32)}return str};var stringToUTF32=(str,outPtr,maxBytesToWrite)=>{maxBytesToWrite??=2147483647;if(maxBytesToWrite<4)return 0;var startPtr=outPtr;var endPtr=startPtr+maxBytesToWrite-4;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}HEAP32[outPtr>>2]=codePoint;outPtr+=4;if(outPtr+4>endPtr)break}HEAP32[outPtr>>2]=0;return outPtr-startPtr};var lengthBytesUTF32=str=>{var len=0;for(var i=0;i<str.length;++i){var codePoint=str.codePointAt(i);if(codePoint>65535){i++}len+=4}return len};var __embind_register_std_wstring=(rawType,charSize,name)=>{name=AsciiToString(name);var decodeString,encodeString,lengthBytesUTF;if(charSize===2){decodeString=UTF16ToString;encodeString=stringToUTF16;lengthBytesUTF=lengthBytesUTF16}else{decodeString=UTF32ToString;encodeString=stringToUTF32;lengthBytesUTF=lengthBytesUTF32}registerType(rawType,{name,fromWireType:value=>{var length=HEAPU32[value>>2];var str=decodeString(value+4,length*charSize,true);_free(value);return str},toWireType:(destructors,value)=>{if(!(typeof value=="string")){throwBindingError(`Cannot pass non-string to C++ string type ${name}`)}var length=lengthBytesUTF(value);var ptr=_malloc(4+length+charSize);HEAPU32[ptr>>2]=length/charSize;encodeString(value,ptr+4,length+charSize);if(destructors!==null){destructors.push(_free,ptr)}return ptr},readValueFromPointer:readPointer,destructorFunction(ptr){_free(ptr)}})};var __embind_register_value_object=(rawType,name,constructorSignature,rawConstructor,destructorSignature,rawDestructor)=>{structRegistrations[rawType]={name:AsciiToString(name),rawConstructor:embind__requireFunction(constructorSignature,rawConstructor),rawDestructor:embind__requireFunction(destructorSignature,rawDestructor),fields:[]}};var __embind_register_value_object_field=(structType,fieldName,getterReturnType,getterSignature,getter,getterContext,setterArgumentType,setterSignature,setter,setterContext)=>{structRegistrations[structType].fields.push({fieldName:AsciiToString(fieldName),getterReturnType,getter:embind__requireFunction(getterSignature,getter),getterContext,setterArgumentType,setter:embind__requireFunction(setterSignature,setter),setterContext})};var __embind_register_void=(rawType,name)=>{name=AsciiToString(name);registerType(rawType,{isVoid:true,name,fromWireType:()=>undefined,toWireType:(destructors,o)=>undefined})};var emval_methodCallers=[];var emval_addMethodCaller=caller=>{var id=emval_methodCallers.length;emval_methodCallers.push(caller);return id};var emval_lookupTypes=(argCount,argTypes)=>{var a=new Array(argCount);for(var i=0;i<argCount;++i){a[i]=requireRegisteredType(HEAPU32[argTypes+i*4>>2],`parameter ${i}`)}return a};var emval_returnValue=(toReturnWire,destructorsRef,handle)=>{var destructors=[];var result=toReturnWire(destructors,handle);if(destructors.length){HEAPU32[destructorsRef>>2]=Emval.toHandle(destructors)}return result};var emval_symbols={};var getStringOrSymbol=address=>{var symbol=emval_symbols[address];if(symbol===undefined){return AsciiToString(address)}return symbol};var __emval_create_invoker=(argCount,argTypesPtr,kind)=>{var GenericWireTypeSize=8;var[retType,...argTypes]=emval_lookupTypes(argCount,argTypesPtr);var toReturnWire=retType.toWireType.bind(retType);var argFromPtr=argTypes.map(type=>type.readValueFromPointer.bind(type));argCount--;var argN=new Array(argCount);var invokerFunction=(handle,methodName,destructorsRef,args)=>{var offset=0;for(var i=0;i<argCount;++i){argN[i]=argFromPtr[i](args+offset);offset+=GenericWireTypeSize}var rv;switch(kind){case 0:rv=Emval.toValue(handle).apply(null,argN);break;case 2:rv=Reflect.construct(Emval.toValue(handle),argN);break;case 3:rv=argN[0];break;case 1:rv=Emval.toValue(handle)[getStringOrSymbol(methodName)](...argN);break}return emval_returnValue(toReturnWire,destructorsRef,rv)};var functionName=`methodCaller<(${argTypes.map(t=>t.name)}) => ${retType.name}>`;return emval_addMethodCaller(createNamedFunction(functionName,invokerFunction))};var __emval_invoke=(caller,handle,methodName,destructorsRef,args)=>emval_methodCallers[caller](handle,methodName,destructorsRef,args);var __emval_new_array=()=>Emval.toHandle([]);var __emval_new_cstring=v=>Emval.toHandle(getStringOrSymbol(v));var __emval_new_object=()=>Emval.toHandle({});var __emval_run_destructors=handle=>{var destructors=Emval.toValue(handle);runDestructors(destructors);__emval_decref(handle)};var __emval_set_property=(handle,key,value)=>{handle=Emval.toValue(handle);key=Emval.toValue(key);value=Emval.toValue(value);handle[key]=value};var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var _emscripten_get_now=()=>performance.now();var _emscripten_date_now=()=>Date.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;var INT53_MAX=9007199254740992;var INT53_MIN=-9007199254740992;var bigintToI53Checked=num=>num<INT53_MIN||num>INT53_MAX?NaN:Number(num);function _clock_time_get(clk_id,ignored_precision,ptime){ignored_precision=bigintToI53Checked(ignored_precision);if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);HEAP64[ptime>>3]=BigInt(nsec);return 0}var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var GLctx;var webgl_enable_ANGLE_instanced_arrays=ctx=>{var ext=ctx.getExtension("ANGLE_instanced_arrays");if(ext){ctx["vertexAttribDivisor"]=(index,divisor)=>ext["vertexAttribDivisorANGLE"](index,divisor);ctx["drawArraysInstanced"]=(mode,first,count,primcount)=>ext["drawArraysInstancedANGLE"](mode,first,count,primcount);ctx["drawElementsInstanced"]=(mode,count,type,indices,primcount)=>ext["drawElementsInstancedANGLE"](mode,count,type,indices,primcount);return 1}};var webgl_enable_OES_vertex_array_object=ctx=>{var ext=ctx.getExtension("OES_vertex_array_object");if(ext){ctx["createVertexArray"]=()=>ext["createVertexArrayOES"]();ctx["deleteVertexArray"]=vao=>ext["deleteVertexArrayOES"](vao);ctx["bindVertexArray"]=vao=>ext["bindVertexArrayOES"](vao);ctx["isVertexArray"]=vao=>ext["isVertexArrayOES"](vao);return 1}};var webgl_enable_WEBGL_draw_buffers=ctx=>{var ext=ctx.getExtension("WEBGL_draw_buffers");if(ext){ctx["drawBuffers"]=(n,bufs)=>ext["drawBuffersWEBGL"](n,bufs);return 1}};var webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.dibvbi=ctx.getExtension("WEBGL_draw_instanced_base_vertex_base_instance"));var webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance=ctx=>!!(ctx.mdibvbi=ctx.getExtension("WEBGL_multi_draw_instanced_base_vertex_base_instance"));var webgl_enable_EXT_polygon_offset_clamp=ctx=>!!(ctx.extPolygonOffsetClamp=ctx.getExtension("EXT_polygon_offset_clamp"));var webgl_enable_EXT_clip_control=ctx=>!!(ctx.extClipControl=ctx.getExtension("EXT_clip_control"));var webgl_enable_WEBGL_polygon_mode=ctx=>!!(ctx.webglPolygonMode=ctx.getExtension("WEBGL_polygon_mode"));var webgl_enable_WEBGL_multi_draw=ctx=>!!(ctx.multiDrawWebgl=ctx.getExtension("WEBGL_multi_draw"));var getEmscriptenSupportedExtensions=ctx=>{var supportedExtensions=["ANGLE_instanced_arrays","EXT_blend_minmax","EXT_disjoint_timer_query","EXT_frag_depth","EXT_shader_texture_lod","EXT_sRGB","OES_element_index_uint","OES_fbo_render_mipmap","OES_standard_derivatives","OES_texture_float","OES_texture_half_float","OES_texture_half_float_linear","OES_vertex_array_object","WEBGL_color_buffer_float","WEBGL_depth_texture","WEBGL_draw_buffers","EXT_color_buffer_float","EXT_conservative_depth","EXT_disjoint_timer_query_webgl2","EXT_texture_norm16","NV_shader_noperspective_interpolation","WEBGL_clip_cull_distance","EXT_clip_control","EXT_color_buffer_half_float","EXT_depth_clamp","EXT_float_blend","EXT_polygon_offset_clamp","EXT_texture_compression_bptc","EXT_texture_compression_rgtc","EXT_texture_filter_anisotropic","KHR_parallel_shader_compile","OES_texture_float_linear","WEBGL_blend_func_extended","WEBGL_compressed_texture_astc","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_etc1","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_s3tc_srgb","WEBGL_debug_renderer_info","WEBGL_debug_shaders","WEBGL_lose_context","WEBGL_multi_draw","WEBGL_polygon_mode"];return(ctx.getSupportedExtensions()||[]).filter(ext=>supportedExtensions.includes(ext))};var registerPreMainLoop=f=>{typeof MainLoop!="undefined"&&MainLoop.preMainLoop.push(f)};var GL={counter:1,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:[],offscreenCanvases:{},queries:[],samplers:[],transformFeedbacks:[],syncs:[],byteSizeByTypeRoot:5120,byteSizeByType:[1,1,2,2,4,4,4,2,3,4,8],stringCache:{},stringiCache:{},unpackAlignment:4,unpackRowLength:0,recordError:errorCode=>{if(!GL.lastError){GL.lastError=errorCode}},getNewId:table=>{var ret=GL.counter++;for(var i=table.length;i<ret;i++){table[i]=null}while(table[ret]){ret=GL.counter++}return ret},genObject:(n,buffers,createFunction,objectTable)=>{for(var i=0;i<n;i++){var buffer=GLctx[createFunction]();var id=buffer&&GL.getNewId(objectTable);if(buffer){buffer.name=id;objectTable[id]=buffer}else{GL.recordError(1282)}HEAP32[buffers+i*4>>2]=id}},MAX_TEMP_BUFFER_SIZE:2097152,numTempVertexBuffersPerSize:64,log2ceilLookup:i=>32-Math.clz32(i===0?0:i-1),generateTempBuffers:(quads,context)=>{var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);context.tempVertexBufferCounters1=[];context.tempVertexBufferCounters2=[];context.tempVertexBufferCounters1.length=context.tempVertexBufferCounters2.length=largestIndex+1;context.tempVertexBuffers1=[];context.tempVertexBuffers2=[];context.tempVertexBuffers1.length=context.tempVertexBuffers2.length=largestIndex+1;context.tempIndexBuffers=[];context.tempIndexBuffers.length=largestIndex+1;for(var i=0;i<=largestIndex;++i){context.tempIndexBuffers[i]=null;context.tempVertexBufferCounters1[i]=context.tempVertexBufferCounters2[i]=0;var ringbufferLength=GL.numTempVertexBuffersPerSize;context.tempVertexBuffers1[i]=[];context.tempVertexBuffers2[i]=[];var ringbuffer1=context.tempVertexBuffers1[i];var ringbuffer2=context.tempVertexBuffers2[i];ringbuffer1.length=ringbuffer2.length=ringbufferLength;for(var j=0;j<ringbufferLength;++j){ringbuffer1[j]=ringbuffer2[j]=null}}if(quads){context.tempQuadIndexBuffer=GLctx.createBuffer();context.GLctx.bindBuffer(34963,context.tempQuadIndexBuffer);var numIndexes=GL.MAX_TEMP_BUFFER_SIZE>>1;var quadIndexes=new Uint16Array(numIndexes);var i=0,v=0;while(1){quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+1;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v;if(i>=numIndexes)break;quadIndexes[i++]=v+2;if(i>=numIndexes)break;quadIndexes[i++]=v+3;if(i>=numIndexes)break;v+=4}context.GLctx.bufferData(34963,quadIndexes,35044);context.GLctx.bindBuffer(34963,null)}},getTempVertexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ringbuffer=GL.currentContext.tempVertexBuffers1[idx];var nextFreeBufferIndex=GL.currentContext.tempVertexBufferCounters1[idx];GL.currentContext.tempVertexBufferCounters1[idx]=GL.currentContext.tempVertexBufferCounters1[idx]+1&GL.numTempVertexBuffersPerSize-1;var vbo=ringbuffer[nextFreeBufferIndex];if(vbo){return vbo}var prevVBO=GLctx.getParameter(34964);ringbuffer[nextFreeBufferIndex]=GLctx.createBuffer();GLctx.bindBuffer(34962,ringbuffer[nextFreeBufferIndex]);GLctx.bufferData(34962,1<<idx,35048);GLctx.bindBuffer(34962,prevVBO);return ringbuffer[nextFreeBufferIndex]},getTempIndexBuffer:sizeBytes=>{var idx=GL.log2ceilLookup(sizeBytes);var ibo=GL.currentContext.tempIndexBuffers[idx];if(ibo){return ibo}var prevIBO=GLctx.getParameter(34965);GL.currentContext.tempIndexBuffers[idx]=GLctx.createBuffer();GLctx.bindBuffer(34963,GL.currentContext.tempIndexBuffers[idx]);GLctx.bufferData(34963,1<<idx,35048);GLctx.bindBuffer(34963,prevIBO);return GL.currentContext.tempIndexBuffers[idx]},newRenderingFrameStarted:()=>{if(!GL.currentContext){return}var vb=GL.currentContext.tempVertexBuffers1;GL.currentContext.tempVertexBuffers1=GL.currentContext.tempVertexBuffers2;GL.currentContext.tempVertexBuffers2=vb;vb=GL.currentContext.tempVertexBufferCounters1;GL.currentContext.tempVertexBufferCounters1=GL.currentContext.tempVertexBufferCounters2;GL.currentContext.tempVertexBufferCounters2=vb;var largestIndex=GL.log2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);for(var i=0;i<=largestIndex;++i){GL.currentContext.tempVertexBufferCounters1[i]=0}},getSource:(shader,count,string,length)=>{var source="";for(var i=0;i<count;++i){var len=length?HEAPU32[length+i*4>>2]:undefined;source+=UTF8ToString(HEAPU32[string+i*4>>2],len)}return source},calcBufLength:(size,type,stride,count)=>{if(stride>0){return count*stride}var typeSize=GL.byteSizeByType[type-GL.byteSizeByTypeRoot];return size*typeSize*count},usedTempBuffers:[],preDrawHandleClientVertexAttribBindings:count=>{GL.resetBufferBinding=false;for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(!cb.clientside||!cb.enabled)continue;GL.resetBufferBinding=true;var size=GL.calcBufLength(cb.size,cb.type,cb.stride,count);var buf=GL.getTempVertexBuffer(size);GLctx.bindBuffer(34962,buf);GLctx.bufferSubData(34962,0,HEAPU8.subarray(cb.ptr,cb.ptr+size));cb.vertexAttribPointerAdaptor.call(GLctx,i,cb.size,cb.type,cb.normalized,cb.stride,0)}},postDrawHandleClientVertexAttribBindings:()=>{if(GL.resetBufferBinding){GLctx.bindBuffer(34962,GL.buffers[GLctx.currentArrayBufferBinding])}},createContext:(canvas,webGLContextAttributes)=>{if(!canvas.getContextSafariWebGL2Fixed){canvas.getContextSafariWebGL2Fixed=canvas.getContext;function fixedGetContext(ver,attrs){var gl=canvas.getContextSafariWebGL2Fixed(ver,attrs);return ver=="webgl"==gl instanceof WebGLRenderingContext?gl:null}canvas.getContext=fixedGetContext}var ctx=webGLContextAttributes.majorVersion>1?canvas.getContext("webgl2",webGLContextAttributes):canvas.getContext("webgl",webGLContextAttributes);if(!ctx)return 0;var handle=GL.registerContext(ctx,webGLContextAttributes);return handle},registerContext:(ctx,webGLContextAttributes)=>{var handle=GL.getNewId(GL.contexts);var context={handle,attributes:webGLContextAttributes,version:webGLContextAttributes.majorVersion,GLctx:ctx};if(ctx.canvas)ctx.canvas.GLctxObject=context;GL.contexts[handle]=context;if(typeof webGLContextAttributes.enableExtensionsByDefault=="undefined"||webGLContextAttributes.enableExtensionsByDefault){GL.initExtensions(context)}context.maxVertexAttribs=context.GLctx.getParameter(34921);context.clientBuffers=[];for(var i=0;i<context.maxVertexAttribs;i++){context.clientBuffers[i]={enabled:false,clientside:false,size:0,type:0,normalized:0,stride:0,ptr:0,vertexAttribPointerAdaptor:null}}GL.generateTempBuffers(false,context);return handle},makeContextCurrent:contextHandle=>{GL.currentContext=GL.contexts[contextHandle];Module["ctx"]=GLctx=GL.currentContext?.GLctx;return!(contextHandle&&!GLctx)},getContext:contextHandle=>GL.contexts[contextHandle],deleteContext:contextHandle=>{if(GL.currentContext===GL.contexts[contextHandle]){GL.currentContext=null}if(typeof JSEvents=="object"){JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas)}if(GL.contexts[contextHandle]?.GLctx.canvas){GL.contexts[contextHandle].GLctx.canvas.GLctxObject=undefined}GL.contexts[contextHandle]=null},initExtensions:context=>{context||=GL.currentContext;if(context.initExtensionsDone)return;context.initExtensionsDone=true;var GLctx=context.GLctx;webgl_enable_WEBGL_multi_draw(GLctx);webgl_enable_EXT_polygon_offset_clamp(GLctx);webgl_enable_EXT_clip_control(GLctx);webgl_enable_WEBGL_polygon_mode(GLctx);webgl_enable_ANGLE_instanced_arrays(GLctx);webgl_enable_OES_vertex_array_object(GLctx);webgl_enable_WEBGL_draw_buffers(GLctx);webgl_enable_WEBGL_draw_instanced_base_vertex_base_instance(GLctx);webgl_enable_WEBGL_multi_draw_instanced_base_vertex_base_instance(GLctx);if(context.version>=2){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query_webgl2")}if(context.version<2||!GLctx.disjointTimerQueryExt){GLctx.disjointTimerQueryExt=GLctx.getExtension("EXT_disjoint_timer_query")}for(var ext of getEmscriptenSupportedExtensions(GLctx)){if(!ext.includes("lose_context")&&!ext.includes("debug")){GLctx.getExtension(ext)}}}};var webglPowerPreferences=["default","low-power","high-performance"];var maybeCStringToJsString=cString=>cString>2?UTF8ToString(cString):cString;var specialHTMLTargets=[0,globalThis.document??0,globalThis.window??0];var findEventTarget=target=>{target=maybeCStringToJsString(target);var domElement=specialHTMLTargets[target]||globalThis.document?.querySelector(target);return domElement};var findCanvasEventTarget=findEventTarget;var _emscripten_webgl_do_create_context=(target,attributes)=>{var attr32=attributes>>2;var powerPreference=HEAP32[attr32+(8>>2)];var contextAttributes={alpha:!!HEAP8[attributes+0],depth:!!HEAP8[attributes+1],stencil:!!HEAP8[attributes+2],antialias:!!HEAP8[attributes+3],premultipliedAlpha:!!HEAP8[attributes+4],preserveDrawingBuffer:!!HEAP8[attributes+5],powerPreference:webglPowerPreferences[powerPreference],failIfMajorPerformanceCaveat:!!HEAP8[attributes+12],majorVersion:HEAP32[attr32+(16>>2)],minorVersion:HEAP32[attr32+(20>>2)],enableExtensionsByDefault:HEAP8[attributes+24],explicitSwapControl:HEAP8[attributes+25],proxyContextToMainThread:HEAP32[attr32+(28>>2)],renderViaOffscreenBackBuffer:HEAP8[attributes+32]};var canvas=findCanvasEventTarget(target);if(!canvas){return 0}if(contextAttributes.explicitSwapControl){return 0}var contextHandle=GL.createContext(canvas,contextAttributes);return contextHandle};var _emscripten_webgl_create_context=_emscripten_webgl_do_create_context;var _emscripten_webgl_destroy_context=contextHandle=>{if(GL.currentContext==contextHandle)GL.currentContext=0;GL.deleteContext(contextHandle)};var _emscripten_webgl_make_context_current=contextHandle=>{var success=GL.makeContextCurrent(contextHandle);return success?0:-5};var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var _environ_get=(__environ,environ_buf)=>{var bufSize=0;var envp=0;for(var string of getEnvStrings()){var ptr=environ_buf+bufSize;HEAPU32[__environ+envp>>2]=ptr;bufSize+=stringToUTF8(string,ptr,Infinity)+1;envp+=4}return 0};var _environ_sizes_get=(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings();HEAPU32[penviron_count>>2]=strings.length;var bufSize=0;for(var string of strings){bufSize+=lengthBytesUTF8(string)+1}HEAPU32[penviron_buf_size>>2]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len)break;if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_read(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset,whence,newOffset){offset=bigintToI53Checked(offset);try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);HEAP64[newOffset>>3]=BigInt(stream.position);if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i<iovcnt;i++){var ptr=HEAPU32[iov>>2];var len=HEAPU32[iov+4>>2];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr<len){break}if(typeof offset!="undefined"){offset+=curr}}return ret};function _fd_write(fd,iov,iovcnt,pnum){try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>2]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var _emscripten_glActiveTexture=x0=>GLctx.activeTexture(x0);var _glActiveTexture=_emscripten_glActiveTexture;var _emscripten_glAttachShader=(program,shader)=>{GLctx.attachShader(GL.programs[program],GL.shaders[shader])};var _glAttachShader=_emscripten_glAttachShader;var _emscripten_glBindAttribLocation=(program,index,name)=>{GLctx.bindAttribLocation(GL.programs[program],index,UTF8ToString(name))};var _glBindAttribLocation=_emscripten_glBindAttribLocation;var _emscripten_glBindBuffer=(target,buffer)=>{if(buffer&&!GL.buffers[buffer]){var b=GLctx.createBuffer();b.name=buffer;GL.buffers[buffer]=b}if(target==34962){GLctx.currentArrayBufferBinding=buffer}else if(target==34963){GLctx.currentElementArrayBufferBinding=buffer}if(target==35051){GLctx.currentPixelPackBufferBinding=buffer}else if(target==35052){GLctx.currentPixelUnpackBufferBinding=buffer}GLctx.bindBuffer(target,GL.buffers[buffer])};var _glBindBuffer=_emscripten_glBindBuffer;var _emscripten_glBindFramebuffer=(target,framebuffer)=>{GLctx.bindFramebuffer(target,GL.framebuffers[framebuffer])};var _glBindFramebuffer=_emscripten_glBindFramebuffer;var _emscripten_glBindTexture=(target,texture)=>{GLctx.bindTexture(target,GL.textures[texture])};var _glBindTexture=_emscripten_glBindTexture;var _emscripten_glBindVertexArray=vao=>{GLctx.bindVertexArray(GL.vaos[vao]);var ibo=GLctx.getParameter(34965);GLctx.currentElementArrayBufferBinding=ibo?ibo.name|0:0};var _glBindVertexArray=_emscripten_glBindVertexArray;var _emscripten_glBlendFunc=(x0,x1)=>GLctx.blendFunc(x0,x1);var _glBlendFunc=_emscripten_glBlendFunc;var _emscripten_glBlendFuncSeparate=(x0,x1,x2,x3)=>GLctx.blendFuncSeparate(x0,x1,x2,x3);var _glBlendFuncSeparate=_emscripten_glBlendFuncSeparate;var _emscripten_glBufferData=(target,size,data,usage)=>{if(GL.currentContext.version>=2){if(data&&size){GLctx.bufferData(target,HEAPU8,usage,data,size)}else{GLctx.bufferData(target,size,usage)}return}GLctx.bufferData(target,data?HEAPU8.subarray(data,data+size):size,usage)};var _glBufferData=_emscripten_glBufferData;var _emscripten_glBufferSubData=(target,offset,size,data)=>{if(GL.currentContext.version>=2){size&&GLctx.bufferSubData(target,offset,HEAPU8,data,size);return}GLctx.bufferSubData(target,offset,HEAPU8.subarray(data,data+size))};var _glBufferSubData=_emscripten_glBufferSubData;var _emscripten_glCheckFramebufferStatus=x0=>GLctx.checkFramebufferStatus(x0);var _glCheckFramebufferStatus=_emscripten_glCheckFramebufferStatus;var _emscripten_glClear=x0=>GLctx.clear(x0);var _glClear=_emscripten_glClear;var _emscripten_glClearColor=(x0,x1,x2,x3)=>GLctx.clearColor(x0,x1,x2,x3);var _glClearColor=_emscripten_glClearColor;var _emscripten_glCompileShader=shader=>{GLctx.compileShader(GL.shaders[shader])};var _glCompileShader=_emscripten_glCompileShader;var _emscripten_glCreateProgram=()=>{var id=GL.getNewId(GL.programs);var program=GLctx.createProgram();program.name=id;program.maxUniformLength=program.maxAttributeLength=program.maxUniformBlockNameLength=0;program.uniformIdCounter=1;GL.programs[id]=program;return id};var _glCreateProgram=_emscripten_glCreateProgram;var _emscripten_glCreateShader=shaderType=>{var id=GL.getNewId(GL.shaders);GL.shaders[id]=GLctx.createShader(shaderType);return id};var _glCreateShader=_emscripten_glCreateShader;var _emscripten_glDeleteBuffers=(n,buffers)=>{for(var i=0;i<n;i++){var id=HEAP32[buffers+i*4>>2];var buffer=GL.buffers[id];if(!buffer)continue;GLctx.deleteBuffer(buffer);buffer.name=0;GL.buffers[id]=null;if(id==GLctx.currentArrayBufferBinding)GLctx.currentArrayBufferBinding=0;if(id==GLctx.currentElementArrayBufferBinding)GLctx.currentElementArrayBufferBinding=0;if(id==GLctx.currentPixelPackBufferBinding)GLctx.currentPixelPackBufferBinding=0;if(id==GLctx.currentPixelUnpackBufferBinding)GLctx.currentPixelUnpackBufferBinding=0}};var _glDeleteBuffers=_emscripten_glDeleteBuffers;var _emscripten_glDeleteFramebuffers=(n,framebuffers)=>{for(var i=0;i<n;++i){var id=HEAP32[framebuffers+i*4>>2];var framebuffer=GL.framebuffers[id];if(!framebuffer)continue;GLctx.deleteFramebuffer(framebuffer);framebuffer.name=0;GL.framebuffers[id]=null}};var _glDeleteFramebuffers=_emscripten_glDeleteFramebuffers;var _emscripten_glDeleteProgram=id=>{if(!id)return;var program=GL.programs[id];if(!program){GL.recordError(1281);return}GLctx.deleteProgram(program);program.name=0;GL.programs[id]=null};var _glDeleteProgram=_emscripten_glDeleteProgram;var _emscripten_glDeleteShader=id=>{if(!id)return;var shader=GL.shaders[id];if(!shader){GL.recordError(1281);return}GLctx.deleteShader(shader);GL.shaders[id]=null};var _glDeleteShader=_emscripten_glDeleteShader;var _emscripten_glDeleteTextures=(n,textures)=>{for(var i=0;i<n;i++){var id=HEAP32[textures+i*4>>2];var texture=GL.textures[id];if(!texture)continue;GLctx.deleteTexture(texture);texture.name=0;GL.textures[id]=null}};var _glDeleteTextures=_emscripten_glDeleteTextures;var _emscripten_glDeleteVertexArrays=(n,vaos)=>{for(var i=0;i<n;i++){var id=HEAP32[vaos+i*4>>2];GLctx.deleteVertexArray(GL.vaos[id]);GL.vaos[id]=null}};var _glDeleteVertexArrays=_emscripten_glDeleteVertexArrays;var _emscripten_glDisable=x0=>GLctx.disable(x0);var _glDisable=_emscripten_glDisable;var _emscripten_glDisableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=false;GLctx.disableVertexAttribArray(index)};var _glDisableVertexAttribArray=_emscripten_glDisableVertexAttribArray;var _emscripten_glDrawArrays=(mode,first,count)=>{GL.preDrawHandleClientVertexAttribBindings(first+count);GLctx.drawArrays(mode,first,count);GL.postDrawHandleClientVertexAttribBindings()};var _glDrawArrays=_emscripten_glDrawArrays;var _emscripten_glDrawElements=(mode,count,type,indices)=>{var buf;var vertexes=0;if(!GLctx.currentElementArrayBufferBinding){var size=GL.calcBufLength(1,type,0,count);buf=GL.getTempIndexBuffer(size);GLctx.bindBuffer(34963,buf);GLctx.bufferSubData(34963,0,HEAPU8.subarray(indices,indices+size));if(count>0){for(var i=0;i<GL.currentContext.maxVertexAttribs;++i){var cb=GL.currentContext.clientBuffers[i];if(cb.clientside&&cb.enabled){let arrayClass;switch(type){case 5121:arrayClass=Uint8Array;break;case 5123:arrayClass=Uint16Array;break;case 5125:arrayClass=Uint32Array;break;default:GL.recordError(1282);return}vertexes=new arrayClass(HEAPU8.buffer,indices,count).reduce((max,current)=>Math.max(max,current))+1;break}}}indices=0}GL.preDrawHandleClientVertexAttribBindings(vertexes);GLctx.drawElements(mode,count,type,indices);GL.postDrawHandleClientVertexAttribBindings(count);if(!GLctx.currentElementArrayBufferBinding){GLctx.bindBuffer(34963,null)}};var _glDrawElements=_emscripten_glDrawElements;var _emscripten_glEnable=x0=>GLctx.enable(x0);var _glEnable=_emscripten_glEnable;var _emscripten_glEnableVertexAttribArray=index=>{var cb=GL.currentContext.clientBuffers[index];cb.enabled=true;GLctx.enableVertexAttribArray(index)};var _glEnableVertexAttribArray=_emscripten_glEnableVertexAttribArray;var _emscripten_glFramebufferTexture2D=(target,attachment,textarget,texture,level)=>{GLctx.framebufferTexture2D(target,attachment,textarget,GL.textures[texture],level)};var _glFramebufferTexture2D=_emscripten_glFramebufferTexture2D;var _emscripten_glGenBuffers=(n,buffers)=>{GL.genObject(n,buffers,"createBuffer",GL.buffers)};var _glGenBuffers=_emscripten_glGenBuffers;var _emscripten_glGenFramebuffers=(n,ids)=>{GL.genObject(n,ids,"createFramebuffer",GL.framebuffers)};var _glGenFramebuffers=_emscripten_glGenFramebuffers;var _emscripten_glGenTextures=(n,textures)=>{GL.genObject(n,textures,"createTexture",GL.textures)};var _glGenTextures=_emscripten_glGenTextures;var _emscripten_glGenVertexArrays=(n,arrays)=>{GL.genObject(n,arrays,"createVertexArray",GL.vaos)};var _glGenVertexArrays=_emscripten_glGenVertexArrays;var _emscripten_glGenerateMipmap=x0=>GLctx.generateMipmap(x0);var _glGenerateMipmap=_emscripten_glGenerateMipmap;var _emscripten_glGetAttribLocation=(program,name)=>GLctx.getAttribLocation(GL.programs[program],UTF8ToString(name));var _glGetAttribLocation=_emscripten_glGetAttribLocation;var _emscripten_glGetError=()=>{var error=GLctx.getError()||GL.lastError;GL.lastError=0;return error};var _glGetError=_emscripten_glGetError;var writeI53ToI64=(ptr,num)=>{HEAPU32[ptr>>2]=num;var lower=HEAPU32[ptr>>2];HEAPU32[ptr+4>>2]=(num-lower)/4294967296};var webglGetExtensions=()=>{var exts=getEmscriptenSupportedExtensions(GLctx);exts=exts.concat(exts.map(e=>"GL_"+e));return exts};var emscriptenWebGLGet=(name_,p,type)=>{if(!p){GL.recordError(1281);return}var ret=undefined;switch(name_){case 36346:ret=1;break;case 36344:if(type!=0&&type!=1){GL.recordError(1280)}return;case 34814:case 36345:ret=0;break;case 34466:var formats=GLctx.getParameter(34467);ret=formats?formats.length:0;break;case 33309:if(GL.currentContext.version<2){GL.recordError(1282);return}ret=webglGetExtensions().length;break;case 33307:case 33308:if(GL.currentContext.version<2){GL.recordError(1280);return}ret=name_==33307?3:0;break}if(ret===undefined){var result=GLctx.getParameter(name_);switch(typeof result){case"number":ret=result;break;case"boolean":ret=result?1:0;break;case"string":GL.recordError(1280);return;case"object":if(result===null){switch(name_){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 36662:case 36663:case 35053:case 35055:case 36010:case 35097:case 35869:case 32874:case 36389:case 35983:case 35368:case 34068:{ret=0;break}default:{GL.recordError(1280);return}}}else if(result instanceof Float32Array||result instanceof Uint32Array||result instanceof Int32Array||result instanceof Array){for(var i=0;i<result.length;++i){switch(type){case 0:HEAP32[p+i*4>>2]=result[i];break;case 2:HEAPF32[p+i*4>>2]=result[i];break;case 4:HEAP8[p+i]=result[i]?1:0;break}}return}else{try{ret=result.name|0}catch(e){GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Unknown object returned from WebGL getParameter(${name_})! (error: ${e})`);return}}break;default:GL.recordError(1280);err(`GL_INVALID_ENUM in glGet${type}v: Native code calling glGet${type}v(${name_}) and it returns ${result} of type ${typeof result}!`);return}}switch(type){case 1:writeI53ToI64(p,ret);break;case 0:HEAP32[p>>2]=ret;break;case 2:HEAPF32[p>>2]=ret;break;case 4:HEAP8[p]=ret?1:0;break}};var _emscripten_glGetIntegerv=(name_,p)=>emscriptenWebGLGet(name_,p,0);var _glGetIntegerv=_emscripten_glGetIntegerv;var _emscripten_glGetProgramInfoLog=(program,maxLength,length,infoLog)=>{var log=GLctx.getProgramInfoLog(GL.programs[program]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetProgramInfoLog=_emscripten_glGetProgramInfoLog;var _emscripten_glGetProgramiv=(program,pname,p)=>{if(!p){GL.recordError(1281);return}if(program>=GL.counter){GL.recordError(1281);return}program=GL.programs[program];if(pname==35716){var log=GLctx.getProgramInfoLog(program);if(log===null)log="(unknown error)";HEAP32[p>>2]=log.length+1}else if(pname==35719){if(!program.maxUniformLength){var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(var i=0;i<numActiveUniforms;++i){program.maxUniformLength=Math.max(program.maxUniformLength,GLctx.getActiveUniform(program,i).name.length+1)}}HEAP32[p>>2]=program.maxUniformLength}else if(pname==35722){if(!program.maxAttributeLength){var numActiveAttributes=GLctx.getProgramParameter(program,35721);for(var i=0;i<numActiveAttributes;++i){program.maxAttributeLength=Math.max(program.maxAttributeLength,GLctx.getActiveAttrib(program,i).name.length+1)}}HEAP32[p>>2]=program.maxAttributeLength}else if(pname==35381){if(!program.maxUniformBlockNameLength){var numActiveUniformBlocks=GLctx.getProgramParameter(program,35382);for(var i=0;i<numActiveUniformBlocks;++i){program.maxUniformBlockNameLength=Math.max(program.maxUniformBlockNameLength,GLctx.getActiveUniformBlockName(program,i).length+1)}}HEAP32[p>>2]=program.maxUniformBlockNameLength}else{HEAP32[p>>2]=GLctx.getProgramParameter(program,pname)}};var _glGetProgramiv=_emscripten_glGetProgramiv;var _emscripten_glGetShaderInfoLog=(shader,maxLength,length,infoLog)=>{var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var numBytesWrittenExclNull=maxLength>0&&infoLog?stringToUTF8(log,infoLog,maxLength):0;if(length)HEAP32[length>>2]=numBytesWrittenExclNull};var _glGetShaderInfoLog=_emscripten_glGetShaderInfoLog;var _emscripten_glGetShaderiv=(shader,pname,p)=>{if(!p){GL.recordError(1281);return}if(pname==35716){var log=GLctx.getShaderInfoLog(GL.shaders[shader]);if(log===null)log="(unknown error)";var logLength=log?log.length+1:0;HEAP32[p>>2]=logLength}else if(pname==35720){var source=GLctx.getShaderSource(GL.shaders[shader]);var sourceLength=source?source.length+1:0;HEAP32[p>>2]=sourceLength}else{HEAP32[p>>2]=GLctx.getShaderParameter(GL.shaders[shader],pname)}};var _glGetShaderiv=_emscripten_glGetShaderiv;var stringToNewUTF8=str=>{var size=lengthBytesUTF8(str)+1;var ret=_malloc(size);if(ret)stringToUTF8(str,ret,size);return ret};var _emscripten_glGetString=name_=>{var ret=GL.stringCache[name_];if(!ret){switch(name_){case 7939:ret=stringToNewUTF8(webglGetExtensions().join(" "));break;case 7936:case 7937:case 37445:case 37446:var s=GLctx.getParameter(name_);if(!s){GL.recordError(1280)}ret=s?stringToNewUTF8(s):0;break;case 7938:var webGLVersion=GLctx.getParameter(7938);var glVersion=`OpenGL ES 2.0 (${webGLVersion})`;if(GL.currentContext.version>=2)glVersion=`OpenGL ES 3.0 (${webGLVersion})`;ret=stringToNewUTF8(glVersion);break;case 35724:var glslVersion=GLctx.getParameter(35724);var ver_re=/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/;var ver_num=glslVersion.match(ver_re);if(ver_num!==null){if(ver_num[1].length==3)ver_num[1]=ver_num[1]+"0";glslVersion=`OpenGL ES GLSL ES ${ver_num[1]} (${glslVersion})`}ret=stringToNewUTF8(glslVersion);break;default:GL.recordError(1280)}GL.stringCache[name_]=ret}return ret};var _glGetString=_emscripten_glGetString;var jstoi_q=str=>parseInt(str);var webglGetLeftBracePos=name=>name.slice(-1)=="]"&&name.lastIndexOf("[");var webglPrepareUniformLocationsBeforeFirstUse=program=>{var uniformLocsById=program.uniformLocsById,uniformSizeAndIdsByName=program.uniformSizeAndIdsByName,i,j;if(!uniformLocsById){program.uniformLocsById=uniformLocsById={};program.uniformArrayNamesById={};var numActiveUniforms=GLctx.getProgramParameter(program,35718);for(i=0;i<numActiveUniforms;++i){var u=GLctx.getActiveUniform(program,i);var nm=u.name;var sz=u.size;var lb=webglGetLeftBracePos(nm);var arrayName=lb>0?nm.slice(0,lb):nm;var id=program.uniformIdCounter;program.uniformIdCounter+=sz;uniformSizeAndIdsByName[arrayName]=[sz,id];for(j=0;j<sz;++j){uniformLocsById[id]=j;program.uniformArrayNamesById[id++]=arrayName}}}};var _emscripten_glGetUniformLocation=(program,name)=>{name=UTF8ToString(name);if(program=GL.programs[program]){webglPrepareUniformLocationsBeforeFirstUse(program);var uniformLocsById=program.uniformLocsById;var arrayIndex=0;var uniformBaseName=name;var leftBrace=webglGetLeftBracePos(name);if(leftBrace>0){arrayIndex=jstoi_q(name.slice(leftBrace+1))>>>0;uniformBaseName=name.slice(0,leftBrace)}var sizeAndId=program.uniformSizeAndIdsByName[uniformBaseName];if(sizeAndId&&arrayIndex<sizeAndId[0]){arrayIndex+=sizeAndId[1];if(uniformLocsById[arrayIndex]=uniformLocsById[arrayIndex]||GLctx.getUniformLocation(program,name)){return arrayIndex}}}else{GL.recordError(1281)}return-1};var _glGetUniformLocation=_emscripten_glGetUniformLocation;var _emscripten_glLinkProgram=program=>{program=GL.programs[program];GLctx.linkProgram(program);program.uniformLocsById=0;program.uniformSizeAndIdsByName={}};var _glLinkProgram=_emscripten_glLinkProgram;var _emscripten_glPixelStorei=(pname,param)=>{if(pname==3317){GL.unpackAlignment=param}else if(pname==3314){GL.unpackRowLength=param}GLctx.pixelStorei(pname,param)};var _glPixelStorei=_emscripten_glPixelStorei;var _emscripten_glScissor=(x0,x1,x2,x3)=>GLctx.scissor(x0,x1,x2,x3);var _glScissor=_emscripten_glScissor;var _emscripten_glShaderSource=(shader,count,string,length)=>{var source=GL.getSource(shader,count,string,length);GLctx.shaderSource(GL.shaders[shader],source)};var _glShaderSource=_emscripten_glShaderSource;var computeUnpackAlignedImageSize=(width,height,sizePerPixel)=>{function roundedToNextMultipleOf(x,y){return x+y-1&-y}var plainRowSize=(GL.unpackRowLength||width)*sizePerPixel;var alignedRowSize=roundedToNextMultipleOf(plainRowSize,GL.unpackAlignment);return height*alignedRowSize};var colorChannelsInGlTextureFormat=format=>{var colorChannels={5:3,6:4,8:2,29502:3,29504:4,26917:2,26918:2,29846:3,29847:4};return colorChannels[format-6402]||1};var heapObjectForWebGLType=type=>{type-=5120;if(type==0)return HEAP8;if(type==1)return HEAPU8;if(type==2)return HEAP16;if(type==4)return HEAP32;if(type==6)return HEAPF32;if(type==5||type==28922||type==28520||type==30779||type==30782)return HEAPU32;return HEAPU16};var toTypedArrayIndex=(pointer,heap)=>pointer>>>31-Math.clz32(heap.BYTES_PER_ELEMENT);var emscriptenWebGLGetTexPixelData=(type,format,width,height,pixels,internalFormat)=>{var heap=heapObjectForWebGLType(type);var sizePerPixel=colorChannelsInGlTextureFormat(format)*heap.BYTES_PER_ELEMENT;var bytes=computeUnpackAlignedImageSize(width,height,sizePerPixel);return heap.subarray(toTypedArrayIndex(pixels,heap),toTypedArrayIndex(pixels+bytes,heap))};var _emscripten_glTexImage2D=(target,level,internalFormat,width,height,border,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);var index=toTypedArrayIndex(pixels,heap);GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,heap,index);return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,internalFormat):null;GLctx.texImage2D(target,level,internalFormat,width,height,border,format,type,pixelData)};var _glTexImage2D=_emscripten_glTexImage2D;var _emscripten_glTexParameteri=(x0,x1,x2)=>GLctx.texParameteri(x0,x1,x2);var _glTexParameteri=_emscripten_glTexParameteri;var _emscripten_glTexSubImage2D=(target,level,xoffset,yoffset,width,height,format,type,pixels)=>{if(GL.currentContext.version>=2){if(GLctx.currentPixelUnpackBufferBinding){GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixels);return}if(pixels){var heap=heapObjectForWebGLType(type);GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,heap,toTypedArrayIndex(pixels,heap));return}}var pixelData=pixels?emscriptenWebGLGetTexPixelData(type,format,width,height,pixels,0):null;GLctx.texSubImage2D(target,level,xoffset,yoffset,width,height,format,type,pixelData)};var _glTexSubImage2D=_emscripten_glTexSubImage2D;var webglGetUniformLocation=location=>{var p=GLctx.currentProgram;if(p){var webglLoc=p.uniformLocsById[location];if(typeof webglLoc=="number"){p.uniformLocsById[location]=webglLoc=GLctx.getUniformLocation(p,p.uniformArrayNamesById[location]+(webglLoc>0?`[${webglLoc}]`:""))}return webglLoc}else{GL.recordError(1282)}};var _emscripten_glUniform1f=(location,v0)=>{GLctx.uniform1f(webglGetUniformLocation(location),v0)};var _glUniform1f=_emscripten_glUniform1f;var _emscripten_glUniform1i=(location,v0)=>{GLctx.uniform1i(webglGetUniformLocation(location),v0)};var _glUniform1i=_emscripten_glUniform1i;var _emscripten_glUniform2f=(location,v0,v1)=>{GLctx.uniform2f(webglGetUniformLocation(location),v0,v1)};var _glUniform2f=_emscripten_glUniform2f;var _emscripten_glUniform3f=(location,v0,v1,v2)=>{GLctx.uniform3f(webglGetUniformLocation(location),v0,v1,v2)};var _glUniform3f=_emscripten_glUniform3f;var _emscripten_glUniform4f=(location,v0,v1,v2,v3)=>{GLctx.uniform4f(webglGetUniformLocation(location),v0,v1,v2,v3)};var _glUniform4f=_emscripten_glUniform4f;var miniTempWebGLFloatBuffers=[];var _emscripten_glUniformMatrix4fv=(location,count,transpose,value)=>{if(GL.currentContext.version>=2){count&&GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,HEAPF32,value>>2,count*16);return}if(count<=18){var view=miniTempWebGLFloatBuffers[16*count];var heap=HEAPF32;value=value>>2;count*=16;for(var i=0;i<count;i+=16){var dst=value+i;view[i]=heap[dst];view[i+1]=heap[dst+1];view[i+2]=heap[dst+2];view[i+3]=heap[dst+3];view[i+4]=heap[dst+4];view[i+5]=heap[dst+5];view[i+6]=heap[dst+6];view[i+7]=heap[dst+7];view[i+8]=heap[dst+8];view[i+9]=heap[dst+9];view[i+10]=heap[dst+10];view[i+11]=heap[dst+11];view[i+12]=heap[dst+12];view[i+13]=heap[dst+13];view[i+14]=heap[dst+14];view[i+15]=heap[dst+15]}}else{var view=HEAPF32.subarray(value>>2,value+count*64>>2)}GLctx.uniformMatrix4fv(webglGetUniformLocation(location),!!transpose,view)};var _glUniformMatrix4fv=_emscripten_glUniformMatrix4fv;var _emscripten_glUseProgram=program=>{program=GL.programs[program];GLctx.useProgram(program);GLctx.currentProgram=program};var _glUseProgram=_emscripten_glUseProgram;var _emscripten_glVertexAttribPointer=(index,size,type,normalized,stride,ptr)=>{var cb=GL.currentContext.clientBuffers[index];if(!GLctx.currentArrayBufferBinding){cb.size=size;cb.type=type;cb.normalized=normalized;cb.stride=stride;cb.ptr=ptr;cb.clientside=true;cb.vertexAttribPointerAdaptor=function(index,size,type,normalized,stride,ptr){this.vertexAttribPointer(index,size,type,normalized,stride,ptr)};return}cb.clientside=false;GLctx.vertexAttribPointer(index,size,type,!!normalized,stride,ptr)};var _glVertexAttribPointer=_emscripten_glVertexAttribPointer;var _emscripten_glViewport=(x0,x1,x2,x3)=>GLctx.viewport(x0,x1,x2,x3);var _glViewport=_emscripten_glViewport;var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer)};var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func(...cArgs);function onDone(ret){if(stack!==0)stackRestore(stack);return convertReturnValue(ret)}ret=onDone(ret);return ret};var cwrap=(ident,returnType,argTypes,opts)=>{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=(...args)=>FS.createPath(...args);var FS_unlink=(...args)=>FS.unlink(...args);var FS_createLazyFile=(...args)=>FS.createLazyFile(...args);var FS_createDevice=(...args)=>FS.createDevice(...args);FS.createPreloadedFile=FS_createPreloadedFile;FS.preloadFile=FS_preloadFile;FS.staticInit();init_ClassHandle();init_RegisteredPointer();registerPreMainLoop(()=>GL.newRenderingFrameStarted());var miniTempWebGLFloatBuffersStorage=new Float32Array(288);for(var i=0;i<=288;++i){miniTempWebGLFloatBuffers[i]=miniTempWebGLFloatBuffersStorage.subarray(0,i)}{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["preloadPlugins"])preloadPlugins=Module["preloadPlugins"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].shift()()}}}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["FS_preloadFile"]=FS_preloadFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS"]=FS;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;Module["GL"]=GL;function callMaterialProvider(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr){var fn=Module["materialDataProvider"];if(fn){fn(materialId,outShaderIdPtr,outBlendModePtr,outUniformBufPtr,outUniformCountPtr)}else{HEAPU32[outShaderIdPtr>>2]=0;HEAPU32[outBlendModePtr>>2]=0;HEAPU32[outUniformBufPtr>>2]=0;HEAPU32[outUniformCountPtr>>2]=0}}var ___getTypeName,_malloc,_free,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){___getTypeName=wasmExports["Za"];_malloc=Module["_malloc"]=wasmExports["$a"];_free=Module["_free"]=wasmExports["ab"];__emscripten_stack_restore=wasmExports["bb"];__emscripten_stack_alloc=wasmExports["cb"];_emscripten_stack_get_current=wasmExports["db"];memory=wasmMemory=wasmExports["Xa"];__indirect_function_table=wasmTable=wasmExports["_a"]}var wasmImports={aa:___syscall_fcntl64,va:___syscall_ioctl,wa:___syscall_openat,za:__abort_js,g:__embind_finalize_value_object,pa:__embind_register_bigint,Qa:__embind_register_bool,qa:__embind_register_class,Na:__embind_register_class_constructor,c:__embind_register_class_function,Oa:__embind_register_emval,Q:__embind_register_enum,n:__embind_register_enum_value,oa:__embind_register_float,b:__embind_register_function,w:__embind_register_integer,i:__embind_register_memory_view,Pa:__embind_register_std_string,V:__embind_register_std_wstring,h:__embind_register_value_object,a:__embind_register_value_object_field,Ra:__embind_register_void,I:__emval_create_invoker,G:__emval_decref,H:__emval_invoke,ra:__emval_new_array,ga:__emval_new_cstring,ja:__emval_new_object,T:__emval_run_destructors,_:__emval_set_property,Sa:__tzset_js,Wa:callMaterialProvider,xa:_clock_time_get,ya:_emscripten_resize_heap,Va:_emscripten_webgl_create_context,Ma:_emscripten_webgl_destroy_context,sa:_emscripten_webgl_make_context_current,Ta:_environ_get,Ua:_environ_sizes_get,$:_fd_close,ta:_fd_read,ua:_fd_seek,ba:_fd_write,e:_glActiveTexture,ha:_glAttachShader,q:_glBindAttribLocation,f:_glBindBuffer,B:_glBindFramebuffer,d:_glBindTexture,m:_glBindVertexArray,Y:_glBlendFunc,y:_glBlendFuncSeparate,t:_glBufferData,z:_glBufferSubData,Aa:_glCheckFramebufferStatus,E:_glClear,R:_glClearColor,ka:_glCompileShader,La:_glCreateProgram,ma:_glCreateShader,v:_glDeleteBuffers,da:_glDeleteFramebuffers,na:_glDeleteProgram,A:_glDeleteShader,D:_glDeleteTextures,J:_glDeleteVertexArrays,r:_glDisable,U:_glDisableVertexAttribArray,Z:_glDrawArrays,C:_glDrawElements,s:_glEnable,o:_glEnableVertexAttribArray,ca:_glFramebufferTexture2D,u:_glGenBuffers,Ba:_glGenFramebuffers,P:_glGenTextures,K:_glGenVertexArrays,Ca:_glGenerateMipmap,Da:_glGetAttribLocation,l:_glGetError,W:_glGetIntegerv,Ka:_glGetProgramInfoLog,M:_glGetProgramiv,ia:_glGetShaderInfoLog,L:_glGetShaderiv,S:_glGetString,x:_glGetUniformLocation,N:_glLinkProgram,fa:_glPixelStorei,X:_glScissor,la:_glShaderSource,O:_glTexImage2D,p:_glTexParameteri,ea:_glTexSubImage2D,Ia:_glUniform1f,j:_glUniform1i,Ha:_glUniform2f,Ga:_glUniform3f,Fa:_glUniform4f,Ea:_glUniformMatrix4fv,Ja:_glUseProgram,k:_glVertexAttribPointer,F:_glViewport};function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve?.(Module);Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}var wasmExports;wasmExports=await (createWasm());run();if(runtimeInitialized){moduleRtn=Module}else{moduleRtn=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject})}
;return moduleRtn}})();if(typeof exports==="object"&&typeof module==="object"){module.exports=ESEngineModule;module.exports.default=ESEngineModule}else if(typeof define==="function"&&define["amd"])define([],()=>ESEngineModule);
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index f4266170b..fbe9c3c37 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -70,6 +70,8 @@ export class SceneViewPanel {
private colliderOverlay_: ColliderOverlay;
private keydownHandler_: ((e: KeyboardEvent) => void) | null = null;
private skipNextClick_ = false;
+ private mouseDownX_ = 0;
+ private mouseDownY_ = 0;
private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;
private boundOnDocumentMouseUp_: ((e: MouseEvent) => void) | null = null;
@@ -94,6 +96,20 @@ export class SceneViewPanel {
};
}
}
+
+ const hasBitmapText = entityData.components.some(c => c.type === 'BitmapText');
+ if (hasBitmapText && this.sceneRenderer_) {
+ const textBounds = this.sceneRenderer_.getBitmapTextBounds(entityData.id);
+ if (textBounds) {
+ return {
+ width: textBounds.width,
+ height: textBounds.height,
+ offsetX: textBounds.offsetX,
+ offsetY: textBounds.offsetY,
+ };
+ }
+ }
+
return getEntityBounds(entityData.components);
}
@@ -574,6 +590,9 @@ export class SceneViewPanel {
if (e.button !== 0) return;
+ this.mouseDownX_ = e.clientX;
+ this.mouseDownY_ = e.clientY;
+
const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);
if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null &&
@@ -674,6 +693,10 @@ export class SceneViewPanel {
}
private onMouseUp(_e: MouseEvent): void {
+ const dx = _e.clientX - this.mouseDownX_;
+ const dy = _e.clientY - this.mouseDownY_;
+ const didMove = dx * dx + dy * dy > 9;
+
if (this.isDragging_) {
this.isDragging_ = false;
this.canvas_.style.cursor = 'default';
@@ -684,7 +707,7 @@ export class SceneViewPanel {
const { worldX, worldY } = this.screenToWorld(_e.clientX, _e.clientY);
this.updateGizmoContext();
this.gizmoManager_.onMouseUp(worldX, worldY);
- this.skipNextClick_ = true;
+ this.skipNextClick_ = didMove;
}
if (this.colliderOverlay_.isDragging()) {
@@ -692,7 +715,7 @@ export class SceneViewPanel {
if (octx) {
this.colliderOverlay_.onDragEnd(octx);
}
- this.skipNextClick_ = true;
+ this.skipNextClick_ = didMove;
}
}
@@ -720,8 +743,16 @@ export class SceneViewPanel {
if (result.hit) return;
}
- const entity = this.findEntityAtPosition(worldX, worldY);
- this.store_.selectEntity(entity);
+ const hits = this.findEntitiesAtPosition(worldX, worldY);
+ if (hits.length === 0) {
+ this.store_.selectEntity(null);
+ return;
+ }
+
+ const current = this.store_.selectedEntity;
+ const idx = current !== null ? hits.indexOf(current as Entity) : -1;
+ const next = idx >= 0 ? hits[(idx + 1) % hits.length] : hits[0];
+ this.store_.selectEntity(next);
}
private focusOnEntity(entityId: number): void {
@@ -768,8 +799,9 @@ export class SceneViewPanel {
this.requestRender();
}
- private findEntityAtPosition(worldX: number, worldY: number): Entity | null {
+ private findEntitiesAtPosition(worldX: number, worldY: number): Entity[] {
const scene = this.store_.scene;
+ const result: Entity[] = [];
for (let i = scene.entities.length - 1; i >= 0; i--) {
const entity = scene.entities[i];
@@ -800,11 +832,11 @@ export class SceneViewPanel {
worldY >= centerY - halfH &&
worldY <= centerY + halfH
) {
- return entity.id as Entity;
+ result.push(entity.id as Entity);
}
}
- return null;
+ return result;
}
private updateZoomDisplay(): void {
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index 5edb609bb..c1873db1b 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -166,6 +166,10 @@ export class EditorSceneRenderer {
return { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height };
}
+ getBitmapTextBounds(entityId: number): { width: number; height: number; offsetX: number; offsetY: number } | null {
+ return this.sceneManager_?.getBitmapTextBounds(entityId) ?? null;
+ }
+
getSpineSkeletonInfo(entityId: number): { animations: string[]; skins: string[] } | null {
return this.sceneManager_?.getSpineSkeletonInfo(entityId) ?? null;
}
@@ -181,6 +185,7 @@ export class EditorSceneRenderer {
render(width: number, height: number): void {
if (!this.pipeline_ || !this.sceneManager_ || !this.initialized_) return;
if (width <= 0 || height <= 0) return;
+ if (this.sceneManager_.isBusy) return;
const bg = this.findCanvasBackgroundColor();
Renderer.setClearColor(bg.r, bg.g, bg.b, bg.a);
@@ -188,15 +193,28 @@ export class EditorSceneRenderer {
const matrix = this.camera_.getViewProjection(width, height);
const elapsed = (performance.now() - this.startTime_) / 1000;
+ const cppReg = this.sceneManager_.registry;
+ const registry = { _cpp: cppReg };
+
try {
- this.pipeline_.render({
- registry: { _cpp: this.sceneManager_.registry },
- viewProjection: matrix,
- width, height, elapsed,
- });
+ Renderer.setViewport(0, 0, width, height);
+ Renderer.clearBuffers(3);
+ Renderer.begin(matrix);
+ if (this.pipeline_.maskProcessor) {
+ this.pipeline_.maskProcessor(registry._cpp, matrix, 0, 0, width, height);
+ }
+ Renderer.submitSprites(registry);
+ Renderer.submitBitmapText(registry);
+ if (this.pipeline_.spineRenderer) {
+ this.pipeline_.spineRenderer(registry, elapsed);
+ } else {
+ Renderer.submitSpine(registry);
+ }
+ Renderer.flush();
+ Renderer.end();
} catch (e) {
if (e instanceof WebAssembly.RuntimeError) {
- console.warn('[EditorSceneRenderer] WASM error during render, skipping frame');
+ console.warn('[EditorSceneRenderer] WASM error during render:', (e as Error).message);
} else {
throw e;
}
diff --git a/editor/src/scene/EditorSceneManager.ts b/editor/src/scene/EditorSceneManager.ts
index 8dbc8d405..157a3a143 100644
--- a/editor/src/scene/EditorSceneManager.ts
+++ b/editor/src/scene/EditorSceneManager.ts
@@ -10,6 +10,7 @@ import {
LocalTransform,
Sprite,
BitmapText,
+ Renderer,
INVALID_TEXTURE,
INVALID_FONT,
TextRenderer,
@@ -62,6 +63,7 @@ export class EditorSceneManager {
private spineInstanceKeys_ = new Map<number, string>();
private spineCurrentState_ = new Map<number, { animation: string; skin: string; loop: boolean }>();
private spineReadyListeners_ = new Set<(entityId: number) => void>();
+ private updatingEntities_ = new Map<number, Promise<void>>();
constructor(module: ESEngineModule, pathResolver: AssetPathResolver) {
this.module_ = module;
@@ -216,6 +218,23 @@ export class EditorSceneManager {
// =========================================================================
async updateEntity(entityId: number, components: ComponentData[], entityData?: EntityData): Promise<void> {
+ const prev = this.updatingEntities_.get(entityId);
+ if (prev) {
+ await prev;
+ }
+
+ const p = this.updateEntityInternal(entityId, components, entityData);
+ this.updatingEntities_.set(entityId, p);
+ try {
+ await p;
+ } finally {
+ if (this.updatingEntities_.get(entityId) === p) {
+ this.updatingEntities_.delete(entityId);
+ }
+ }
+ }
+
+ private async updateEntityInternal(entityId: number, components: ComponentData[], entityData?: EntityData): Promise<void> {
let entity = this.entityMap_.get(entityId);
if (!entity) {
entity = this.world_.spawn();
@@ -370,6 +389,10 @@ export class EditorSceneManager {
return registry;
}
+ get isBusy(): boolean {
+ return this.syncing_ || this.updatingEntities_.size > 0;
+ }
+
get assetServer(): EditorAssetServer {
return this.assetServer_;
}
@@ -387,7 +410,9 @@ export class EditorSceneManager {
for (const [entityId, instanceId] of this.spineInstances_) {
const entityData = this.entityDataMap_.get(entityId);
- const spineComp = entityData?.components.find(c => c.type === 'SpineAnimation');
+ if (!entityData || entityData.visible === false) continue;
+
+ const spineComp = entityData.components.find(c => c.type === 'SpineAnimation');
const spineData = spineComp?.data as Record<string, unknown> | undefined;
const skeletonScale = (spineData?.skeletonScale as number) ?? 1;
@@ -437,12 +462,39 @@ export class EditorSceneManager {
return this.spineController_.getBounds(instanceId);
}
+ getBitmapTextBounds(entityId: number): { width: number; height: number; offsetX: number; offsetY: number } | null {
+ const entity = this.entityMap_.get(entityId);
+ if (entity === undefined) return null;
+
+ const registry = this.registry;
+ if (!registry.hasBitmapText(entity)) return null;
+
+ const bt = registry.getBitmapText(entity);
+ if (!bt.text || bt.font === (INVALID_FONT as number)) return null;
+
+ const metrics = Renderer.measureBitmapText(bt.font, bt.text, bt.fontSize, bt.spacing);
+
+ let offsetX = metrics.width / 2;
+ if (bt.align === 1) {
+ offsetX = 0;
+ } else if (bt.align === 2) {
+ offsetX = -metrics.width / 2;
+ }
+
+ return { width: metrics.width, height: metrics.height, offsetX, offsetY: metrics.height / 2 };
+ }
+
hasSpineInstance(entityId: number): boolean {
return this.spineInstances_.has(entityId);
}
get spineInstanceCount(): number {
- return this.spineInstances_.size;
+ let count = 0;
+ for (const entityId of this.spineInstances_.keys()) {
+ const entityData = this.entityDataMap_.get(entityId);
+ if (entityData && entityData.visible !== false) count++;
+ }
+ return count;
}
onSpineInstanceReady(listener: (entityId: number) => void): () => void {
@@ -560,7 +612,8 @@ export class EditorSceneManager {
this.assetServer_.releaseMaterialInstance(entityId);
const rawTexture = data.texture;
- const textureRef = typeof rawTexture === 'string' ? rawTexture : '';
+ const textureRef = typeof rawTexture === 'string' && rawTexture !== String(INVALID_TEXTURE)
+ ? rawTexture : '';
if (textureRef) {
const texturePath = this.resolveAssetRef(textureRef);
const info = await this.assetServer_.loadTexture(texturePath);
diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.ts
index b44f85825..e6af8a4d6 100644
--- a/sdk/src/renderer.ts
+++ b/sdk/src/renderer.ts
@@ -109,6 +109,11 @@ export const Renderer = {
module?.renderer_clearBuffers(flags);
},
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number } {
+ if (!module) return { width: 0, height: 0 };
+ return module.getResourceManager().measureBitmapText(fontHandle, text, fontSize, spacing);
+ },
+
getStats(): RenderStats {
if (!module) {
return { drawCalls: 0, triangles: 0, sprites: 0, text: 0, spine: 0, meshes: 0, culled: 0 };
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 9a907f1fe..fa35e0db5 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -33,6 +33,7 @@ export interface CppResourceManager {
loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
releaseBitmapFont(handle: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number };
}
// =============================================================================
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index b6690f059..b7fd12aa1 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -388,6 +388,22 @@ void rm_releaseBitmapFont(resource::ResourceManager& rm, u32 handleId) {
rm.releaseBitmapFont(resource::BitmapFontHandle(handleId));
}
+emscripten::val rm_measureBitmapText(resource::ResourceManager& rm, u32 fontHandle,
+ const std::string& text, f32 fontSize, f32 spacing) {
+ auto* font = rm.getBitmapFont(resource::BitmapFontHandle(fontHandle));
+ if (!font) {
+ auto result = emscripten::val::object();
+ result.set("width", 0);
+ result.set("height", 0);
+ return result;
+ }
+ auto metrics = font->measureText(text, fontSize, spacing);
+ auto result = emscripten::val::object();
+ result.set("width", metrics.width);
+ result.set("height", metrics.height);
+ return result;
+}
+
void rm_setTextureMetadata(resource::ResourceManager& rm, u32 handleId,
f32 left, f32 right, f32 top, f32 bottom) {
resource::TextureMetadata metadata;
@@ -1262,7 +1278,8 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
.function("registerTextureWithPath", &esengine::rm_registerTextureWithPath)
.function("loadBitmapFont", &esengine::rm_loadBitmapFont)
.function("createLabelAtlasFont", &esengine::rm_createLabelAtlasFont)
- .function("releaseBitmapFont", &esengine::rm_releaseBitmapFont);
+ .function("releaseBitmapFont", &esengine::rm_releaseBitmapFont)
+ .function("measureBitmapText", &esengine::rm_measureBitmapText);
#ifdef ES_ENABLE_SPINE
emscripten::value_object<esengine::SpineBounds>("SpineBounds")
diff --git a/src/esengine/text/BitmapFont.cpp b/src/esengine/text/BitmapFont.cpp
index a905b43a9..5d387c9cd 100644
--- a/src/esengine/text/BitmapFont.cpp
+++ b/src/esengine/text/BitmapFont.cpp
@@ -171,6 +171,55 @@ void BitmapFont::createLabelAtlas(resource::TextureHandle texture,
}
}
+static u32 decodeUtf8Char(const char* data, usize length, usize& pos) {
+ u8 b0 = static_cast<u8>(data[pos]);
+ if (b0 < 0x80) {
+ return b0;
+ }
+ if ((b0 & 0xE0) == 0xC0 && pos + 1 < length) {
+ u32 cp = (b0 & 0x1F) << 6;
+ cp |= (static_cast<u8>(data[pos + 1]) & 0x3F);
+ pos += 1;
+ return cp;
+ }
+ if ((b0 & 0xF0) == 0xE0 && pos + 2 < length) {
+ u32 cp = (b0 & 0x0F) << 12;
+ cp |= (static_cast<u8>(data[pos + 1]) & 0x3F) << 6;
+ cp |= (static_cast<u8>(data[pos + 2]) & 0x3F);
+ pos += 2;
+ return cp;
+ }
+ if ((b0 & 0xF8) == 0xF0 && pos + 3 < length) {
+ u32 cp = (b0 & 0x07) << 18;
+ cp |= (static_cast<u8>(data[pos + 1]) & 0x3F) << 12;
+ cp |= (static_cast<u8>(data[pos + 2]) & 0x3F) << 6;
+ cp |= (static_cast<u8>(data[pos + 3]) & 0x3F);
+ pos += 3;
+ return cp;
+ }
+ return 0xFFFD;
+}
+
+BitmapFont::TextMetrics BitmapFont::measureText(const std::string& text, f32 fontSize, f32 spacing) const {
+ f32 totalWidth = 0;
+ u32 prevChar = 0;
+
+ for (usize i = 0; i < text.size(); ++i) {
+ u32 charCode = decodeUtf8Char(text.c_str(), text.size(), i);
+ auto* glyph = getGlyph(charCode);
+ if (!glyph) {
+ continue;
+ }
+ if (prevChar) {
+ totalWidth += getKerning(prevChar, charCode);
+ }
+ totalWidth += glyph->xAdvance + spacing;
+ prevChar = charCode;
+ }
+
+ return { totalWidth * fontSize, line_height_ * fontSize };
+}
+
const Glyph* BitmapFont::getGlyph(u32 charCode) const {
auto it = glyphs_.find(charCode);
return it != glyphs_.end() ? &it->second : nullptr;
diff --git a/src/esengine/text/BitmapFont.hpp b/src/esengine/text/BitmapFont.hpp
index 521a517a3..606c3e3a3 100644
--- a/src/esengine/text/BitmapFont.hpp
+++ b/src/esengine/text/BitmapFont.hpp
@@ -35,6 +35,13 @@ public:
const std::string& chars,
u32 charWidth, u32 charHeight);
+ struct TextMetrics {
+ f32 width;
+ f32 height;
+ };
+
+ TextMetrics measureText(const std::string& text, f32 fontSize, f32 spacing) const;
+
const Glyph* getGlyph(u32 charCode) const;
f32 getKerning(u32 first, u32 second) const;
resource::TextureHandle getTexture() const { return texture_; }