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: add audio module with cross-platform backend, ECS components and editor integration

esengineed1933b97f52
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index cdfd5072e..250899ca9 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}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function d(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function u(e,t){return new Promise((s,n)=>{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,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,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=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function h(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}`)}}const p=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],f={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},g=new Map,y=new Set;for(const e of p)for(const t of e.extensions)g.set(t,e),y.add(t);function m(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function _(e){return g.get(m(e))}function x(e){return y.has(e.toLowerCase())}function w(){const e=[];for(const t of p)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function v(e){const t=_(e);return t?.wechatPackInclude??!1}function b(e){const t=_(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let S=null;function P(){return S||(S=wx.getFileSystemManager()),S}function T(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(v(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function M(e){const t=P();try{return t.accessSync(e),!0}catch{return!1}}function E(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}async function A(e){return C(await E(e))}let R=!1;const I=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return u(e,t)}async readFile(e){return function(e){return P().readFileSync(e)}(b(e))}async readTextFile(e){return function(e,t="utf-8"){return P().readFileSync(e,t)}(b(e))}async fileExists(e){return M(b(e))}async loadImagePixels(e){return A(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return h(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),r="function"==typeof wx.onKeyDown;r&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},i=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(i),wx.onTouchEnd(a),this.inputCleanup_=()=>{r&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(i),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},F=1920,k=1080,B=1/60,D={x:0,y:-9.81},U=1/60,L={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const W={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function z(e,t){if(void 0!==t.maxDeltaTime&&(L.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(L.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(L.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(L.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(L.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");L.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(L.canvasScaleMode=W[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(L.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=4294967295,O=4294967295;function H(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(H);const t={};for(const s in e)t[s]=H(e[s]);return t}let X=0;function j(e,t){const s=++X,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...H(t),...e}:H(t):e?{...t,...e}:{...t}}}function Y(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function N(e,t){const s=K.get(e)??Y().get(e);if(s)return s;const n=j(e,t);return Y().set(e,n),K.set(e,n),G(e,t,!1),n}function V(e){return Y().get(e)}function G(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function q(e){return!0===e._builtin}const K=new Map;function J(e,t){K.set(e,t)}function Q(e){return K.get(e)??V(e)}function Z(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return K.set(e,s),s}const ee={Perspective:0,Orthographic:1},te={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ne=Z("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),re=ne,oe=ne,ie=Z("Sprite",{texture:$,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,enabled:!0}),ae=Z("Camera",{projectionType:ee.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:te.ColorAndDepth}),le=Z("Canvas",{designResolution:{x:F,y:k},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ce=Z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),de=Z("Parent",{entity:0}),ue=Z("Children",{entities:[]}),he=Z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:O,enabled:!0}),pe=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,enabled:!0}),fe=N("Name",{value:""}),ge=N("SceneOwner",{scene:"",persistent:!1});const ye=Z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),me=Z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e=Z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=Z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),we={Static:0,Kinematic:1,Dynamic:2};let ve=0;function be(e,t){const s=++ve;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Se(e){return{_type:"res",_resource:e}}function Pe(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_)}updateValue(e){this.value_=e}}class Me{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Te(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ee=be({delta:0,elapsed:0,frameCount:0},"Time");function Ce(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ae(t[e]),o=Ae(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function Ae(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Re(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Ie=null;function Fe(e){Ie=e}function ke(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ie&&Ie(e,t)}function Be(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="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}:n}}return s}let De=1;const Ue=new WeakMap;function Le(e){let t=Ue.get(e);return void 0===t&&(t=De++,Ue.set(e,t)),t}const We=[];function ze(e,t=[],s=[]){We.length=0;for(const t of e)We.push(Le(t));We.sort((e,t)=>e-t);let n=We.join(",");if(t.length>0){We.length=0;for(const e of t)We.push(Le(e));We.sort((e,t)=>e-t),n+="|+"+We.join(",")}if(s.length>0){We.length=0;for(const e of s)We.push(Le(e));We.sort((e,t)=>e-t),n+="|-"+We.join(",")}return n}class $e{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw ke(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){ke(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){ke(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ke(t,`removeParent(entity=${e})`)}}insert(e,t,s){return q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(q(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Be(s))}catch(s){ke(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}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)}tryGet(e,t){if(q(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return ke(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:r.bind(s),has:o.bind(s),remove:i.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ce(t._name,t._default,n);if(e.length>0)throw new Error(Re(t._name,e))}const r={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Be(r))}catch(s){ke(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const r=t[n];if(null!=r&&"object"==typeof r&&!Array.isArray(r)&&"r"in r&&"g"in r&&"b"in r&&"a"in r){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const r=e[s],o=t[s];if(null==r||"object"!=typeof r||Array.isArray(r)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=r;else{const e=r,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:r}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return ke(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return ke(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){ke(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Ce(t._name,t._default,e);if(r.length>0)throw new Error(Re(t._name,r));n=e}const r=t.create(n),o=this.getStorage(t),i=!o.has(e);o.set(e,r);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),i&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),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),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of K)if(q(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=Y();for(const n of s)for(const[s,r]of e)if(r._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const r=n??ze(e,t,s),o=this.queryCache_.get(r);if(o&&o.version===this.worldVersion_)return o.result;let i=null,a=1/0;for(const t of e)if(!q(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=i?i.keys():this.entities_.keys();for(const n of c){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}if(r)for(const e of t)if(!this.has(n,e)){r=!1;break}if(r)for(const e of s)if(this.has(n,e)){r=!1;break}r&&l.push(n)}return this.queryCache_.set(r,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Oe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function He(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Xe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function je(e){return Oe(e)||He(e)||Xe(e)?e._component:e}function Ye(e,t=[],s=[]){const n=[],r=[],o=[];return e.forEach((e,t)=>{Oe(e)&&n.push(t),He(e)?r.push({index:t,component:e._component}):Xe(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:r,_changedFilters:o,with:(...n)=>Ye(e,[...t,...n],s),without:(...n)=>Ye(e,t,[...s,...n])}}class Ne{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(je),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=ze(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,r=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,i=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}i[0]=d;for(let e=0;e<n;e++)i[e+1]=this.world_.get(d,t[e]);if(r){for(let t=0;t<l;t++)a[t].data=i[e[t]+1];c=d}yield i}}finally{if(this.world_.endIteration(),null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,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(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class Ve{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}class Ge{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=q(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 qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ge(this,null);return this.spawned_.push(e),e}entity(e){return new Ge(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class Ke{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class Je{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ke)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ke,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Qe{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ze{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var et;exports.Schedule=void 0,(et=exports.Schedule||(exports.Schedule={}))[et.Startup=0]="Startup",et[et.First=1]="First",et[et.PreUpdate=2]="PreUpdate",et[et.Update=3]="Update",et[et.PostUpdate=4]="PostUpdate",et[et.Last=5]="Last",et[et.FixedPreUpdate=10]="FixedPreUpdate",et[et.FixedUpdate=11]="FixedUpdate",et[et.FixedPostUpdate=12]="FixedPostUpdate";let tt=0;function st(e,t,s){const n=++tt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function nt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class rt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof qe&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ne(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new qe(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Qe(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ze(s)}case"removed":{const t=e;return new Ve(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ot{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 it=be(new ot,"Input");class at{constructor(e){this.target_=e??null}build(e){const s=new ot;e.insertResource(it,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,n){s.mouseX=t,s.mouseY=n,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,st([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const lt=new at,ct=be({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var dt;function ut(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(dt=exports.BlendMode||(exports.BlendMode={}))[dt.Normal=0]="Normal",dt[dt.Additive=1]="Additive",dt[dt.Multiply=2]="Multiply",dt[dt.Screen=3]="Screen",dt[dt.PremultipliedAlpha=4]="PremultipliedAlpha";let ht=null,pt=null,ft=1;const gt=new Map;function yt(e){ht=e,pt=e.getResourceManager(),Mt()}function mt(){0!==vt&&ht&&(ht._free(vt),vt=0),gt.clear(),ft=1,wt=!1,St.clear(),Pt=null,pt=null,ht=null}function _t(){if(!pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pt}const xt={createShader:(e,t)=>_t().createShader(e,t),releaseShader(e){e>0&&_t().releaseShader(e)},create(e){const t=ft++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return gt.set(t,s),t},get:e=>gt.get(e),setUniform(e,t,s){const n=gt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,ht?.invalidateMaterialCache(e))},getUniform(e,t){const s=gt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=gt.get(e);s&&(s.blendMode=t,ht?.invalidateMaterialCache(e))},getBlendMode(e){const t=gt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=gt.get(e);s&&(s.depthTest=t,ht?.invalidateMaterialCache(e))},getShader(e){const t=gt.get(e);return t?.shader??0},release(e){gt.delete(e),ht?.invalidateMaterialCache(e)},isValid:e=>gt.has(e),releaseAll(){gt.clear(),ht?.clearMaterialCache()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"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=gt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ft++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return gt.set(s,n),s},toAssetData(e,t){const s=gt.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=gt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wt=!1,vt=0;const bt=16384,St=new Map;let Pt=null;function Tt(e){const t=(0===vt&&ht&&(vt=ht._malloc(bt)),vt);if(0===t||!ht)return{ptr:0,count:0};let s=0,n=0;const r=ht.HEAPU8,o=ht.HEAPU32,i=ht.HEAPF32;for(const[a,l]of e){if(ut(l))continue;let e=St.get(a);e||(Pt||(Pt=new TextEncoder),e=Pt.encode(a),St.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>bt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${bt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=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?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Mt(){if(!ht||wt)return;ht.materialDataProvider=(e,t,s,n,r)=>{const o=gt.get(e);if(!o)return ht.HEAPU32[t>>2]=0,ht.HEAPU32[s>>2]=0,ht.HEAPU32[n>>2]=0,void(ht.HEAPU32[r>>2]=0);ht.HEAPU32[t>>2]=o.shader,ht.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Tt(o.uniforms);ht.HEAPU32[n>>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 Ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class At{constructor(e,t=""){this.cache_=new Ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())xt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:xt.createFromAsset(n,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 Rt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function It(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Ft=new Map;function kt(e){Ft.set(e.name,e)}const Bt=N("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Dt(e,t){const s=e.getEntitiesWithComponents([Bt]);for(const n of s){const s=e.get(n,Bt);if(!s.enabled||!s.playing||!s.clip)continue;const r=Ft.get(s.clip);if(!r||0===r.frames.length)continue;const o=1/(r.fps*s.speed),i=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=i;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=r.frames.length&&(s.loop&&r.loop?s.currentFrame=0:(s.currentFrame=r.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ie)){const t=r.frames[s.currentFrame],o=e.get(n,ie);o.texture=t.texture,e.insert(n,ie,o)}a&&e.insert(n,Bt,s)}}const Ut=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}]]);function Lt(e){const t=Ut.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function Wt(e){return Ut.get(e)?.fields??[]}function zt(e){return Ut.get(e)?.spine??null}const $t=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ot(e){return $t.get(e)}function Ht(e,t){const s=$t.get(e.type);if(!s)return;const n=e.data;for(const r of s){const s=n[r];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${r} references entity ${s} which does not exist`),n[r]=void 0!==o?o:0}}}function Xt(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,fe,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)Ht(r,s),Vt(e,t,r,n.name)}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)}return s}function jt(e,t){return Xt(e,t)}async function Yt(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,r){const o=new Map;for(const e of Nt.keys())o.set(e,new Set);const i=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),i.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Nt.entries()].map(async([e,r])=>{const i=await r.load(o.get(e),t,s,n);l.set(e,i)}),d=i.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),r){for(const e of n.values())r.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&r.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)r.fontPaths.add(e);for(const e of a)r.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ut.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const r=t.get(n);void 0!==r&&(s[e.field]=r)}}}(t,n,r,o,s?.collectAssets);const i=Xt(e,t);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 i}const Nt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["anim-clip",{async load(e,t,s,n){const r=[...e].map(async e=>{try{const r=await t.loadJson(e),o=Rt(r),i=new Map,a=o.map(async e=>{try{const r=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),i.set(e,0)}});await Promise.all(a);kt(It(e,r,i))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(r),new Map}}]]);function Vt(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const r=Q(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Gt(e,t){const s=e.getEntitiesWithComponents([ae]);for(const n of s){const s=e.get(n,ae);s&&(s.aspectRatio=t,e.insert(n,ae,s))}}class qt{constructor(e){this.textureCache_=new Ct,this.shaderCache_=new Ct,this.jsonCache_=new Ct,this.textCache_=new Ct,this.binaryCache_=new Ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ct,this.prefabCache_=new Ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l(L.textCanvasSize,L.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new At(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}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);if(this.materialLoader_.releaseAll(),xt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),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),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===_(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=_(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}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 n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of Lt(e.type)){const n=e.data[s];if("string"==typeof n&&n){const r=t(n);r&&(e.data[s]=r)}}const s=zt(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const r=t(s);r&&(e.data[n]=r)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}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 Yt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((s,n)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,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,n,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,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(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 r=this.ctx_.getImageData(0,0,t,s),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,s,a,o.length,1,n);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 n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(r,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(b(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 s=this.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 s=this.getEmbedded(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 s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.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 n=s.split("/").filter(e=>e);let r="";for(const e of n){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 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 Kt=be(null,"Assets");class Jt{build(e){const t=e.wasmModule;t?e.insertResource(Kt,new qt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Jt;async function Zt(e,t,s){const{entities:n,rootId:r}=await ts(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Yt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const es=10;async function ts(e,t,s,n,r,o=0){if(o>es)throw new Error(`Prefab nesting depth exceeded ${es}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ts(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};ss(u.components,i),ns(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function ss(e,t){for(const s of e){const e=Ot(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const r=t.get(e);void 0!==r&&(s.data[n]=r)}}}}function ns(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 rs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Zt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const os=be(null,"Prefabs");class is{constructor(){this.name="PrefabsPlugin",this.dependencies=[Kt]}build(e){const t=e.getResource(Kt);e.insertResource(os,new rs(e.world,t))}}const as=new is;let ls=null,cs=0,ds=0,us=0;const hs=new Float32Array(256);function ps(e){ls=e,cs=ls._malloc(64),ds=ls._malloc(64),us=ls._malloc(1024)}function fs(){ls&&(cs&&(ls._free(cs),cs=0),ds&&(ls._free(ds),ds=0),us&&(ls._free(us),us=0)),ls=null}function gs(){if(!ls)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ls}const ys={r:1,g:1,b:1,a:1},ms={begin(e){const t=gs();try{t.HEAPF32.set(e,cs/4),t.draw_begin(cs)}catch(e){ke(e,"Draw.begin")}},end(){try{gs().draw_end()}catch(e){ke(e,"Draw.end")}},line(e,t,s,n=1){try{gs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){ke(e,"Draw.line")}},rect(e,t,s,n=!0){try{gs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){ke(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{gs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){ke(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{gs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){ke(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{gs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){ke(e,"Draw.circleOutline")}},texture(e,t,s,n=ys){try{gs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){ke(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ys){try{gs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){ke(e,"Draw.textureRotated")}},setLayer(e){gs().draw_setLayer(e)},setDepth(e){gs().draw_setDepth(e)},getDrawCallCount:()=>ls?ls.draw_getDrawCallCount():0,getPrimitiveCount:()=>ls?ls.draw_getPrimitiveCount():0,setBlendMode(e){gs().draw_setBlendMode(e)},setDepthTest(e){gs().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=gs();n.HEAPF32.set(s,ds/4),n.draw_mesh(e,t,ds)}catch(s){ke(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=gs(),r=xt.get(t);if(!r)return;if(ms.setBlendMode(r.blendMode),ms.setDepthTest(r.depthTest),0===r.uniforms.size)return void ms.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,ds/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ws(t);if(!(n<0)){if(ut(s))hs[o++]=10,hs[o++]=n,hs[o++]=s.slot??e++,hs[o++]=s.textureId;else if("number"==typeof s)hs[o++]=1,hs[o++]=n,hs[o++]=s;else if(Array.isArray(s)){hs[o++]=s.length,hs[o++]=n;for(let e=0;e<s.length;e++)hs[o++]=s[e]}else"w"in s?(hs[o++]=4,hs[o++]=n,hs[o++]=s.x,hs[o++]=s.y,hs[o++]=s.z,hs[o++]=s.w):"z"in s?(hs[o++]=3,hs[o++]=n,hs[o++]=s.x,hs[o++]=s.y,hs[o++]=s.z):(hs[o++]=2,hs[o++]=n,hs[o++]=s.x,hs[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(hs.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,ds);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),us/4),n.draw_meshWithUniforms(e,r.shader,ds,us,o)}catch(s){ke(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},_s={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},xs=new Set;function ws(e){const t=_s[e];return void 0!==t?t:(xs.has(e)||(xs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(_s).join(", ")}`)),-1)}const vs=new Map;function bs(e,t,s){vs.set(e,{fn:t,scene:s??""})}function Ss(e){vs.delete(e)}function Ps(){vs.clear()}var Ts;exports.DataType=void 0,(Ts=exports.DataType||(exports.DataType={}))[Ts.Float=1]="Float",Ts[Ts.Float2=2]="Float2",Ts[Ts.Float3=3]="Float3",Ts[Ts.Float4=4]="Float4",Ts[Ts.Int=5]="Int",Ts[Ts.Int2=6]="Int2",Ts[Ts.Int3=7]="Int3",Ts[Ts.Int4=8]="Int4";let Ms=null,Es=0,Cs=0,As=0;function Rs(e){Ms=e,Es=Ms._malloc(262144),Cs=Ms._malloc(65536),As=Ms._malloc(256)}function Is(){Ms&&(Es&&Ms._free(Es),Cs&&Ms._free(Cs),As&&Ms._free(As),Es=0,Cs=0,As=0),Ms=null}function Fs(){if(!Ms)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Ms}const ks={create(e){const t=Fs(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Es/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,As,r).set(o),t.geometry_init(s,Es,n,As,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Cs,n).set(e.indices),t.geometry_setIndices16(s,Cs,n)}else{new Uint32Array(t.HEAPU8.buffer,Cs,n).set(e.indices),t.geometry_setIndices32(s,Cs,n)}}return s},updateVertices(e,t,s=0){const n=Fs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Es/4),n.geometry_updateVertices(e,Es,r,s)},release(e){e>0&&Fs().geometry_release(e)},isValid:e=>!(!Ms||e<=0)&&Ms.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ks.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,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=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/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;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ks.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-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 ks.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 Bs=null;function Ds(e){Bs=e}function Us(){Bs&&Ws.isInitialized()&&Ws.shutdown(),Bs=null}function Ls(){if(!Bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Bs}const Ws={init(e,t){try{return Ls().postprocess_init(e,t)}catch(s){return ke(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ls().postprocess_shutdown()}catch(e){ke(e,"PostProcess.shutdown")}},resize(e,t){try{Ls().postprocess_resize(e,t)}catch(s){ke(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ls().postprocess_addPass(e,t)}catch(t){return ke(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ls().postprocess_removePass(e)}catch(t){ke(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ls().postprocess_setPassEnabled(e,t)}catch(t){ke(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ls().postprocess_isPassEnabled(e)}catch(t){return ke(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ls().postprocess_setUniformFloat(e,t,s)}catch(s){ke(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ls().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){ke(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ls().postprocess_begin()}catch(e){ke(e,"PostProcess.begin")}},end(){try{Ls().postprocess_end()}catch(e){ke(e,"PostProcess.end")}},getPassCount(){try{return Ls().postprocess_getPassCount()}catch(e){return ke(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Bs)return!1;try{return Bs.postprocess_isInitialized()}catch(e){return ke(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ls().postprocess_setBypass(e)}catch(e){ke(e,"PostProcess.setBypass")}},isBypassed(){if(!Bs)return!0;try{return Bs.postprocess_isBypassed()}catch(e){return ke(e,"PostProcess.isBypassed"),!0}},createBlur:()=>xt.createShader(zs,"#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:()=>xt.createShader(zs,"#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:()=>xt.createShader(zs,"#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:()=>xt.createShader(zs,"#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")},zs="#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 $s;exports.RenderStage=void 0,($s=exports.RenderStage||(exports.RenderStage={}))[$s.Background=0]="Background",$s[$s.Opaque=1]="Opaque",$s[$s.Transparent=2]="Transparent",$s[$s.Overlay=3]="Overlay";let Os=null,Hs=0;function Xs(e){Os=e,Hs=Os._malloc(64)}function js(){Os&&Hs&&(Os._free(Hs),Hs=0),Os=null}const Ys={init(e,t){Os?.renderer_init(e,t)},resize(e,t){Os?.renderer_resize(e,t)},begin(e,t){if(Os&&Hs)try{Os.HEAPF32.set(e,Hs/4),Os.renderer_begin(Hs,t??0)}catch(e){ke(e,"Renderer.begin")}},flush(){try{Os?.renderer_flush()}catch(e){ke(e,"Renderer.flush")}},end(){try{Os?.renderer_end()}catch(e){ke(e,"Renderer.end")}},submitSprites(e){if(Os)try{Os.renderer_submitSprites(e._cpp)}catch(e){ke(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Os)try{Os.renderer_submitBitmapText(e._cpp)}catch(e){ke(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Os)try{Os.renderer_submitSpine?.(e._cpp)}catch(e){ke(e,"Renderer.submitSpine")}},setStage(e){Os?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Os?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Os?.renderer_releaseTarget(e)},getTargetTexture:e=>Os?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Os?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Os?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Os?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Os?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Os?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Os?Os.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Os?{drawCalls:Os.renderer_getDrawCalls(),triangles:Os.renderer_getTriangles(),sprites:Os.renderer_getSprites(),text:Os.renderer_getText(),spine:Os.renderer_getSpine?.()??0,meshes:Os.renderer_getMeshes(),culled:Os.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ns=null;function Vs(e){Ns=e}function Gs(){Ns=null}const qs={enable(){Ns?.gl_enableErrorCheck(!0)},disable(){Ns?.gl_enableErrorCheck(!1)},check:e=>Ns?.gl_checkErrors(e)??0,diagnose(){Ns?.renderer_diagnose()}};class Ks{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ys.resize(n,r),Ws.isInitialized()&&Ws.getPassCount()>0&&Ws.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ys.setViewport(0,0,n,r),Ys.clearBuffers(3),Ys.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ys.submitSprites(t),Ys.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ys.submitSpine(t),Ys.flush(),this.executeDrawCallbacks(s,o),Ys.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ys.setViewport(n.x,n.y,n.w,n.h),Ys.setScissor(n.x,n.y,n.w,n.h,!0),Ys.clearBuffers(r),Ys.setScissor(0,0,0,0,!1),Ys.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ys.submitSprites(t),Ys.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ys.submitSpine(t),Ys.flush(),this.executeDrawCallbacks(s,o),Ys.end()}executeDrawCallbacks(e,t){const s=vs;if(s.size>0){ms.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ms.end();for(const e of n)Ss(e)}}}const Js="__scene_transition_overlay__";class Qs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Zs{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ge,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),bs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ws.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ws.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ge)){const s=this.app_.world.get(e,ge);s.persistent=t,this.app_.world.insert(e,ge,s)}}}class en{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??L.sceneTransitionDuration,r=t.color??{...L.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},bs(Js,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;ms.setLayer(9999),ms.setDepth(9999),ms.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Ss(Js),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ss(Js),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Qs(t);this.scenes_.set(e,s);const n=new Zs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Qs(t);this.scenes_.set(e,s);const n=new Zs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ge)){if(this.app_.world.get(e,ge).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Ss(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ws.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:s};this.app_.hasResource(Kt)&&(r.assetServer=this.app_.getResource(Kt));const o=await Yt(this.app_.world,n,r);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,ge,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=sn(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const r=this.contexts_.get(t);s.setup&&await s.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Kt)?this.app_.getResource(Kt):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)xt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let r=!1;if(s.has(e,ie)){const t=s.get(e,ie);n.sprite=t.color.a,t.color.a=0,s.insert(e,ie,t),r=!0}if(s.has(e,pe)){const t=s.get(e,pe);n.spine=t.color.a,t.color.a=0,s.insert(e,pe,t),r=!0}if(s.has(e,he)){const t=s.get(e,he);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,he,t),r=!0}r&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ie)){const t=s.get(e,ie);t.color.a=n.sprite,s.insert(e,ie,t)}if(void 0!==n.spine&&s.has(e,pe)){const t=s.get(e,pe);t.color.a=n.spine,s.insert(e,pe,t)}if(void 0!==n.bitmapText&&s.has(e,he)){const t=s.get(e,he);t.color.a=n.bitmapText,s.insert(e,he,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Ws.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const tn=be(null,"SceneManager");function sn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(tn).getSceneStatus(t)&&s._fn(...n)}}}const nn=st([Pe(tn),Se(Ee)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),rn={name:"SceneManager",build(e){const t=new en(e);e.insertResource(tn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(tn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,nn)}};class on{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new Je,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new $e,this.resources_=new Me;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new on}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const r=n.filter(t=>t.system._id!==e);r.length!==n.length&&(this.systems_.set(s,r),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Fe(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(tn).register(e),this}setInitialScene(e){return this.getResource(tn).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new rt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ee)||this.resources_.insert(Ee,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new rt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ee,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,Ps();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Gs,js,Us,Is,mt,fs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ee);t.delta=e,t.elapsed+=e,t.frameCount++}}function an(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.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 cn(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case se.FixedWidth:return o;case se.FixedHeight:return i;case se.Expand:return Math.max(o,i);case se.Shrink:return Math.min(o,i);case se.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}const dn=[];function un(e){if(e<dn.length)return dn[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return dn.push(t),t}function hn(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ge);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getTransform(e),i=r.viewportW*s/(r.viewportH*n);let a,d=0,u=0;if(r.projectionType===ee.Orthographic){if(u=r.orthoSize,l){u=cn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,i,l.scaleMode,l.matchWidthOrHeight)}d=u*i,a=fn(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=yn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=_n(o.position.x,o.position.y,o.position.z),p=un(c.length);p.entity=e,p.viewProjection.set(wn(a,h)),p.viewportRect.x=r.viewportX,p.viewportRect.y=r.viewportY,p.viewportRect.w=r.viewportW,p.viewportRect.h=r.viewportH,p.clearFlags=r.clearFlags,p.priority=r.priority,p.halfW=d,p.halfH=u,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const pn=new Float32Array(16);function fn(e,t,s,n,r,o){const i=pn;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const gn=new Float32Array(16);function yn(e,t,s,n){const r=gn;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const mn=new Float32Array(16);function _n(e,t,s){const n=mn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const xn=new Float32Array(16);function wn(e,t){const s=xn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const vn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function bn(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,g,y;e.x===t.x?(p=c+s.x-r.x*i.x,g=p+r.x):(p=c+s.x,g=d+n.x),e.y===t.y?(f=u+s.y-r.y*i.y,y=f+r.y):(f=u+s.y,y=h+n.y);const m=Math.max(0,g-p),_=Math.max(0,y-f);return{originX:p+i.x*m,originY:f+i.y*_,width:m,height:_,rect:{left:p,bottom:f,right:g,top:y}}}const Sn=Z("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}});let Pn=null,Tn=null;function Mn(e,t){e.has(t,ie)||e.insert(t,ie,{texture:$,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})}function En(e,t){switch(e){case vn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Cn(e,t,s,n){if(!e.has(t,Sn))return;const r=e.get(t,Sn),o=En(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,Sn,r)}function An(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Rn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function In(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(Rn(i.charCodeAt(0))&&n.length>0&&Rn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Rn(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function Fn(e){let t=1;for(;t<e;)t*=2;return t}function kn(e,t){let s=0,n=t;for(;e.has(n,de);){const t=e.get(n,de).entity;if(!e.valid(t))break;s++,n=t}return s}function Bn(e,t){if(Pn&&Tn){const e=Pn.getUIRectComputedWidth(Tn,t);if(e>0)return e}return e.size.x}function Dn(e,t){if(Pn&&Tn){const e=Pn.getUIRectComputedHeight(Tn,t);if(e>0)return e}return e.size.y}function Un(e,t,s){let n=t;for(;e.has(n,de);){const t=e.get(n,de).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Ln(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Wn(e,t,s,n,r){if(!e.has(t,Sn))return;const o=e.get(t,Sn),i=bn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(e.has(t,ie)){const s=e.get(t,ie);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ie,s))}if(e.has(t,ne)){const s=e.get(t,ne);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,ne,s)}}function zn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const $n=.1,On=30,Hn={r:.3,g:.5,b:.8,a:1},Xn={Left:0,Center:1,Right:2},jn={Top:0,Middle:1,Bottom:2},Yn={Visible:0,Clip:1,Ellipsis:2},Nn=N("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Xn.Left,verticalAlign:jn.Top,wordWrap:!0,overflow:Yn.Visible,lineHeight:1.2});class Vn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l(L.textCanvasSize,L.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Fn(this.frameMaxW_)),e.height=Math.max(e.height,Fn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Fn(this.frameMaxW_),e.height=Fn(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.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=In(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=r?Math.ceil(o):u+2*d,f=r?Math.ceil(i):h+2*d;if(r&&e.overflow===Yn.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)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,Fn(p)),n.height=Math.max(n.height,Fn(f)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Yn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(r){switch(e.verticalAlign){case jn.Top:w=d;break;case jn.Middle:w=d+(f-2*d-x)/2;break;case jn.Bottom:w=f-x-d;break;default:w=d}w<0&&(w=0)}else w=d;let v=w;for(const t of l){let n;switch(e.align){case Xn.Left:n=d;break;case Xn.Center:n=p/2;break;case Xn.Right:n=p-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Yn.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const M=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:M,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 n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);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[s,n]of this.cache)e(s)||(t.releaseTexture(n.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()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Xn.Left:return"left";case Xn.Center:return"center";case Xn.Right:return"right"}}}const Gn=zn({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Bn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Dn(e.uiRect,e.entity):0});class qn{build(e){J("Text",Nn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Vn(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Nn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,Nn)){if(n.valid(e)&&n.has(e,ie)){const t=n.get(e,ie);n.insert(e,ie,{texture:$,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}r.delete(e)}const e=n.getEntitiesWithComponents([Nn]);for(const t of e){const e=n.get(t,Nn),o=n.has(t,Sn)?n.get(t,Sn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!Gn.changed(a,i)){if(n.has(t,ie)&&n.get(t,ie).texture!==$)continue}Mn(n,t);const l=o?{size:{x:Bn(o,t),y:Dn(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,ie);n.insert(t,ie,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),r.set(t,Gn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Kn=new qn,Jn=0,Qn=1,Zn=Z("UIMask",{enabled:!0,mode:Jn});function er(e,t){const s=Math.max(e.x,t.x),n=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:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function tr(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],p=e[10],f=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,T=u*y-h*g,M=u*m-p*g,E=u*_-f*g,C=h*m-p*y,A=h*_-f*y,R=p*_-f*m;let I=x*R-w*A+v*C+b*E-S*M+P*T;return 0===I||(I=1/I,s[0]=(l*R-c*A+d*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-d*M)*I,s[5]=(n*R-o*E+i*M)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-p*v+f*w)*I,s[8]=(a*A-l*E+d*T)*I,s[9]=(r*E-n*A-i*T)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-f*x)*I,s[12]=(l*M-a*C-c*T)*I,s[13]=(n*C-r*M+o*T)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+p*x)*I),s}function sr(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function nr(e,t){return 2*Math.atan2(e,t)}function rr(e,t,s,n,r,o,i){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function or(e,t,s,n,r,o,i){if(!e.has(t,Sn)||!e.has(t,ne))return null;const a=e.get(t,Sn),l=e.get(t,ne),c=Bn(a,t)*l.worldScale.x,d=Dn(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,g=-c*p,y=c*(1-p),m=-d*f,_=d*(1-f),x=nr(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+g*w-m*v,h+g*v+m*w],[u+y*w-m*v,h+y*v+m*w],[u+y*w-_*v,h+y*v+_*w],[u+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,T=-1/0,M=-1/0;for(const[e,t]of b){const[a,l]=rr(e,t,s,n,r,o,i);S=Math.min(S,a),P=Math.min(P,l),T=Math.max(T,a),M=Math.max(M,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(T-S),h:Math.round(M-P)}}function ir(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Zn]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Zn);s.enabled&&(u.add(e),s.mode===Qn?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0;Un(t,e,e=>{if(r.has(e)){if(t.get(e,Zn).mode===Jn)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if(t.get(s,Zn).mode===Jn){const e=or(t,s,o,i,a,l,c);e&&(n=er(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=or(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Un(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class ar{build(e){if(J("UIMask",Zn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ir(e.wasmModule,e.world))}}const lr=new ar,cr=Z("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),dr=Z("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ur={Normal:0,Hovered:1,Pressed:2,Disabled:3},hr=N("Button",{state:ur.Normal,transition:null});class pr{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}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 fr=be(new pr,"UIEvents");class gr{build(e){J("UIRect",Sn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){Pn=e,Tn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(ct)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(ct)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,st([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const yr=new gr;let mr=!1,_r=!1;function xr(){return mr}function wr(){return _r}const vr=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(tr(t,e),s=!1),e)}}();function br(e,t,s,n){t.emit(s,n,s),Un(e,s,r=>{if(!e.has(r,cr))return!1;const o=e.get(r,cr);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class Sr{build(e){J("Interactable",cr),J("Button",hr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new pr;e.insertResource(fr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(it),Se(ct)],(e,a)=>{if(r.drain(),xr()&&!wr())return;const l=t.getEntitiesWithComponents([dr]);for(const e of l){const s=t.get(e,dr);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,dr,s))}if(!a.valid)return;const c=d(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;vr.update(a.viewProjection);const p=sr(u,h,vr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,g,y);const m=s.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,dr)){const e=t.get(o,dr);e.hovered=!1,t.insert(o,dr,e),r.emit(o,"hover_exit")}if(null!==_){Ln(t,_,dr);const e=t.get(_,dr);e.hovered=!0,t.insert(_,dr,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,dr);e.pressed=!0,e.justPressed=!0,t.insert(_,dr,e),i=_,br(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,dr)){const e=t.get(i,dr);e.pressed=!1,e.justReleased=!0,t.insert(i,dr,e),br(t,r,i,"release"),i===o&&br(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,st([],()=>{const e=t.getEntitiesWithComponents([hr]);for(const s of e){if(Ln(t,s,cr,{enabled:!0}),!t.has(s,dr))continue;const e=t.get(s,dr),n=t.get(s,hr),r=t.get(s,cr),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=ur.Pressed:e.hovered?n.state=ur.Hovered:n.state=ur.Normal:n.state=ur.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,ie)){const o=t.get(s,ie);o.color=An(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,ie,o)}}},{name:"ButtonSystem"}))}}const Pr=new Sr,Tr=N("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}),Mr=N("Focusable",{tabIndex:0,isFocused:!1});class Er{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Cr=be(new Er,"FocusManager");class Ar{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(J("TextInput",Tr),xr()&&!wr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=l(L.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=0,a=0,c=!1,d=!0,u=0,h=0;const p=function(){if("undefined"==typeof document||!document.body)return null;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}();if(!p)return;const f=p;function g(){const t=e.getResource(Cr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Tr)?n:null}const y=()=>{c||null===g()||v()},m=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=g();if(null===n)return;if("Escape"===t.key)return void b();const r=s.get(n,Tr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(fr).emit(n,"submit"),void b()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,f.selectionStart=o,f.selectionEnd=o,r.dirty=!0,S())},w=()=>{const t=g();if(null!==t){const n=s.get(t,Tr);n.focused=!1,n.dirty=!0;e.getResource(Cr).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,Tr);if(n.readOnly)return;let r=f.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),f.value=r),r!==n.value){n.value=r;e.getResource(fr).emit(t,"change")}n.cursorPos=f.selectionStart??r.length,n.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=s.get(t,Tr);e.focused=!1,e.dirty=!0}e.getResource(Cr).blur(),f.blur()}function S(){d=!0,u=0}f.addEventListener("input",y),f.addEventListener("compositionstart",m),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",y),f.removeEventListener("compositionstart",m),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==i&&(t._free(i),i=0,a=0)};let P=null;function T(e,l,c,u){(r.width<c||r.height<u)&&(r.width=Fn(Math.max(r.width,c)),r.height=Fn(Math.max(r.height,u))),o.clearRect(0,0,r.width,r.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,c,u),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,u),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=p?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=In(o,f,c-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=y}else{const e=(u-l.fontSize)/2;o.fillText(f,m,e)}if(l.focused&&d){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=In(o,l.value,c-2*m);let r=0,i=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=l.cursorPos){i=t,a=l.cursorPos-r;break}r+=s,t<e.length-1&&r<l.value.length&&"\n"===l.value[r]&&r++,i=t+1,a=0}const d=i<e.length?e[i].substring(0,a):"";t=m+o.measureText(d).width,s=m+i*y,n=y}else t=m+o.measureText(e).width,s=(u-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,u),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==i&&t._free(i),i=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,i);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,u,i,x.length,1,!0);n.set(e,b);const S=s.get(e,ie);S.texture=b,S.size.x=c,S.size.y=u,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,ie,S)}e.addSystemToSchedule(exports.Schedule.Update,st([Se(Cr)],e=>{const t=s.getEntitiesWithComponents([Tr]);for(const e of t)Ln(s,e,Mr,{tabIndex:0,isFocused:!1}),Ln(s,e,cr,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Tr)){const e=s.get(P,Tr);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Tr);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===h?0:(e-h)/1e3;h=e,r=Math.min(r,.1);const o=g();if(null!==o&&(u+=r,u>=.5)){u-=.5,d=!d;s.get(o,Tr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Tr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Tr,Sn]);for(const e of a){const t=s.get(e,Tr);if(!t.dirty)continue;const n=s.get(e,Sn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(Mn(s,e),T(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Rr=new Ar,Ir={Simple:0,Sliced:1,Tiled:2,Filled:3},Fr={Horizontal:0,Vertical:1},kr={Left:0,Right:1,Bottom:2,Top:3},Br=N("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:Ir.Simple,fillMethod:Fr.Horizontal,fillOrigin:kr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Dr=zn({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Bn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Dn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Ur=new class{build(e){J("Image",Br);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Br)||s.delete(e);const e=t.getEntitiesWithComponents([Br]);for(const n of e){const e=t.get(n,Br),r=t.has(n,Sn)?t.get(n,Sn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!Dr.changed(i,o))continue;Mn(t,n);const a=t.get(n,ie);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,r&&(a.size.x=Bn(r,n),a.size.y=Dn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Ir.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Fr.Horizontal?e.fillOrigin===kr.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===kr.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Ir.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,ie,a),s.set(n,Dr.take(o))}else a.color.a=0,t.insert(n,ie,a),s.set(n,Dr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Lr=N("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wr=N("ToggleGroup",{allowSwitchOff:!1});const zr=new class{build(e){J("Toggle",Lr),J("ToggleGroup",Wr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,st([Se(fr)],e=>{const n=t.getEntitiesWithComponents([Lr]);if(!xr()||wr()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Lr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Lr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Lr);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(Ln(t,s,cr,{enabled:!0}),!t.has(s,dr))continue;const n=t.get(s,dr),r=t.get(s,Lr),i=t.get(s,cr);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Wr);if(r.isOn&&i){if(!t.get(n,Wr).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Lr,r),r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,Lr);r.isOn&&(r.isOn=!1,t.insert(n,Lr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,ie)){const e=t.get(s,ie);e.color=An(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,ie,e)}}}for(const e of n){const s=t.get(e,Lr);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ie)){const e=t.get(s.graphicEntity,ie);e.enabled=s.isOn,t.insert(s.graphicEntity,ie,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},$r=vn,Or=N("ProgressBar",{value:0,fillEntity:0,direction:vn.LeftToRight});function Hr(e,t,s,n){if(!e.has(t,Sn))return;const r=e.get(t,Sn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=bn(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,a,r.pivot);if(e.has(t,ie)){const s=e.get(t,ie);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ie,s))}if(e.has(t,ne)){const s=e.get(t,ne),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,ne,s))}}class Xr{build(e){J("ProgressBar",Or);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e=t.getEntitiesWithComponents([Or,Sn]);for(const s of e){const e=t.get(s,Or);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Sn),r=Math.max(0,Math.min(1,e.value));Cn(t,e.fillEntity,e.direction,r);const o=Bn(n,s),i=Dn(n,s);Hr(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const jr=new Xr,Yr=N("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Nr=N("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Vr=new class{build(e){J("Draggable",Yr),J("DragState",Nr);const t=e.world,s=e.getResource(fr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(it),Se(ct)],(e,i)=>{if(xr()&&!wr())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Yr,dr]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Yr).enabled)continue;if(t.get(n,dr).hovered){let e=0;t.has(n,ie)&&(e=t.get(n,ie).layer);const r=kn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,Nr)||t.insert(s,Nr);const e=t.get(s,Nr),o=t.get(s,ne);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Nr)){t.get(n,Nr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Yr);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Nr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Nr))return void(o=null);const n=t.get(o,Nr),r=t.get(o,Yr),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-p},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,ne)){const e=function(e,t,s,n){if(!e.has(t,de))return{x:s,y:n};const r=e.get(t,de).entity;if(!e.valid(r)||!e.has(r,ne))return{x:s,y:n};const o=e.get(r,ne),i=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=nr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,ne);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ne,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Gr=N("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function qr(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function Kr(e,t,s,n,r){const o=2/(n=Math.max(1e-4,n)),i=o*r,a=1/(1+i+.48*i*i+.235*i*i*i),l=e-t,c=(s+o*l)*r,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const Jr=new class{build(e){J("ScrollView",Gr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(it),Se(ct),Se(Ee)],(e,r,o)=>{const i=xr()&&!wr(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);r.valid&&(n.x=r.worldMouseX,n.y=r.worldMouseY);const l=t.getEntitiesWithComponents([Gr,Sn]);for(const o of l){Ln(t,o,Zn,{enabled:!0,mode:Jn});const l=t.get(o,Gr),c=t.get(o,Sn);let d=s.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,d));const u=Bn(c,o),h=Dn(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue).entities;let s=0,n=0,r=0,o=0;for(const i of e){if(!t.valid(i)||!t.has(i,ne))continue;const e=t.get(i,ne);let a=0,l=0,c=.5,d=.5;if(t.has(i,Sn)){const e=t.get(i,Sn);a=Bn(e,i)||e.size.x,l=Dn(e,i)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(i,ie)){const e=t.get(i,ie);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*d,f=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),p<r&&(r=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-r)}const g=Math.max(0,p-u),y=Math.max(0,f-h);if(!i&&r.valid){Ln(t,o,cr,{enabled:!0,blockRaycast:!0});const s=t.has(o,dr)?t.get(o,dr):null;if(s?.justPressed&&(d.isDragging=!0,d.lastWorldX=n.x,d.lastWorldY=n.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=n.x-d.lastWorldX,t=n.y-d.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=qr(l.scrollX,0,g,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=qr(l.scrollY,0,y,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=qr(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=qr(l.scrollX,0,g,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Kr(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<$n&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>$n?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Kr(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<$n&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>$n?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ne)){const e=t.get(l.contentEntity,ne),s=e.position.x,n=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(s-d.lastAppliedX)>.01)&&(d.contentBaseX=s),(isNaN(d.lastAppliedY)||Math.abs(n-d.lastAppliedY)>.01)&&(d.contentBaseY=n),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,ne,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Qr=vn,Zr=N("Slider",{value:0,minValue:0,maxValue:1,direction:vn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function eo(e,t,s,n,r,o){const i=Bn(n,r)*s.worldScale.x,a=Dn(n,r)*s.worldScale.y,l=nr(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,p=u*d-h*c,f=u*c+h*d,g=-n.pivot.x*i,y=-n.pivot.y*a;switch(o){case vn.LeftToRight:return i>0?(p-g)/i:0;case vn.RightToLeft:return i>0?1-(p-g)/i:0;case vn.BottomToTop:return a>0?(f-y)/a:0;case vn.TopToBottom:return a>0?1-(f-y)/a:0}}function to(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case vn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case vn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case vn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case vn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class so{build(e){J("Slider",Zr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(it),Se(ct),Se(fr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([Zr,Sn]);for(const i of o){const o=t.get(i,Zr),a=t.get(i,Sn);if(!xr()||wr()){if(t.has(i,ne)){Ln(t,i,cr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ln(t,o.handleEntity,cr,{enabled:!0,blockRaycast:!1});const l=t.get(i,ne),c=t.has(i,dr)?t.get(i,dr):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,dr)&&(d=t.get(o.handleEntity,dr).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=eo(n.worldMouseX,n.worldMouseY,l,a,i,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(i,Zr,o),o.value!==c&&r.emit(i,"change")}s===i&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Bn(a,i),u=Dn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Cn(t,o.fillEntity,o.direction,c),Wn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Sn)){const e=t.get(o.handleEntity,Sn);to(e,o.direction,c),t.insert(o.handleEntity,Sn,e),Wn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const no=new so;const ro=new class{build(e){J("Focusable",Mr);const t=e.world,s=new Er;e.insertResource(Cr,s),e.addSystemToSchedule(exports.Schedule.Update,st([Se(it),Se(fr)],(e,n)=>{if(xr()&&!wr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([Mr]);for(const e of r){if(!t.has(e,dr))continue;t.get(e,dr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,cr)){if(!t.get(s,cr).enabled)continue}const n=t.get(s,Mr);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,Mr)){t.get(r,Mr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,Mr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},oo=N("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function io(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const ao=new class{build(e){J("SafeArea",oo);const t=e.world;let n=io(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=io(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=io(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(ct)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=d(),c=s()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([oo,Sn]);for(const e of u){const s=t.get(e,oo),r=t.get(e,Sn),o=s.applyTop?n.top*c:0,i=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},d=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,Sn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},lo=N("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let co=null;const uo=new class{build(e){J("ListView",lo);const t=e.world,s=new Map;co=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(it)],e=>{const n=xr()&&!wr();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const r=t.getEntitiesWithComponents([lo,Sn]);for(const o of r){Ln(t,o,cr,{enabled:!0,blockRaycast:!0}),Ln(t,o,Zn,{enabled:!0,mode:Jn});let r=s.get(o);r||(r={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,r));const i=t.get(o,lo),a=t.get(o,Sn),l=Dn(a,o),c=Bn(a,o);if(!n){const s=t.has(o,dr)?t.get(o,dr):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}}const d=Math.max(0,i.itemCount*i.itemHeight-l);i.scrollY=Math.max(0,Math.min(i.scrollY,d));const u=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+l)/i.itemHeight)+i.overscan);for(const[e,s]of r.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),r.itemEntities.delete(e));for(let e=u;e<h;e++){let s=r.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,fe,{value:`ListItem_${e}`}),t.insert(s,Sn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),r.itemEntities.set(e,s),r.renderer&&r.renderer(e,s)),t.has(s,ne)){const n=t.get(s,ne);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(s,ne,n)}}r.visibleStart=u,r.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},ho=N("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const po=new class{build(e){J("Dropdown",ho);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ne))return;const s=t.get(e,ne);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ne,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function r(e){if(t.has(e,ie)){const s=t.get(e,ie);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ie,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const r=s.listEntity;if(0===r||!t.valid(r))return;d(r,!0),c(n);const o=t.get(e,ie),i=o.size.x,a=o.size.y;n.ddWidth=i;const l=s.options.length*On;t.insert(r,Sn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:l},pivot:{x:.5,y:.5}}),t.insert(r,ne,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,ie,{texture:$,color:{r:1,g:1,b:1,a:1},size:{x:i,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*On;t.insert(o,fe,{value:`Option_${e}`}),t.insert(o,Sn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*On},offsetMax:{x:0,y:0},size:{x:i,y:On},pivot:{x:.5,y:.5}}),t.insert(o,ne,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,ie,{texture:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:i,y:On},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,cr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ne,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Nn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Xn.Left,verticalAlign:jn.Middle,wordWrap:!1,overflow:Yn.Clip,lineHeight:1.2}),t.insert(c,Sn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:On},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function i(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,r){t.selectedIndex=n,i(0,t,s),r.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Nn))return;const n=t.get(s,Nn);let r={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,i=!1;if(1===r.r&&1===r.g&&1===r.b&&1===r.a&&(r={r:0,g:0,b:0,a:1},i=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,i=!0)}i&&t.insert(s,Nn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:r,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,cr)&&t.insert(e,cr,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ie))){const n=t.get(e,ie);t.insert(e,ie,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function u(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ie))continue;const r=s===e.highlightIndex?{...Hn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ie,{texture:$,color:r,size:{x:e.ddWidth,y:On},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,dr))continue;if(t.get(s,dr).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,st([Se(it),Se(fr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=xr()&&!wr(),f=t.getEntitiesWithComponents([ho]);for(const g of f){const f=t.get(g,ho);let y=s.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(g,y)),n(f.listEntity),r(g),f.isOpen||d(f.listEntity,!1),l(f),p)continue;Ln(t,g,cr,{enabled:!0,blockRaycast:!0});const m=t.has(g,dr)?t.get(g,dr):null;if(m?.justPressed&&(f.isOpen?i(g,f,y):o(g,f,y)),f.isOpen){for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,dr))continue;if(t.get(s,dr).justPressed){a(g,f,y,e,c);break}}let s=-1;for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,dr))continue;if(t.get(n,dr).hovered){s=e;break}}s>=0&&s!==y.highlightIndex&&(y.highlightIndex=s,u(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=f.options.length-1?y.highlightIndex=0:y.highlightIndex++,u(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=f.options.length-1:y.highlightIndex--,u(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,f,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&i(g,f,y),e.isMouseButtonPressed(0)&&(m?.hovered||h(y)||i(g,f,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},fo=0,go=0,yo=2,mo=N("LayoutGroup",{direction:fo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:go,reverseOrder:!1});const _o=new class{build(e){J("LayoutGroup",mo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e=t.getEntitiesWithComponents([mo,Sn,ue]);for(const s of e){const e=t.get(s,mo),n=t.get(s,Sn),r=t.get(s,ue);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Sn)&&t.has(e,ne)&&o.push({entity:e,rect:t.get(e,Sn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=Bn(n,s),a=Dn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===fo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=Bn(n.rect,n.entity),p=Dn(n.rect,n.entity),f=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;u?(y=-l*i+d.left+h+f*r,m=e.childAlignment===go?(1-c)*a-d.top-(1-g)*p:e.childAlignment===yo?-c*a+d.bottom+g*p:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*p,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===go?-l*i+d.left+f*r:e.childAlignment===yo?(1-l)*i-d.right-(1-f)*r:(.5-l)*i+.5*(d.left-d.right)+(f-.5)*r,m=(1-c)*a-d.top-h-(1-g)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,ne);_.position.x=y,_.position.y=m,t.insert(n.entity,ne,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Z("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Z("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class xo{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,st([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const wo=new xo;async function vo(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const bo=be({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),So=be(null,"PhysicsAPI");function Po(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function To(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Mo{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(bo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=vo(this.wasmUrl_,this.factory_).then(n=>{n._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([le]);for(const s of t){const t=e.world.get(s,le);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;i.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(Ee)],a=>{const l=i.getEntitiesWithComponents([ye,ne]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,ye),l=i.get(r,ne);if(t.has(r)){const e=s.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||(n._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=Po(l.worldRotation);n._physics_createBody(r,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Eo(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===we.Kinematic){const e=Po(l.worldRotation);n._physics_setBodyTransform(r,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,ne);if(!d)continue;let u=a,h=l,p=c;if(e.world.has(i,de)){const t=e.world.get(i,de);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ne)){const s=e.world.get(t.entity,ne),n=Po(s.worldRotation),r=a-s.worldPosition.x,o=l-s.worldPosition.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(r*d+o*i)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}d.position.x=u,d.position.y=h;const f=To(p);d.rotation.w=f.w,d.rotation.x=f.x,d.rotation.y=f.y,d.rotation.z=f.z,e.world.insert(i,ne,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],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;n.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]*s,contactY:t.HEAPF32[r+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 n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(bo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(So,Co._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Eo(e,t,s){const n=e.world;if(n.has(s,me)){const e=n.get(s,me);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(n.has(s,_e)){const e=n.get(s,_e);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(n.has(s,xe)){const e=n.get(s,xe);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 Co{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(Co.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)}}const Ao={nearest:0,linear:1},Ro={repeat:0,clamp:1,mirror:2};function Io(e,t,s=!0,n){const r=e.getResourceManager(),o=e._malloc(t.pixels.length);let i;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&r.createTextureEx){const e=Ao[n.filterMode??"linear"]??1,a=Ro[n.wrapMode??"clamp"]??1;i=r.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else i=r.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),i}function Fo(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 ko(e,t,s,n){const r=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),i=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,p=c+c,f=a*u,g=a*h,y=a*p,m=l*h,_=l*p,x=c*p,w=d*u,v=d*h,b=d*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(f+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(f+m))*i,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Bo(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={},r=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Wt(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=r?.[o];n[o]=Io(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=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),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=zt(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),d=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===_(c)?.contentType;let u,h;if(i){const e=await r.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const p=s.loadSkeleton(u,h,n,n.length,i);if(t._free(u),p<0)continue;o[a]=p;const f=Fo(n),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=g+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=Io(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){const t={gravity:i?.gravity??{...D},fixedTimestep:i?.fixedTimestep??U,subStepCount:i?.subStepCount??4};new Mo("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){const r=Wt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=_(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=Io(e,c,!1),u=e.getResourceManager();n[o]=u.loadBitmapFont(t,d,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=Wt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=xt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=xt.createFromAsset(e,i)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Wt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=r[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(s,c,h,p);const f=jt(e.world,s);if(l&&e.hasResource(tn))for(const t of f.values())e.world.insert(t,ge,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=zt(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(u,s,d,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=B);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,pe)?c.get(o,pe):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,ne)){const e=ko(c.get(o,ne),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,p);const f=s.HEAPU32[u>>2],g=s.HEAPU32[p>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,f,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(p)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Kt);t&&t.setAddressableManifest(a)}}function Do(e,t,s){return{name:e,async setup(){await Bo(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class Uo{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,n=new Set;for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=zt(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===_(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Wt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}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(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=_(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}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),n=await s.blob(),r=await createImageBitmap(n),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 Lo="__preview__";const Wo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ys.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ys.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ys.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ys.releaseRenderTarget(e._handle),Wo.create({width:t,height:s,depth:!0})),begin(e,t){Ys.begin(t,e._handle)},end(){Ys.end()},getDepthTexture:e=>Ys.getTargetDepthTexture(e._handle)};var zo;exports.LogLevel=void 0,(zo=exports.LogLevel||(exports.LogLevel={}))[zo.Debug=0]="Debug",zo[zo.Info=1]="Info",zo[zo.Warn=2]="Warn",zo[zo.Error=3]="Error";class $o{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Oo{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new $o)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Ho=new Oo;const Xo={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},jo={None:0,Restart:1,PingPong:2};class Yo{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let No=null,Vo=null;function Go(e,t){No=e,Vo=t}function qo(){No=null,Vo=null}function Ko(){if(!No)throw new Error("Tween API not initialized");return No}function Jo(){if(!Vo)throw new Error("Tween API not initialized");return Vo}const Qo={to(e,t,s,n,r,o){const i=Ko(),a=Jo(),l=o?.easing??Xo.Linear,c=o?.delay??0,d=o?.loop??jo.None,u=o?.loopCount??0,h=i._anim_createTween(a,e,t,s,n,r,l,c,d,u);return new Yo(i,a,h)},cancel(e){Ko()._anim_cancelTween(Jo(),e.entity)},cancelAll(e){Ko()._anim_cancelAllTweens(Jo(),e)},update(e){Ko()._anim_updateTweens(Jo(),e)}};class Zo{constructor(){this.name="AnimationPlugin"}build(e){Go(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,st([Se(Ee)],e=>{Qo.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,st([Se(Ee)],e=>{Dt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){qo()}}const ei=new Zo;class ti{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const r=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(r.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function si(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}const ni=[Kn,lr,yr,Ur,jr,Pr,Vr,Jr,no,zr,Rr,ro,ao,uo,po,_o,wo],ri=[...ni,ei];function oi(e,t){return function(e,t){const s=on.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ps(e),yt(e),Rs(e),Ds(e),Xs(e),Vs(e);const r=new Ks;s.setPipeline(r);let o=c();const i=t?.getViewportSize??(()=>{const e=d();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=hn(e,n,t,r));const i=s.getResource(ct);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)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.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}s.insertResource(ct,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;Ys.setClearColor(e.x,e.y,e.z,e.w)}const u=(c()-o)/1e3;let h;if(Ys.resize(t,l),Ws.isInitialized()&&Ws.getPassCount()>0&&!Ws.isBypassed()&&Ws.resize(t,l),s.hasResource(tn)){const e=s.getResource(tn).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=hn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:ln,width:t,height:l,elapsed:u});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Ys.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Qt),s.addPlugin(as),s.addPlugin(lt),s.addPlugin(rn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:ri,...t})}class ii{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await r(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function ai(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function li(e,t){try{return await e({instantiateWasm:ai(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}R||(R=!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(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await u(s,n);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: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 h(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 n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),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 n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=I,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=Zo,exports.App=on,exports.AssetPlugin=Jt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=qt,exports.Assets=Kt,exports.AsyncCache=Ct,exports.BitmapText=he,exports.BodyType=we,exports.BoxCollider=me,exports.Button=hr,exports.ButtonState=ur,exports.Camera=ae,exports.Canvas=le,exports.CapsuleCollider=xe,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=ue,exports.CircleCollider=_e,exports.ClearFlags=te,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=qe,exports.DEFAULT_DESIGN_HEIGHT=k,exports.DEFAULT_DESIGN_WIDTH=F,exports.DEFAULT_FALLBACK_DT=B,exports.DEFAULT_FIXED_TIMESTEP=U,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=D,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=Nr,exports.Draggable=Yr,exports.Draw=ms,exports.Dropdown=ho,exports.EasingType=Xo,exports.EntityCommands=Ge,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Ze,exports.EventRegistry=Je,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Qe,exports.FillDirection=vn,exports.FillMethod=Fr,exports.FillOrigin=kr,exports.FocusManager=Cr,exports.FocusManagerState=Er,exports.Focusable=Mr,exports.GLDebug=qs,exports.Geometry=ks,exports.GetWorld=function(){return{_type:"get_world"}},exports.INVALID_ENTITY=0,exports.INVALID_FONT=O,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=$,exports.Image=Br,exports.ImageType=Ir,exports.Input=it,exports.InputPlugin=at,exports.InputState=ot,exports.Interactable=cr,exports.ListView=lo,exports.LocalTransform=re,exports.Logger=Oo,exports.LoopMode=jo,exports.Material=xt,exports.MaterialLoader=At,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=fe,exports.Parent=de,exports.Physics=Co,exports.PhysicsEvents=bo,exports.PhysicsPlugin=Mo,exports.PostProcess=Ws,exports.PrefabServer=rs,exports.Prefabs=os,exports.PrefabsPlugin=is,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(tn);t.register({name:Lo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Lo),this.loadPromise_=t.load(Lo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;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 Uo(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Bo(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,Lo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([ae]);for(const n of s){if(e.get(n,ae).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([le]);for(const r of n){const n=e.get(r,le);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(tn).getScene(Lo),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,ne,i);const a={isActive:!0,projectionType:ee.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:te.ColorAndDepth};e.insert(o,ae,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(tn);await e.switchTo(Lo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=Or,exports.ProgressBarDirection=$r,exports.ProgressBarPlugin=Xr,exports.ProjectionType=ee,exports.Query=function(...e){return Ye(e)},exports.QueryInstance=Ne,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ve,exports.RenderPipeline=Ks,exports.RenderTexture=Wo,exports.Renderer=Ys,exports.Res=Se,exports.ResMut=Pe,exports.RigidBody=ye,exports.RuntimeConfig=L,exports.SafeArea=oo,exports.ScaleMode=se,exports.SceneManager=tn,exports.SceneManagerState=en,exports.SceneOwner=ge,exports.ScrollView=Gr,exports.ShaderSources=Et,exports.Slider=Zr,exports.SliderDirection=Qr,exports.SliderPlugin=so,exports.SpineAnimation=pe,exports.Sprite=ie,exports.SpriteAnimator=Bt,exports.SystemRunner=rt,exports.Text=Nn,exports.TextAlign=Xn,exports.TextInput=Tr,exports.TextInputPlugin=Ar,exports.TextOverflow=Yn,exports.TextPlugin=qn,exports.TextRenderer=Vn,exports.TextVerticalAlign=jn,exports.Time=Ee,exports.Toggle=Lr,exports.Transform=ne,exports.Tween=Qo,exports.TweenHandle=Yo,exports.TweenState={Running:0,Paused:1,Completed:2,Cancelled:3},exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UICameraInfo=ct,exports.UIEventQueue=pr,exports.UIEvents=fr,exports.UIInteraction=dr,exports.UIInteractionPlugin=Sr,exports.UILayoutPlugin=gr,exports.UIMask=Zn,exports.UIMaskPlugin=ar,exports.UIRect=Sn,exports.UIRenderOrderPlugin=xo,exports.Velocity=ce,exports.WeChatAssetProvider=ii,exports.WebAssetProvider=Uo,exports.World=$e,exports.WorldTransform=oe,exports.addStartupSystem=function(e){nt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){nt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){nt().push({schedule:e,system:t})},exports.animationPlugin=ei,exports.applyBuildRuntimeConfig=z,exports.applyDirectionalFill=Cn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=L.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=L.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=L.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=L.canvasMatchWidthOrHeight)},exports.assetPlugin=Qt,exports.clearAnimClips=function(){Ft.clear()},exports.clearDrawCallbacks=Ps,exports.clearUserComponents=function(){const e=Y();for(const t of e.keys())K.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=En,exports.computeFillSize=function(e,t,s,n){switch(e){case vn.BottomToTop:case vn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case vn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case vn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case vn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}},exports.computeUIRectLayout=bn,exports.createMaskProcessor=ir,exports.createRuntimeSceneConfig=Do,exports.createWebApp=oi,exports.debug=function(e,t,s){Ho.debug(e,t,s)},exports.defineComponent=N,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=be,exports.defineSystem=st,exports.defineTag=function(e){const t=K.get(e)??Y().get(e);if(t)return t;const s=j(e,{});return Y().set(e,s),K.set(e,s),G(e,{},!0),s},exports.error=function(e,t,s){Ho.error(e,t,s)},exports.extractAnimClipTexturePaths=Rt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([fe]);for(const n of s){const s=e.get(n,fe);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=an,exports.getAddressableType=function(e){return _(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of p)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return y},exports.getAnimClip=function(e){return Ft.get(e)},exports.getAssetMimeType=function(e){return f[e.toLowerCase()]},exports.getAssetTypeEntry=_,exports.getComponent=Q,exports.getComponentAssetFieldDescriptors=Wt,exports.getComponentAssetFields=Lt,exports.getComponentDefaults=function(e){const t=Q(e);return t?H(t._default):null},exports.getComponentEntityFields=Ot,exports.getComponentSpineFieldDescriptor=zt,exports.getCustomExtensions=w,exports.getEditorType=function(e){return _(e)?.editorType??"unknown"},exports.getLogger=function(){return Ho},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=V,exports.getWeChatPackOptions=function(){return w().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Ho.info(e,t,s)},exports.initDrawAPI=ps,exports.initGLDebugAPI=Vs,exports.initGeometryAPI=Rs,exports.initMaterialAPI=yt,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,sceneData:r,sceneName:o}=e,i=t.getResource(Kt);i&&(i.registerEmbeddedAssets(n),i.setEmbeddedOnly(!0)),an(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await si(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await si(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Do(o,r,{app:t,module:s,provider:new ti(n),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(tn);d.register(c),d.setInitial(o),await d.load(o);const u=e.canvas.width/e.canvas.height;Gt(t.world,u),t.run()},exports.initPostProcessAPI=Ds,exports.initRendererAPI=Xs,exports.initTweenAPI=Go,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=b(e),r=t[e]||t[n]||s[n]||s[e];return r?r.path:n}}(function(e){const t={},s={};for(const n in e.groups){const r=e.groups[n];for(const e in r.assets){const n=r.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),r=wx.createCanvas(),i=wx.getSystemInfoSync();r.width=i.windowWidth*i.pixelRatio,r.height=i.windowHeight*i.pixelRatio;const a=await e.engineFactory({canvas:r,instantiateWasm:ai("esengine.wasm")}),l=r.getContext("webgl2")||r.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),d=oi(a,{glContextHandle:c,getViewportSize:()=>({width:r.width,height:r.height})});e.runtimeConfig&&z(d,e.runtimeConfig),an(d);let u=null;e.spineFactory&&(u=await li(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await li(e.physicsFactory,"physics.wasm"));const p={app:d,module:a,provider:new ii(n),spineModule:u,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s},f=d.getResource(tn);for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`),s=JSON.parse(e);f.register(Do(t,s,p))}e.firstScene&&(f.setInitial(e.firstScene),await f.load(e.firstScene));const g=r.width/r.height;Gt(d.world,g),d.run()},exports.inputPlugin=lt,exports.instantiatePrefab=Zt,exports.intersectRects=er,exports.invertMatrix4=tr,exports.isBuiltinComponent=q,exports.isCustomExtension=v,exports.isEditor=xr,exports.isKnownAssetExtension=x,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=wr,exports.isRuntime=function(){return!mr},exports.isTextureRef=ut,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Vt,exports.loadPhysicsModule=vo,exports.loadRuntimeScene=Bo,exports.loadSceneData=jt,exports.loadSceneWithAssets=Yt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&x(m(e)))},exports.parseAnimClipData=It,exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=a,exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,r,o,i,a,l,c){const d=nr(l,c),u=Math.sin(-d),h=Math.cos(-d),p=e-s,f=t-n,g=p*h-f*u+s,y=p*u+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=as,exports.progressBarPlugin=jr,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=kt,exports.registerComponent=J,exports.registerComponentAssetFields=function(e,t){Ut.set(e,t)},exports.registerComponentEntityFields=function(e,t){$t.set(e,t)},exports.registerDrawCallback=bs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Kt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Mt,exports.remapEntityFields=Ht,exports.sceneManagerPlugin=rn,exports.screenToWorld=sr,exports.setEditorMode=function(e){mr=e},exports.setListViewRenderer=function(e,t){if(!co)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=co.get(e);s?s.renderer=t:co.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Ho.setMinLevel(e)},exports.setPlayMode=function(e){_r=e},exports.setWasmErrorHandler=Fe,exports.shutdownDrawAPI=fs,exports.shutdownGLDebugAPI=Gs,exports.shutdownGeometryAPI=Is,exports.shutdownMaterialAPI=mt,exports.shutdownPostProcessAPI=Us,exports.shutdownRendererAPI=js,exports.shutdownTweenAPI=qo,exports.sliderPlugin=no,exports.spriteAnimatorSystemUpdate=Dt,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,ie))return;const i=e.get(t,ie);let a,l;switch(s){case vn.BottomToTop:case vn.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,ie,i))},exports.textInputPlugin=Rr,exports.textPlugin=Kn,exports.toBuildPath=b,exports.transitionTo=async function(e,t,s){const n=e.getResource(tn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Pr,exports.uiLayoutPlugin=yr,exports.uiMaskPlugin=lr,exports.uiPlugins=ni,exports.uiRenderOrderPlugin=wo,exports.unregisterAnimClip=function(e){Ft.delete(e)},exports.unregisterComponent=function(e){Y().delete(e),K.delete(e)},exports.unregisterDrawCallback=Ss,exports.updateCameraAspectRatio=Gt,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,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Ho.warn(e,t,s)},exports.wrapSceneSystem=sn,exports.wxFileExists=function(e){return new Promise(t=>{P().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=M,exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=A,exports.wxReadFile=function(e){return new Promise((t,s)=>{P().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(T(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{P().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(T(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{P().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(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}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function d(e,t){return new Promise((s,n)=>{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,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,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=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function h(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}`)}}const p=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],f={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},g=new Map,m=new Set;for(const e of p)for(const t of e.extensions)g.set(t,e),m.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function _(e){return g.get(y(e))}function x(e){return m.has(e.toLowerCase())}function w(){const e=[];for(const t of p)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function v(e){const t=_(e);return t?.wechatPackInclude??!1}function b(e){const t=_(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let S=null;function P(){return S||(S=wx.getFileSystemManager()),S}function M(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(v(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function T(e){const t=P();try{return t.accessSync(e),!0}catch{return!1}}function E(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}async function A(e){return C(await E(e))}let R=!1;const I=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return d(e,t)}async readFile(e){return function(e){return P().readFileSync(e)}(b(e))}async readTextFile(e){return function(e,t="utf-8"){return P().readFileSync(e,t)}(b(e))}async fileExists(e){return T(b(e))}async loadImagePixels(e){return A(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return h(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),r="function"==typeof wx.onKeyDown;r&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},i=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(i),wx.onTouchEnd(a),this.inputCleanup_=()=>{r&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(i),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},F=1920,k=1080,B=1/60,D={x:0,y:-9.81},U=1/60,L={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function W(e,t){if(void 0!==t.maxDeltaTime&&(L.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(L.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(L.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(L.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(L.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");L.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(L.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(L.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=4294967295,O=4294967295;function H(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(H);const t={};for(const s in e)t[s]=H(e[s]);return t}let X=0;function j(e,t){const s=++X,n=function(e){for(const t in e){const s=e[t];if(null!==s&&"object"==typeof s)return!0}return!1}(t);return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>n?e?{...H(t),...e}:H(t):e?{...t,...e}:{...t}}}function N(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Y(e,t){const s=K.get(e)??N().get(e);if(s)return s;const n=j(e,t);return N().set(e,n),K.set(e,n),G(e,t,!1),n}function V(e){return N().get(e)}function G(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function q(e){return!0===e._builtin}const K=new Map;function J(e,t){K.set(e,t)}function Q(e){return K.get(e)??V(e)}function Z(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return K.set(e,s),s}const ee={Perspective:0,Orthographic:1},te={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ne=Z("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),re=ne,oe=ne,ie=Z("Sprite",{texture:$,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,enabled:!0}),ae=Z("Camera",{projectionType:ee.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:te.ColorAndDepth}),le=Z("Canvas",{designResolution:{x:F,y:k},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ce=Z("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ue=Z("Parent",{entity:0}),de=Z("Children",{entities:[]}),he=Z("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:O,enabled:!0}),pe=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,enabled:!0}),fe=Y("Name",{value:""}),ge=Y("SceneOwner",{scene:"",persistent:!1});const me=Z("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ye=Z("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e=Z("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=Z("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),we={Static:0,Kinematic:1,Dynamic:2};let ve=0;function be(e,t){const s=++ve;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Se(e){return{_type:"res",_resource:e}}function Pe(e){return{_type:"res_mut",_resource:e}}class Me{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_)}updateValue(e){this.value_=e}}class Te{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ee=be({delta:0,elapsed:0,frameCount:0},"Time");function Ce(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ae(t[e]),o=Ae(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function Ae(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Re(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Ie=null;function Fe(e){Ie=e}function ke(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ie&&Ie(e,t)}function Be(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="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}:n}}return s}let De=1;const Ue=new WeakMap;function Le(e){let t=Ue.get(e);return void 0===t&&(t=De++,Ue.set(e,t)),t}const ze=[];function We(e,t=[],s=[]){ze.length=0;for(const t of e)ze.push(Le(t));ze.sort((e,t)=>e-t);let n=ze.join(",");if(t.length>0){ze.length=0;for(const e of t)ze.push(Le(e));ze.sort((e,t)=>e-t),n+="|+"+ze.join(",")}if(s.length>0){ze.length=0;for(const e of s)ze.push(Le(e));ze.sort((e,t)=>e-t),n+="|-"+ze.join(",")}return n}class $e{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw ke(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){ke(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){ke(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ke(t,`removeParent(entity=${e})`)}}insert(e,t,s){return q(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(q(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Be(s))}catch(s){ke(s,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,s),this.recordChangedTick_(t,e)}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)}tryGet(e,t){if(q(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return ke(s,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");q(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:r.bind(s),has:o.bind(s),remove:i.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Ce(t._name,t._default,n);if(e.length>0)throw new Error(Re(t._name,e))}const r={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Be(r))}catch(s){ke(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const r=t[n];if(null!=r&&"object"==typeof r&&!Array.isArray(r)&&"r"in r&&"g"in r&&"b"in r&&"a"in r){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const r=e[s],o=t[s];if(null==r||"object"!=typeof r||Array.isArray(r)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=r;else{const e=r,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:r}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return ke(s,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(s){return ke(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){ke(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Ce(t._name,t._default,e);if(r.length>0)throw new Error(Re(t._name,r));n=e}const r=t.create(n),o=this.getStorage(t),i=!o.has(e);o.set(e,r);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),i&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),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),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of K)if(q(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=N();for(const n of s)for(const[s,r]of e)if(r._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const r=n??We(e,t,s),o=this.queryCache_.get(r);if(o&&o.version===this.worldVersion_)return o.result;let i=null,a=1/0;for(const t of e)if(!q(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=i?i.keys():this.entities_.keys();for(const n of c){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}if(r)for(const e of t)if(!this.has(n,e)){r=!1;break}if(r)for(const e of s)if(this.has(n,e)){r=!1;break}r&&l.push(n)}return this.queryCache_.set(r,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Oe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function He(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Xe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function je(e){return Oe(e)||He(e)||Xe(e)?e._component:e}function Ne(e,t=[],s=[]){const n=[],r=[],o=[];return e.forEach((e,t)=>{Oe(e)&&n.push(t),He(e)?r.push({index:t,component:e._component}):Xe(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:r,_changedFilters:o,with:(...n)=>Ne(e,[...t,...n],s),without:(...n)=>Ne(e,t,[...s,...n])}}class Ye{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(je),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=We(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,r=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,i=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}i[0]=u;for(let e=0;e<n;e++)i[e+1]=this.world_.get(u,t[e]);if(r){for(let t=0;t<l;t++)a[t].data=i[e[t]+1];c=u}yield i}}finally{if(this.world_.endIteration(),null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,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(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class Ve{constructor(e,t,s){this.world_=e,this.component_=t,this.lastRunTick_=s}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}class Ge{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=q(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 qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ge(this,null);return this.spawned_.push(e),e}entity(e){return new Ge(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class Ke{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class Je{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ke)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ke,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Qe{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ze{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var et;exports.Schedule=void 0,(et=exports.Schedule||(exports.Schedule={}))[et.Startup=0]="Startup",et[et.First=1]="First",et[et.PreUpdate=2]="PreUpdate",et[et.Update=3]="Update",et[et.PostUpdate=4]="PostUpdate",et[et.Last=5]="Last",et[et.FixedPreUpdate=10]="FixedPreUpdate",et[et.FixedUpdate=11]="FixedUpdate",et[et.FixedPostUpdate=12]="FixedPostUpdate";let tt=0;function st(e,t,s){const n=++tt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function nt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class rt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof qe&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ye(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new qe(this.world_,this.resources_);case"event_writer":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Qe(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ze(s)}case"removed":{const t=e;return new Ve(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ot{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 it=be(new ot,"Input");class at{constructor(e){this.target_=e??null}build(e){const s=new ot;e.insertResource(it,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,n){s.mouseX=t,s.mouseY=n,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,st([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const lt=new at,ct=be({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var ut;function dt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(ut=exports.BlendMode||(exports.BlendMode={}))[ut.Normal=0]="Normal",ut[ut.Additive=1]="Additive",ut[ut.Multiply=2]="Multiply",ut[ut.Screen=3]="Screen",ut[ut.PremultipliedAlpha=4]="PremultipliedAlpha";let ht=null,pt=null,ft=1;const gt=new Map;function mt(e){ht=e,pt=e.getResourceManager(),Tt()}function yt(){0!==vt&&ht&&(ht._free(vt),vt=0),gt.clear(),ft=1,wt=!1,St.clear(),Pt=null,pt=null,ht=null}function _t(){if(!pt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pt}const xt={createShader:(e,t)=>_t().createShader(e,t),releaseShader(e){e>0&&_t().releaseShader(e)},create(e){const t=ft++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??exports.BlendMode.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,n]of Object.entries(e.uniforms))s.uniforms.set(t,n);return gt.set(t,s),t},get:e=>gt.get(e),setUniform(e,t,s){const n=gt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,ht?.invalidateMaterialCache(e))},getUniform(e,t){const s=gt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=gt.get(e);s&&(s.blendMode=t,ht?.invalidateMaterialCache(e))},getBlendMode(e){const t=gt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=gt.get(e);s&&(s.depthTest=t,ht?.invalidateMaterialCache(e))},getShader(e){const t=gt.get(e);return t?.shader??0},release(e){gt.delete(e),ht?.invalidateMaterialCache(e)},isValid:e=>gt.has(e),releaseAll(){gt.clear(),ht?.clearMaterialCache()},createFromAsset(e,t){const s={};for(const[t,n]of Object.entries(e.properties))if("number"==typeof n)s[t]=n;else if("object"==typeof n&&null!==n){const e=n;"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=gt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ft++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return gt.set(s,n),s},toAssetData(e,t){const s=gt.get(e);if(!s)return null;const n={};for(const[e,t]of s.uniforms)n[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:s.blendMode,depthTest:s.depthTest,properties:n}},getUniforms(e){const t=gt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wt=!1,vt=0;const bt=16384,St=new Map;let Pt=null;function Mt(e){const t=(0===vt&&ht&&(vt=ht._malloc(bt)),vt);if(0===t||!ht)return{ptr:0,count:0};let s=0,n=0;const r=ht.HEAPU8,o=ht.HEAPU32,i=ht.HEAPF32;for(const[a,l]of e){if(dt(l))continue;let e=St.get(a);e||(Pt||(Pt=new TextEncoder),e=Pt.encode(a),St.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>bt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${bt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,r.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;n++}return{ptr:t,count:n}}function Tt(){if(!ht||wt)return;ht.materialDataProvider=(e,t,s,n,r)=>{const o=gt.get(e);if(!o)return ht.HEAPU32[t>>2]=0,ht.HEAPU32[s>>2]=0,ht.HEAPU32[n>>2]=0,void(ht.HEAPU32[r>>2]=0);ht.HEAPU32[t>>2]=o.shader,ht.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=Mt(o.uniforms);ht.HEAPU32[n>>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 Ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class At{constructor(e,t=""){this.cache_=new Ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(xt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())xt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:xt.createFromAsset(n,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 Rt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function It(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:s.get(e.texture)??0}))}}const Ft=new Map;function kt(e){Ft.set(e.name,e)}const Bt=Y("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Dt(e,t){const s=e.getEntitiesWithComponents([Bt]);for(const n of s){const s=e.get(n,Bt);if(!s.enabled||!s.playing||!s.clip)continue;const r=Ft.get(s.clip);if(!r||0===r.frames.length)continue;const o=1/(r.fps*s.speed),i=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=i;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=r.frames.length&&(s.loop&&r.loop?s.currentFrame=0:(s.currentFrame=r.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ie)){const t=r.frames[s.currentFrame],o=e.get(n,ie);o.texture=t.texture,e.insert(n,ie,o)}a&&e.insert(n,Bt,s)}}class Ut{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const s=this.bufferCache_.get(e);return s?this.backend_.play(s,{bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0}):(this.preload(e).then(()=>{const s=this.bufferCache_.get(e);s&&this.backend_.play(s,{bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0})}),this.createPendingHandle())}static playBGM(e,t){const s=e=>{this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade):this.bgmHandle_&&this.bgmHandle_.stop(),this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:t?.fadeIn?0:t?.volume??1,loop:!0}),t?.fadeIn&&this.fadeIn(this.bgmHandle_,t.fadeIn,t?.volume??1)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&s(t)})}static stopBGM(e){this.bgmHandle_&&(e&&e>0?this.fadeOut(this.bgmHandle_,e):this.bgmHandle_.stop(),this.bgmHandle_=null)}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),r=()=>{const o=(performance.now()-n)/1e3,i=Math.min(o/t,1);e.setVolume(i*s),i<1&&e.isPlaying&&requestAnimationFrame(r)};requestAnimationFrame(r)}static fadeOut(e,t){const s=performance.now(),n=()=>{const r=(performance.now()-s)/1e3,o=Math.min(r/t,1);e.setVolume(1-o),o<1&&e.isPlaying?requestAnimationFrame(n):e.stop()};requestAnimationFrame(n)}static createPendingHandle(){return{id:-1,stop(){},pause(){},resume(){},setVolume(){},setPan(){},setLoop(){},setPlaybackRate(){},isPlaying:!1,currentTime:0,duration:0}}}Ut.mixer_=null,Ut.bufferCache_=new Map,Ut.bgmHandle_=null;const Lt=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function zt(e){const t=Lt.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function Wt(e){return Lt.get(e)?.fields??[]}function $t(e){return Lt.get(e)?.spine??null}const Ot=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ht(e){return Ot.get(e)}function Xt(e,t){const s=Ot.get(e.type);if(!s)return;const n=e.data;for(const r of s){const s=n[r];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${r} references entity ${s} which does not exist`),n[r]=void 0!==o?o:0}}}function jt(e,t){const s=new Map;for(const n of t.entities){if(!1===n.visible)continue;const t=e.spawn();s.set(n.id,t),e.insert(t,fe,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)Xt(r,s),Gt(e,t,r,n.name)}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)}return s}function Nt(e,t){return jt(e,t)}async function Yt(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,r){const o=new Map;for(const e of Vt.keys())o.set(e,new Set);const i=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Lt.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),i.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Vt.entries()].map(async([e,r])=>{const i=await r.load(o.get(e),t,s,n);l.set(e,i)}),u=i.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),r){for(const e of n.values())r.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&r.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)r.fontPaths.add(e);for(const e of a)r.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Lt.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const r=t.get(n);void 0!==r&&(s[e.field]=r)}}}(t,n,r,o,s?.collectAssets);const i=jt(e,t);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 i}const Vt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["anim-clip",{async load(e,t,s,n){const r=[...e].map(async e=>{try{const r=await t.loadJson(e),o=Rt(r),i=new Map,a=o.map(async e=>{try{const r=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),i.set(e,0)}});await Promise.all(a);kt(It(e,r,i))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(r),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await Ut.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Gt(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const r=Q(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function qt(e,t){const s=e.getEntitiesWithComponents([ae]);for(const n of s){const s=e.get(n,ae);s&&(s.aspectRatio=t,e.insert(n,ae,s))}}class Kt{constructor(e){this.textureCache_=new Ct,this.shaderCache_=new Ct,this.jsonCache_=new Ct,this.textCache_=new Ct,this.binaryCache_=new Ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ct,this.prefabCache_=new Ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l(L.textCanvasSize,L.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new At(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}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);if(this.materialLoader_.releaseAll(),xt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),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),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===_(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=_(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}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 n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of zt(e.type)){const n=e.data[s];if("string"==typeof n&&n){const r=t(n);r&&(e.data[s]=r)}}const s=$t(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const r=t(s);r&&(e.data[n]=r)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}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 Yt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((s,n)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(r)},r.onerror=()=>n(new Error(`Failed to load image: ${e}`)),r.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,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,n,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,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(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 r=this.ctx_.getImageData(0,0,t,s),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,s,a,o.length,1,n);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 n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(r,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(b(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 s=this.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);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 s=this.getEmbedded(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 s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.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 n=s.split("/").filter(e=>e);let r="";for(const e of n){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 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 Jt=be(null,"Assets");class Qt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new Kt(t)):console.warn("AssetPlugin: No WASM module available")}}const Zt=new Qt;async function es(e,t,s){const{entities:n,rootId:r}=await ss(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Yt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const ts=10;async function ss(e,t,s,n,r,o=0){if(o>ts)throw new Error(`Prefab nesting depth exceeded ${ts}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ss(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};ns(d.components,i),rs(d,t),l.push(d)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function ns(e,t){for(const s of e){const e=Ht(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const r=t.get(e);void 0!==r&&(s.data[n]=r)}}}}function rs(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 os{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return es(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const is=be(null,"Prefabs");class as{constructor(){this.name="PrefabsPlugin",this.dependencies=[Jt]}build(e){const t=e.getResource(Jt);e.insertResource(is,new os(e.world,t))}}const ls=new as;let cs=null,us=0,ds=0,hs=0;const ps=new Float32Array(256);function fs(e){cs=e,us=cs._malloc(64),ds=cs._malloc(64),hs=cs._malloc(1024)}function gs(){cs&&(us&&(cs._free(us),us=0),ds&&(cs._free(ds),ds=0),hs&&(cs._free(hs),hs=0)),cs=null}function ms(){if(!cs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return cs}const ys={r:1,g:1,b:1,a:1},_s={begin(e){const t=ms();try{t.HEAPF32.set(e,us/4),t.draw_begin(us)}catch(e){ke(e,"Draw.begin")}},end(){try{ms().draw_end()}catch(e){ke(e,"Draw.end")}},line(e,t,s,n=1){try{ms().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){ke(e,"Draw.line")}},rect(e,t,s,n=!0){try{ms().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){ke(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ms().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){ke(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ms().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){ke(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ms().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){ke(e,"Draw.circleOutline")}},texture(e,t,s,n=ys){try{ms().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){ke(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ys){try{ms().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){ke(e,"Draw.textureRotated")}},setLayer(e){ms().draw_setLayer(e)},setDepth(e){ms().draw_setDepth(e)},getDrawCallCount:()=>cs?cs.draw_getDrawCallCount():0,getPrimitiveCount:()=>cs?cs.draw_getPrimitiveCount():0,setBlendMode(e){ms().draw_setBlendMode(e)},setDepthTest(e){ms().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ms();n.HEAPF32.set(s,ds/4),n.draw_mesh(e,t,ds)}catch(s){ke(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ms(),r=xt.get(t);if(!r)return;if(_s.setBlendMode(r.blendMode),_s.setDepthTest(r.depthTest),0===r.uniforms.size)return void _s.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,ds/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=vs(t);if(!(n<0)){if(dt(s))ps[o++]=10,ps[o++]=n,ps[o++]=s.slot??e++,ps[o++]=s.textureId;else if("number"==typeof s)ps[o++]=1,ps[o++]=n,ps[o++]=s;else if(Array.isArray(s)){ps[o++]=s.length,ps[o++]=n;for(let e=0;e<s.length;e++)ps[o++]=s[e]}else"w"in s?(ps[o++]=4,ps[o++]=n,ps[o++]=s.x,ps[o++]=s.y,ps[o++]=s.z,ps[o++]=s.w):"z"in s?(ps[o++]=3,ps[o++]=n,ps[o++]=s.x,ps[o++]=s.y,ps[o++]=s.z):(ps[o++]=2,ps[o++]=n,ps[o++]=s.x,ps[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(ps.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,ds);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),hs/4),n.draw_meshWithUniforms(e,r.shader,ds,hs,o)}catch(s){ke(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},xs={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},ws=new Set;function vs(e){const t=xs[e];return void 0!==t?t:(ws.has(e)||(ws.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(xs).join(", ")}`)),-1)}const bs=new Map;function Ss(e,t,s){bs.set(e,{fn:t,scene:s??""})}function Ps(e){bs.delete(e)}function Ms(){bs.clear()}var Ts;exports.DataType=void 0,(Ts=exports.DataType||(exports.DataType={}))[Ts.Float=1]="Float",Ts[Ts.Float2=2]="Float2",Ts[Ts.Float3=3]="Float3",Ts[Ts.Float4=4]="Float4",Ts[Ts.Int=5]="Int",Ts[Ts.Int2=6]="Int2",Ts[Ts.Int3=7]="Int3",Ts[Ts.Int4=8]="Int4";let Es=null,Cs=0,As=0,Rs=0;function Is(e){Es=e,Cs=Es._malloc(262144),As=Es._malloc(65536),Rs=Es._malloc(256)}function Fs(){Es&&(Cs&&Es._free(Cs),As&&Es._free(As),Rs&&Es._free(Rs),Cs=0,As=0,Rs=0),Es=null}function ks(){if(!Es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Es}const Bs={create(e){const t=ks(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Cs/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,Rs,r).set(o),t.geometry_init(s,Cs,n,Rs,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices16(s,As,n)}else{new Uint32Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices32(s,As,n)}}return s},updateVertices(e,t,s=0){const n=ks(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Cs/4),n.geometry_updateVertices(e,Cs,r,s)},release(e){e>0&&ks().geometry_release(e)},isValid:e=>!(!Es||e<=0)&&Es.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Bs.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,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=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/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;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Bs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-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 Bs.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 Ds=null;function Us(e){Ds=e}function Ls(){Ds&&Ws.isInitialized()&&Ws.shutdown(),Ds=null}function zs(){if(!Ds)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ds}const Ws={init(e,t){try{return zs().postprocess_init(e,t)}catch(s){return ke(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{zs().postprocess_shutdown()}catch(e){ke(e,"PostProcess.shutdown")}},resize(e,t){try{zs().postprocess_resize(e,t)}catch(s){ke(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return zs().postprocess_addPass(e,t)}catch(t){return ke(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{zs().postprocess_removePass(e)}catch(t){ke(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{zs().postprocess_setPassEnabled(e,t)}catch(t){ke(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return zs().postprocess_isPassEnabled(e)}catch(t){return ke(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{zs().postprocess_setUniformFloat(e,t,s)}catch(s){ke(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{zs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){ke(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{zs().postprocess_begin()}catch(e){ke(e,"PostProcess.begin")}},end(){try{zs().postprocess_end()}catch(e){ke(e,"PostProcess.end")}},getPassCount(){try{return zs().postprocess_getPassCount()}catch(e){return ke(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ds)return!1;try{return Ds.postprocess_isInitialized()}catch(e){return ke(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{zs().postprocess_setBypass(e)}catch(e){ke(e,"PostProcess.setBypass")}},isBypassed(){if(!Ds)return!0;try{return Ds.postprocess_isBypassed()}catch(e){return ke(e,"PostProcess.isBypassed"),!0}},createBlur:()=>xt.createShader($s,"#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:()=>xt.createShader($s,"#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:()=>xt.createShader($s,"#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:()=>xt.createShader($s,"#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")},$s="#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 Os;exports.RenderStage=void 0,(Os=exports.RenderStage||(exports.RenderStage={}))[Os.Background=0]="Background",Os[Os.Opaque=1]="Opaque",Os[Os.Transparent=2]="Transparent",Os[Os.Overlay=3]="Overlay";let Hs=null,Xs=0;function js(e){Hs=e,Xs=Hs._malloc(64)}function Ns(){Hs&&Xs&&(Hs._free(Xs),Xs=0),Hs=null}const Ys={init(e,t){Hs?.renderer_init(e,t)},resize(e,t){Hs?.renderer_resize(e,t)},begin(e,t){if(Hs&&Xs)try{Hs.HEAPF32.set(e,Xs/4),Hs.renderer_begin(Xs,t??0)}catch(e){ke(e,"Renderer.begin")}},flush(){try{Hs?.renderer_flush()}catch(e){ke(e,"Renderer.flush")}},end(){try{Hs?.renderer_end()}catch(e){ke(e,"Renderer.end")}},submitSprites(e){if(Hs)try{Hs.renderer_submitSprites(e._cpp)}catch(e){ke(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Hs)try{Hs.renderer_submitBitmapText(e._cpp)}catch(e){ke(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Hs)try{Hs.renderer_submitSpine?.(e._cpp)}catch(e){ke(e,"Renderer.submitSpine")}},setStage(e){Hs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Hs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Hs?.renderer_releaseTarget(e)},getTargetTexture:e=>Hs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Hs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Hs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Hs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Hs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Hs?Hs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Hs?{drawCalls:Hs.renderer_getDrawCalls(),triangles:Hs.renderer_getTriangles(),sprites:Hs.renderer_getSprites(),text:Hs.renderer_getText(),spine:Hs.renderer_getSpine?.()??0,meshes:Hs.renderer_getMeshes(),culled:Hs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Vs=null;function Gs(e){Vs=e}function qs(){Vs=null}const Ks={enable(){Vs?.gl_enableErrorCheck(!0)},disable(){Vs?.gl_enableErrorCheck(!1)},check:e=>Vs?.gl_checkErrors(e)??0,diagnose(){Vs?.renderer_diagnose()}};class Js{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ys.resize(n,r),Ws.isInitialized()&&Ws.getPassCount()>0&&Ws.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ys.setViewport(0,0,n,r),Ys.clearBuffers(3),Ys.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ys.submitSprites(t),Ys.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ys.submitSpine(t),Ys.flush(),this.executeDrawCallbacks(s,o),Ys.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ys.setViewport(n.x,n.y,n.w,n.h),Ys.setScissor(n.x,n.y,n.w,n.h,!0),Ys.clearBuffers(r),Ys.setScissor(0,0,0,0,!1),Ys.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ys.submitSprites(t),Ys.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ys.submitSpine(t),Ys.flush(),this.executeDrawCallbacks(s,o),Ys.end()}executeDrawCallbacks(e,t){const s=bs;if(s.size>0){_s.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}_s.end();for(const e of n)Ps(e)}}}const Qs="__scene_transition_overlay__";class Zs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class en{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,ge,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ss(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ws.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ws.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ge)){const s=this.app_.world.get(e,ge);s.persistent=t,this.app_.world.insert(e,ge,s)}}}class tn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??L.sceneTransitionDuration,r=t.color??{...L.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ss(Qs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;_s.setLayer(9999),_s.setDepth(9999),_s.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Ps(Qs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ps(Qs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ge)){if(this.app_.world.get(e,ge).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Ps(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ws.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:s};this.app_.hasResource(Jt)&&(r.assetServer=this.app_.getResource(Jt));const o=await Yt(this.app_.world,n,r);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,ge,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=nn(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const r=this.contexts_.get(t);s.setup&&await s.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(s){for(const e of t.textureUrls)s.releaseTexture(e);for(const e of t.fontPaths)s.releaseFont(e);for(const e of t.spineKeys)s.releaseSpine(e)}for(const e of t.materialHandles)xt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let r=!1;if(s.has(e,ie)){const t=s.get(e,ie);n.sprite=t.color.a,t.color.a=0,s.insert(e,ie,t),r=!0}if(s.has(e,pe)){const t=s.get(e,pe);n.spine=t.color.a,t.color.a=0,s.insert(e,pe,t),r=!0}if(s.has(e,he)){const t=s.get(e,he);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,he,t),r=!0}r&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ie)){const t=s.get(e,ie);t.color.a=n.sprite,s.insert(e,ie,t)}if(void 0!==n.spine&&s.has(e,pe)){const t=s.get(e,pe);t.color.a=n.spine,s.insert(e,pe,t)}if(void 0!==n.bitmapText&&s.has(e,he)){const t=s.get(e,he);t.color.a=n.bitmapText,s.insert(e,he,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Ws.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const sn=be(null,"SceneManager");function nn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(sn).getSceneStatus(t)&&s._fn(...n)}}}const rn=st([Pe(sn),Se(Ee)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),on={name:"SceneManager",build(e){const t=new tn(e);e.insertResource(sn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(sn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,rn)}};class an{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new Je,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new $e,this.resources_=new Te;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new an}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const r=n.filter(t=>t.system._id!==e);r.length!==n.length&&(this.systems_.set(s,r),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Fe(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(sn).register(e),this}setInitialScene(e){return this.getResource(sn).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new rt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ee)||this.resources_.insert(Ee,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new rt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ee,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,Ms();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[qs,Ns,Ls,Fs,yt,gs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ee);t.delta=e,t.elapsed+=e,t.frameCount++}}function ln(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const cn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function un(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case se.FixedWidth:return o;case se.FixedHeight:return i;case se.Expand:return Math.max(o,i);case se.Shrink:return Math.min(o,i);case se.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}const dn=[];function hn(e){if(e<dn.length)return dn[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return dn.push(t),t}function pn(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ge);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getTransform(e),i=r.viewportW*s/(r.viewportH*n);let a,u=0,d=0;if(r.projectionType===ee.Orthographic){if(d=r.orthoSize,l){d=un(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,i,l.scaleMode,l.matchWidthOrHeight)}u=d*i,a=gn(-u,u,-d,d,-r.farPlane,r.farPlane)}else a=yn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=xn(o.position.x,o.position.y,o.position.z),p=hn(c.length);p.entity=e,p.viewProjection.set(vn(a,h)),p.viewportRect.x=r.viewportX,p.viewportRect.y=r.viewportY,p.viewportRect.w=r.viewportW,p.viewportRect.h=r.viewportH,p.clearFlags=r.clearFlags,p.priority=r.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const fn=new Float32Array(16);function gn(e,t,s,n,r,o){const i=fn;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const mn=new Float32Array(16);function yn(e,t,s,n){const r=mn;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const _n=new Float32Array(16);function xn(e,t,s){const n=_n;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const wn=new Float32Array(16);function vn(e,t){const s=wn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const bn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Sn(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,g,m;e.x===t.x?(p=c+s.x-r.x*i.x,g=p+r.x):(p=c+s.x,g=u+n.x),e.y===t.y?(f=d+s.y-r.y*i.y,m=f+r.y):(f=d+s.y,m=h+n.y);const y=Math.max(0,g-p),_=Math.max(0,m-f);return{originX:p+i.x*y,originY:f+i.y*_,width:y,height:_,rect:{left:p,bottom:f,right:g,top:m}}}const Pn=Z("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}});let Mn=null,Tn=null;function En(e,t){e.has(t,ie)||e.insert(t,ie,{texture:$,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})}function Cn(e,t){switch(e){case bn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case bn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case bn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function An(e,t,s,n){if(!e.has(t,Pn))return;const r=e.get(t,Pn),o=Cn(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,Pn,r)}function Rn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function In(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Fn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(In(i.charCodeAt(0))&&n.length>0&&In(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!In(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function kn(e){let t=1;for(;t<e;)t*=2;return t}function Bn(e,t){let s=0,n=t;for(;e.has(n,ue);){const t=e.get(n,ue).entity;if(!e.valid(t))break;s++,n=t}return s}function Dn(e,t){if(Mn&&Tn){const e=Mn.getUIRectComputedWidth(Tn,t);if(e>0)return e}return e.size.x}function Un(e,t){if(Mn&&Tn){const e=Mn.getUIRectComputedHeight(Tn,t);if(e>0)return e}return e.size.y}function Ln(e,t,s){let n=t;for(;e.has(n,ue);){const t=e.get(n,ue).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function zn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Wn(e,t,s,n,r){if(!e.has(t,Pn))return;const o=e.get(t,Pn),i=Sn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(e.has(t,ie)){const s=e.get(t,ie);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ie,s))}if(e.has(t,ne)){const s=e.get(t,ne);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,ne,s)}}function $n(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const On=.1,Hn=30,Xn={r:.3,g:.5,b:.8,a:1},jn={Left:0,Center:1,Right:2},Nn={Top:0,Middle:1,Bottom:2},Yn={Visible:0,Clip:1,Ellipsis:2},Vn=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:jn.Left,verticalAlign:Nn.Top,wordWrap:!0,overflow:Yn.Visible,lineHeight:1.2});class Gn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l(L.textCanvasSize,L.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,kn(this.frameMaxW_)),e.height=Math.max(e.height,kn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=kn(this.frameMaxW_),e.height=kn(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.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=Fn(s,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===Yn.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)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,kn(p)),n.height=Math.max(n.height,kn(f)));const g=Math.round(255*e.color.r),m=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${m}, ${y}, ${_})`,r&&e.overflow===Yn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(r){switch(e.verticalAlign){case Nn.Top:w=u;break;case Nn.Middle:w=u+(f-2*u-x)/2;break;case Nn.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let v=w;for(const t of l){let n;switch(e.align){case jn.Left:n=u;break;case jn.Center:n=p/2;break;case jn.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=c}r&&e.overflow===Yn.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,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 n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);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[s,n]of this.cache)e(s)||(t.releaseTexture(n.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()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case jn.Left:return"left";case jn.Center:return"center";case jn.Right:return"right"}}}const qn=$n({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Dn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Un(e.uiRect,e.entity):0});class Kn{build(e){J("Text",Vn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Gn(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Vn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,Vn)){if(n.valid(e)&&n.has(e,ie)){const t=n.get(e,ie);n.insert(e,ie,{texture:$,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}r.delete(e)}const e=n.getEntitiesWithComponents([Vn]);for(const t of e){const e=n.get(t,Vn),o=n.has(t,Pn)?n.get(t,Pn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!qn.changed(a,i)){if(n.has(t,ie)&&n.get(t,ie).texture!==$)continue}En(n,t);const l=o?{size:{x:Dn(o,t),y:Un(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ie);n.insert(t,ie,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),r.set(t,qn.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Jn=new Kn,Qn=0,Zn=1,er=Z("UIMask",{enabled:!0,mode:Qn});function tr(e,t){const s=Math.max(e.x,t.x),n=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:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function sr(e,t){const s=t??new Float32Array(16),n=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],g=e[12],m=e[13],y=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*u-i*a,b=r*c-o*l,S=r*u-i*l,P=o*u-i*c,M=d*m-h*g,T=d*y-p*g,E=d*_-f*g,C=h*y-p*m,A=h*_-f*m,R=p*_-f*y;let I=x*R-w*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*C)*I,s[1]=(o*A-r*R-i*C)*I,s[2]=(m*P-y*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-u*T)*I,s[5]=(n*R-o*E+i*T)*I,s[6]=(y*v-g*P-_*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*A-l*E+u*M)*I,s[9]=(r*E-n*A-i*M)*I,s[10]=(g*S-m*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(m*w-g*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function nr(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/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 rr(e,t){return 2*Math.atan2(e,t)}function or(e,t,s,n,r,o,i){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function ir(e,t,s,n,r,o,i){if(!e.has(t,Pn)||!e.has(t,ne))return null;const a=e.get(t,Pn),l=e.get(t,ne),c=Dn(a,t)*l.worldScale.x,u=Un(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,g=-c*p,m=c*(1-p),y=-u*f,_=u*(1-f),x=rr(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[d+g*w-y*v,h+g*v+y*w],[d+m*w-y*v,h+m*v+y*w],[d+m*w-_*v,h+m*v+_*w],[d+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=or(e,t,s,n,r,o,i);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function ar(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([er]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,er);s.enabled&&(d.add(e),s.mode===Zn?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const u=[];for(const e of n){let s=!0;Ln(t,e,e=>{if(r.has(e)){if(t.get(e,er).mode===Qn)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(r.has(s)){if(t.get(s,er).mode===Qn){const e=ir(t,s,o,i,a,l,c);e&&(n=tr(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ir(t,e,o,i,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,r,o,i,a),u.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Ln(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class lr{build(e){if(J("UIMask",er),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ar(e.wasmModule,e.world))}}const cr=new lr,ur=Z("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),dr=Z("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),hr={Normal:0,Hovered:1,Pressed:2,Disabled:3},pr=Y("Button",{state:hr.Normal,transition:null});class fr{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}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 gr=be(new fr,"UIEvents");class mr{build(e){J("UIRect",Pn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){Mn=e,Tn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(ct)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n),s.transform_update(n))},{name:"UILayoutSystem"})),e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(ct)],e=>{e.valid&&(s.uiLayout_update(n,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),s.uiFlexLayout_update(n))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(exports.Schedule.PostUpdate,st([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const yr=new mr;let _r=!1,xr=!1;function wr(){return _r}function vr(){return xr}const br=function(){const e=new Float32Array(16),t=new Float32Array(16);let s=!0;return{update(e){for(let n=0;n<16;n++)if(t[n]!==e[n]){t.set(e),s=!0;break}},getInverse:t=>(s&&(sr(t,e),s=!1),e)}}();function Sr(e,t,s,n){t.emit(s,n,s),Ln(e,s,r=>{if(!e.has(r,ur))return!1;const o=e.get(r,ur);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class Pr{build(e){J("Interactable",ur),J("Button",pr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new fr;e.insertResource(gr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(it),Se(ct)],(e,a)=>{if(r.drain(),wr()&&!vr())return;const l=t.getEntitiesWithComponents([dr]);for(const e of l){const s=t.get(e,dr);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,dr,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;br.update(a.viewProjection);const p=nr(d,h,br.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),m=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,g,m);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,dr)){const e=t.get(o,dr);e.hovered=!1,t.insert(o,dr,e),r.emit(o,"hover_exit")}if(null!==_){zn(t,_,dr);const e=t.get(_,dr);e.hovered=!0,t.insert(_,dr,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,dr);e.pressed=!0,e.justPressed=!0,t.insert(_,dr,e),i=_,Sr(t,r,_,"press")}if(m&&null!==i){if(t.valid(i)&&t.has(i,dr)){const e=t.get(i,dr);e.pressed=!1,e.justReleased=!0,t.insert(i,dr,e),Sr(t,r,i,"release"),i===o&&Sr(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,st([],()=>{const e=t.getEntitiesWithComponents([pr]);for(const s of e){if(zn(t,s,ur,{enabled:!0}),!t.has(s,dr))continue;const e=t.get(s,dr),n=t.get(s,pr),r=t.get(s,ur),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=hr.Pressed:e.hovered?n.state=hr.Hovered:n.state=hr.Normal:n.state=hr.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,ie)){const o=t.get(s,ie);o.color=Rn(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,ie,o)}}},{name:"ButtonSystem"}))}}const Mr=new Pr,Tr=Y("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}),Er=Y("Focusable",{tabIndex:0,isFocused:!1});class Cr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Ar=be(new Cr,"FocusManager");class Rr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(J("TextInput",Tr),wr()&&!vr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=l(L.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=0,a=0,c=!1,u=!0,d=0,h=0;const p=function(){if("undefined"==typeof document||!document.body)return null;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}();if(!p)return;const f=p;function g(){const t=e.getResource(Ar);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Tr)?n:null}const m=()=>{c||null===g()||v()},y=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=g();if(null===n)return;if("Escape"===t.key)return void b();const r=s.get(n,Tr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(gr).emit(n,"submit"),void b()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,f.selectionStart=o,f.selectionEnd=o,r.dirty=!0,S())},w=()=>{const t=g();if(null!==t){const n=s.get(t,Tr);n.focused=!1,n.dirty=!0;e.getResource(Ar).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,Tr);if(n.readOnly)return;let r=f.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),f.value=r),r!==n.value){n.value=r;e.getResource(gr).emit(t,"change")}n.cursorPos=f.selectionStart??r.length,n.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=s.get(t,Tr);e.focused=!1,e.dirty=!0}e.getResource(Ar).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",m),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",m),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==i&&(t._free(i),i=0,a=0)};let P=null;function M(e,l,c,d){(r.width<c||r.height<d)&&(r.width=kn(Math.max(r.width,c)),r.height=kn(Math.max(r.height,d))),o.clearRect(0,0,r.width,r.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=p?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const m=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Fn(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=m}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Fn(o,l.value,c-2*y);let r=0,i=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=l.cursorPos){i=t,a=l.cursorPos-r;break}r+=s,t<e.length-1&&r<l.value.length&&"\n"===l.value[r]&&r++,i=t+1,a=0}const u=i<e.length?e[i].substring(0,a):"";t=y+o.measureText(u).width,s=y+i*m,n=m}else t=y+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==i&&t._free(i),i=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,i);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,d,i,x.length,1,!0);n.set(e,b);const S=s.get(e,ie);S.texture=b,S.size.x=c,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,ie,S)}e.addSystemToSchedule(exports.Schedule.Update,st([Se(Ar)],e=>{const t=s.getEntitiesWithComponents([Tr]);for(const e of t)zn(s,e,Er,{tabIndex:0,isFocused:!1}),zn(s,e,ur,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Tr)){const e=s.get(P,Tr);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Tr);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===h?0:(e-h)/1e3;h=e,r=Math.min(r,.1);const o=g();if(null!==o&&(d+=r,d>=.5)){d-=.5,u=!u;s.get(o,Tr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Tr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Tr,Pn]);for(const e of a){const t=s.get(e,Tr);if(!t.dirty)continue;const n=s.get(e,Pn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(En(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Ir=new Rr,Fr={Simple:0,Sliced:1,Tiled:2,Filled:3},kr={Horizontal:0,Vertical:1},Br={Left:0,Right:1,Bottom:2,Top:3},Dr=Y("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:Fr.Simple,fillMethod:kr.Horizontal,fillOrigin:Br.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ur=$n({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Dn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Un(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Lr=new class{build(e){J("Image",Dr);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Dr)||s.delete(e);const e=t.getEntitiesWithComponents([Dr]);for(const n of e){const e=t.get(n,Dr),r=t.has(n,Pn)?t.get(n,Pn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!Ur.changed(i,o))continue;En(t,n);const a=t.get(n,ie);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,r&&(a.size.x=Dn(r,n),a.size.y=Un(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===kr.Horizontal?e.fillOrigin===Br.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===Br.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===Fr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(n,ie,a),s.set(n,Ur.take(o))}else a.color.a=0,t.insert(n,ie,a),s.set(n,Ur.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},zr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wr=Y("ToggleGroup",{allowSwitchOff:!1});const $r=new class{build(e){J("Toggle",zr),J("ToggleGroup",Wr);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,st([Se(gr)],e=>{const n=t.getEntitiesWithComponents([zr]);if(!wr()||vr()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,zr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,zr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,zr);if(0!==s.group&&t.valid(s.group)){let t=o.get(s.group);t||(t=[],o.set(s.group,t)),t.push(e)}}for(const s of n){if(zn(t,s,ur,{enabled:!0}),!t.has(s,dr))continue;const n=t.get(s,dr),r=t.get(s,zr),i=t.get(s,ur);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Wr);if(r.isOn&&i){if(!t.get(n,Wr).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,zr,r),r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,zr);r.isOn&&(r.isOn=!1,t.insert(n,zr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,ie)){const e=t.get(s,ie);e.color=Rn(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,ie,e)}}}for(const e of n){const s=t.get(e,zr);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ie)){const e=t.get(s.graphicEntity,ie);e.enabled=s.isOn,t.insert(s.graphicEntity,ie,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Or=bn,Hr=Y("ProgressBar",{value:0,fillEntity:0,direction:bn.LeftToRight});function Xr(e,t,s,n){if(!e.has(t,Pn))return;const r=e.get(t,Pn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=Sn(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,a,r.pivot);if(e.has(t,ie)){const s=e.get(t,ie);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ie,s))}if(e.has(t,ne)){const s=e.get(t,ne),n=s.position;n.x===l.originX&&n.y===l.originY||(s.position={x:l.originX,y:l.originY,z:n.z},e.insert(t,ne,s))}}class jr{build(e){J("ProgressBar",Hr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e=t.getEntitiesWithComponents([Hr,Pn]);for(const s of e){const e=t.get(s,Hr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Pn),r=Math.max(0,Math.min(1,e.value));An(t,e.fillEntity,e.direction,r);const o=Dn(n,s),i=Un(n,s);Xr(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Nr=new jr,Yr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Vr=Y("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Gr=new class{build(e){J("Draggable",Yr),J("DragState",Vr);const t=e.world,s=e.getResource(gr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(it),Se(ct)],(e,i)=>{if(wr()&&!vr())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Yr,dr]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Yr).enabled)continue;if(t.get(n,dr).hovered){let e=0;t.has(n,ie)&&(e=t.get(n,ie).layer);const r=Bn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,Vr)||t.insert(s,Vr);const e=t.get(s,Vr),o=t.get(s,ne);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Vr)){t.get(n,Vr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),u=t.get(n,Yr);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Vr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Vr))return void(o=null);const n=t.get(o,Vr),r=t.get(o,Yr),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,ne)){const e=function(e,t,s,n){if(!e.has(t,ue))return{x:s,y:n};const r=e.get(t,ue).entity;if(!e.valid(r)||!e.has(r,ne))return{x:s,y:n};const o=e.get(r,ne),i=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=rr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/i,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,ne);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ne,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},qr=Y("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Kr(e,t,s,n){return n<=0?1:e<t?Math.max(0,1-(t-e)/n):e>s?Math.max(0,1-(e-s)/n):1}function Jr(e,t,s,n,r){const o=2/(n=Math.max(1e-4,n)),i=o*r,a=1/(1+i+.48*i*i+.235*i*i*i),l=e-t,c=(s+o*l)*r,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}const Qr=new class{build(e){J("ScrollView",qr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(it),Se(ct),Se(Ee)],(e,r,o)=>{const i=wr()&&!vr(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);r.valid&&(n.x=r.worldMouseX,n.y=r.worldMouseY);const l=t.getEntitiesWithComponents([qr,Pn]);for(const o of l){zn(t,o,er,{enabled:!0,mode:Qn});const l=t.get(o,qr),c=t.get(o,Pn);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=Dn(c,o),h=Un(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,de)){const e=t.get(l.contentEntity,de).entities;let s=0,n=0,r=0,o=0;for(const i of e){if(!t.valid(i)||!t.has(i,ne))continue;const e=t.get(i,ne);let a=0,l=0,c=.5,u=.5;if(t.has(i,Pn)){const e=t.get(i,Pn);a=Dn(e,i)||e.size.x,l=Un(e,i)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(i,ie)){const e=t.get(i,ie);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<r&&(r=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-r)}const g=Math.max(0,p-d),m=Math.max(0,f-h);if(!i&&r.valid){zn(t,o,ur,{enabled:!0,blockRaycast:!0});const s=t.has(o,dr)?t.get(o,dr):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=Kr(l.scrollX,0,g,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=Kr(l.scrollY,0,m,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Kr(l.scrollY,0,m,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Kr(l.scrollX,0,g,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>m;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Jr(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<On&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>On?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:m,t=Jr(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<On&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>On?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,m)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,m+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ne)){const e=t.get(l.contentEntity,ne),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,ne,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Zr=bn,eo=Y("Slider",{value:0,minValue:0,maxValue:1,direction:bn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function to(e,t,s,n,r,o){const i=Dn(n,r)*s.worldScale.x,a=Un(n,r)*s.worldScale.y,l=rr(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,g=-n.pivot.x*i,m=-n.pivot.y*a;switch(o){case bn.LeftToRight:return i>0?(p-g)/i:0;case bn.RightToLeft:return i>0?1-(p-g)/i:0;case bn.BottomToTop:return a>0?(f-m)/a:0;case bn.TopToBottom:return a>0?1-(f-m)/a:0}}function so(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case bn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case bn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case bn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case bn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class no{build(e){J("Slider",eo);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(it),Se(ct),Se(gr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([eo,Pn]);for(const i of o){const o=t.get(i,eo),a=t.get(i,Pn);if(!wr()||vr()){if(t.has(i,ne)){zn(t,i,ur,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&zn(t,o.handleEntity,ur,{enabled:!0,blockRaycast:!1});const l=t.get(i,ne),c=t.has(i,dr)?t.get(i,dr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,dr)&&(u=t.get(o.handleEntity,dr).justPressed),u&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=to(n.worldMouseX,n.worldMouseY,l,a,i,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(i,eo,o),o.value!==c&&r.emit(i,"change")}s===i&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Dn(a,i),d=Un(a,i),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(An(t,o.fillEntity,o.direction,c),Wn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Pn)){const e=t.get(o.handleEntity,Pn);so(e,o.direction,c),t.insert(o.handleEntity,Pn,e),Wn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const ro=new no;const oo=new class{build(e){J("Focusable",Er);const t=e.world,s=new Cr;e.insertResource(Ar,s),e.addSystemToSchedule(exports.Schedule.Update,st([Se(it),Se(gr)],(e,n)=>{if(wr()&&!vr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([Er]);for(const e of r){if(!t.has(e,dr))continue;t.get(e,dr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,ur)){if(!t.get(s,ur).enabled)continue}const n=t.get(s,Er);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,Er)){t.get(r,Er).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,Er).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},io=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ao(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const lo=new class{build(e){J("SafeArea",io);const t=e.world;let n=ao(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ao(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ao(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(ct)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([io,Pn]);for(const e of d){const s=t.get(e,io),r=t.get(e,Pn),o=s.applyTop?n.top*c:0,i=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},u=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Pn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},co=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let uo=null;const ho=new class{build(e){J("ListView",co);const t=e.world,s=new Map;uo=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(it)],e=>{const n=wr()&&!vr();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const r=t.getEntitiesWithComponents([co,Pn]);for(const o of r){zn(t,o,ur,{enabled:!0,blockRaycast:!0}),zn(t,o,er,{enabled:!0,mode:Qn});let r=s.get(o);r||(r={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,r));const i=t.get(o,co),a=t.get(o,Pn),l=Un(a,o),c=Dn(a,o);if(!n){const s=t.has(o,dr)?t.get(o,dr):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}}const u=Math.max(0,i.itemCount*i.itemHeight-l);i.scrollY=Math.max(0,Math.min(i.scrollY,u));const d=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+l)/i.itemHeight)+i.overscan);for(const[e,s]of r.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),r.itemEntities.delete(e));for(let e=d;e<h;e++){let s=r.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,fe,{value:`ListItem_${e}`}),t.insert(s,Pn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),r.itemEntities.set(e,s),r.renderer&&r.renderer(e,s)),t.has(s,ne)){const n=t.get(s,ne);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(s,ne,n)}}r.visibleStart=d,r.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},po=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const fo=new class{build(e){J("Dropdown",po);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ne))return;const s=t.get(e,ne);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ne,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function r(e){if(t.has(e,ie)){const s=t.get(e,ie);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ie,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const r=s.listEntity;if(0===r||!t.valid(r))return;u(r,!0),c(n);const o=t.get(e,ie),i=o.size.x,a=o.size.y;n.ddWidth=i;const l=s.options.length*Hn;t.insert(r,Pn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:l},pivot:{x:.5,y:.5}}),t.insert(r,ne,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,ie,{texture:$,color:{r:1,g:1,b:1,a:1},size:{x:i,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Hn;t.insert(o,fe,{value:`Option_${e}`}),t.insert(o,Pn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Hn},offsetMax:{x:0,y:0},size:{x:i,y:Hn},pivot:{x:.5,y:.5}}),t.insert(o,ne,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,ie,{texture:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:i,y:Hn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ur,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ne,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Vn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:jn.Left,verticalAlign:Nn.Middle,wordWrap:!1,overflow:Yn.Clip,lineHeight:1.2}),t.insert(c,Pn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:Hn},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function i(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,r){t.selectedIndex=n,i(0,t,s),r.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Vn))return;const n=t.get(s,Vn);let r={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,i=!1;if(1===r.r&&1===r.g&&1===r.b&&1===r.a&&(r={r:0,g:0,b:0,a:1},i=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,i=!0)}i&&t.insert(s,Vn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:r,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,ur)&&t.insert(e,ur,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ie))){const n=t.get(e,ie);t.insert(e,ie,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ie))continue;const r=s===e.highlightIndex?{...Xn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ie,{texture:$,color:r,size:{x:e.ddWidth,y:Hn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,dr))continue;if(t.get(s,dr).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,st([Se(it),Se(gr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=wr()&&!vr(),f=t.getEntitiesWithComponents([po]);for(const g of f){const f=t.get(g,po);let m=s.get(g);if(m||(m={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(g,m)),n(f.listEntity),r(g),f.isOpen||u(f.listEntity,!1),l(f),p)continue;zn(t,g,ur,{enabled:!0,blockRaycast:!0});const y=t.has(g,dr)?t.get(g,dr):null;if(y?.justPressed&&(f.isOpen?i(g,f,m):o(g,f,m)),f.isOpen){for(let e=0;e<m.optionEntities.length;e++){const s=m.optionEntities[e];if(!t.valid(s)||!t.has(s,dr))continue;if(t.get(s,dr).justPressed){a(g,f,m,e,c);break}}let s=-1;for(let e=0;e<m.optionEntities.length;e++){const n=m.optionEntities[e];if(!t.valid(n)||!t.has(n,dr))continue;if(t.get(n,dr).hovered){s=e;break}}s>=0&&s!==m.highlightIndex&&(m.highlightIndex=s,d(m)),e.isKeyPressed("ArrowDown")?(m.highlightIndex>=f.options.length-1?m.highlightIndex=0:m.highlightIndex++,d(m)):e.isKeyPressed("ArrowUp")?(m.highlightIndex<=0?m.highlightIndex=f.options.length-1:m.highlightIndex--,d(m)):e.isKeyPressed("Enter")&&m.highlightIndex>=0?a(g,f,m,m.highlightIndex,c):e.isKeyPressed("Escape")&&i(g,f,m),e.isMouseButtonPressed(0)&&(y?.hovered||h(m)||i(g,f,m))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},go=0,mo=0,yo=2,_o=Y("LayoutGroup",{direction:go,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:mo,reverseOrder:!1});const xo=new class{build(e){J("LayoutGroup",_o);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e=t.getEntitiesWithComponents([_o,Pn,de]);for(const s of e){const e=t.get(s,_o),n=t.get(s,Pn),r=t.get(s,de);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,Pn)&&t.has(e,ne)&&o.push({entity:e,rect:t.get(e,Pn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=Dn(n,s),a=Un(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===go;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=Dn(n.rect,n.entity),p=Un(n.rect,n.entity),f=n.rect.pivot.x,g=n.rect.pivot.y;let m,y;d?(m=-l*i+u.left+h+f*r,y=e.childAlignment===mo?(1-c)*a-u.top-(1-g)*p:e.childAlignment===yo?-c*a+u.bottom+g*p:(.5-c)*a+.5*(u.bottom-u.top)+(g-.5)*p,h+=r,s<o.length-1&&(h+=e.spacing)):(m=e.childAlignment===mo?-l*i+u.left+f*r:e.childAlignment===yo?(1-l)*i-u.right-(1-f)*r:(.5-l)*i+.5*(u.left-u.right)+(f-.5)*r,y=(1-c)*a-u.top-h-(1-g)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,ne);_.position.x=m,_.position.y=y,t.insert(n.entity,ne,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Z("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Z("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class wo{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,st([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const vo=new wo;async function bo(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const So=be({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Po=be(null,"PhysicsAPI");function Mo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function To(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Eo{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(So,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=bo(this.wasmUrl_,this.factory_).then(n=>{n._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([le]);for(const s of t){const t=e.world.get(s,le);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;i.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(Ee)],a=>{const l=i.getEntitiesWithComponents([me,ne]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,me),l=i.get(r,ne);if(t.has(r)){const e=s.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||(n._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=Mo(l.worldRotation);n._physics_createBody(r,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Co(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===we.Kinematic){const e=Mo(l.worldRotation);n._physics_setBodyTransform(r,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,ne);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(i,ue)){const t=e.world.get(i,ue);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ne)){const s=e.world.get(t.entity,ne),n=Mo(s.worldRotation),r=a-s.worldPosition.x,o=l-s.worldPosition.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(r*u+o*i)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=To(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,ne,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],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;n.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]*s,contactY:t.HEAPF32[r+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 n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(So,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Po,Ao._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Co(e,t,s){const n=e.world;if(n.has(s,ye)){const e=n.get(s,ye);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(n.has(s,_e)){const e=n.get(s,_e);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(n.has(s,xe)){const e=n.get(s,xe);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 Ao{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(Ao.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)}}const Ro={nearest:0,linear:1},Io={repeat:0,clamp:1,mirror:2};function Fo(e,t,s=!0,n){const r=e.getResourceManager(),o=e._malloc(t.pixels.length);let i;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&r.createTextureEx){const e=Ro[n.filterMode??"linear"]??1,a=Io[n.wrapMode??"clamp"]??1;i=r.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else i=r.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),i}function ko(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 Bo(e,t,s,n){const r=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),i=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,g=a*h,m=a*p,y=l*h,_=l*p,x=c*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(y+x))*r,(g+b)*r,(m-v)*r,0,(g-b)*o,(1-(f+x))*o,(_+w)*o,0,(m+v)*i,(_-w)*i,(1-(f+y))*i,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Do(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={},r=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Wt(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=r?.[o];n[o]=Fo(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let u={},d=null;if(r&&(d=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),u=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=$t(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),u=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===_(c)?.contentType;let d,h;if(i){const e=await r.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(a),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,n,n.length,i);if(t._free(d),p<0)continue;o[a]=p;const f=ko(n),g=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=g+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=Fo(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){const t={gravity:i?.gravity??{...D},fixedTimestep:i?.fixedTimestep??U,subStepCount:i?.subStepCount??4};new Eo("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){const r=Wt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=_(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=Fo(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=Wt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=xt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=xt.createFromAsset(e,i)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Wt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=r[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(s,c,h,p);const f=Nt(e.world,s);if(l&&e.hasResource(sn))for(const t of f.values())e.world.insert(t,ge,{scene:l,persistent:!1});if(r&&d){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=$t(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(d,s,u,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=B);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,pe)?c.get(o,pe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,l*d);let h=0;if(c.has(o,ne)){const e=Bo(c.get(o,ne),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,c,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],m=new Float32Array(s.HEAPF32.buffer,c,8*r),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(m,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,r,x,o,f,g,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(Jt);t&&t.setAddressableManifest(a)}}function Uo(e,t,s){return{name:e,async setup(){await Do(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class Lo{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,n=new Set;for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=$t(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===_(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Wt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}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(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=_(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}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),n=await s.blob(),r=await createImageBitmap(n),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 zo="__preview__";const Wo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ys.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ys.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ys.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ys.releaseRenderTarget(e._handle),Wo.create({width:t,height:s,depth:!0})),begin(e,t){Ys.begin(t,e._handle)},end(){Ys.end()},getDepthTexture:e=>Ys.getTargetDepthTexture(e._handle)};var $o;exports.LogLevel=void 0,($o=exports.LogLevel||(exports.LogLevel={}))[$o.Debug=0]="Debug",$o[$o.Info=1]="Info",$o[$o.Warn=2]="Warn",$o[$o.Error=3]="Error";class Oo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${exports.LogLevel[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case exports.LogLevel.Debug:console.debug(t,s);break;case exports.LogLevel.Info:console.log(t,s);break;case exports.LogLevel.Warn:console.warn(t,s);break;case exports.LogLevel.Error:console.error(t,s)}}}class Ho{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Oo)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Xo=new Ho;const jo={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},No={None:0,Restart:1,PingPong:2};class Yo{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Vo=null,Go=null;function qo(e,t){Vo=e,Go=t}function Ko(){Vo=null,Go=null}function Jo(){if(!Vo)throw new Error("Tween API not initialized");return Vo}function Qo(){if(!Go)throw new Error("Tween API not initialized");return Go}const Zo={to(e,t,s,n,r,o){const i=Jo(),a=Qo(),l=o?.easing??jo.Linear,c=o?.delay??0,u=o?.loop??No.None,d=o?.loopCount??0,h=i._anim_createTween(a,e,t,s,n,r,l,c,u,d);return new Yo(i,a,h)},cancel(e){Jo()._anim_cancelTween(Qo(),e.entity)},cancelAll(e){Jo()._anim_cancelAllTweens(Qo(),e)},update(e){Jo()._anim_updateTweens(Qo(),e)}};class ei{constructor(){this.name="AnimationPlugin"}build(e){qo(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,st([Se(Ee)],e=>{Zo.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,st([Se(Ee)],e=>{Dt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Ko()}}const ti=new ei;class si{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=t.volume??1,this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof si?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class ni{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new si(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new si(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new si(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new si(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new si(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new si(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class ri{constructor(e,t=16){this.pool_=[],this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,priority:0,startTime:0}}acquire(e=0){let t=this.pool_.find(e=>!e.inUse);return t||(t=this.createNode(),this.pool_.push(t)),t.inUse=!0,t.priority=e,t.startTime=this.context_.currentTime,t.gain.gain.value=1,t.panner.pan.value=0,t}release(e){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0}get activeCount(){return this.pool_.filter(e=>e.inUse).length}get capacity(){return this.pool_.length}}var oi;exports.AttenuationModel=void 0,(oi=exports.AttenuationModel||(exports.AttenuationModel={}))[oi.Linear=0]="Linear",oi[oi.Inverse=1]="Inverse",oi[oi.Exponential=2]="Exponential";const ii={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ai(e,t=ii){const{model:s,refDistance:n,maxDistance:r,rolloff:o}=t,i=Math.max(e,.001);switch(s){case exports.AttenuationModel.Linear:return 1-(Math.min(Math.max(i,n),r)-n)/(r-n);case exports.AttenuationModel.Inverse:return n/Math.max(i,n);case exports.AttenuationModel.Exponential:return Math.pow(Math.max(i,n)/n,-o);default:return 1}}function li(e,t,s,n,r){const o=e-s;return Math.max(-1,Math.min(1,o/r))}const ci=Y("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),ui=Y("AudioListener",{enabled:!0});class di{constructor(e,t,s,n,r){this.playing_=!0,this.id=e,this.source_=t,this.poolNode_=s,this.pool_=n,this.context_=r}stop(){this.playing_=!1,this.pool_.release(this.poolNode_)}pause(){this.playing_&&(this.playing_=!1,this.source_.playbackRate.value=0)}resume(){this.playing_||(this.playing_=!0,this.source_.playbackRate.value=1)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.source_.loop=e}setPlaybackRate(e){this.source_.playbackRate.value=e}get isPlaying(){return this.playing_}get currentTime(){return this.playing_?this.context_.currentTime-this.poolNode_.startTime:0}get duration(){return this.source_.buffer?.duration??0}markEnded(){this.playing_=!1}}class hi{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.nextBufferId_=0,this.nextHandleId_=0}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new ni(this.context_,e.mixerConfig),this.pool_=new ri(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e)};document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("mousedown",e,{once:!0}),document.addEventListener("keydown",e,{once:!0})}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=await fetch(e),s=await t.arrayBuffer(),n=await this.context_.decodeAudioData(s),r=++this.nextBufferId_;return this.buffers_.set(r,n),{id:r,duration:n.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(t.priority??0),r=this.context_.createBufferSource();r.buffer=s,r.loop=t.loop??!1,r.playbackRate.value=t.playbackRate??1,r.connect(n.gain),n.source=r,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",i=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(i.node),r.start(0,t.startOffset??0);const a=++this.nextHandleId_,l=new di(a,r,n,this.pool_,this.context_);return r.onended=()=>{r.loop||(l.markEnded(),this.pool_.release(n),l.onEnd?.())},l}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.context_?.close(),this.context_=null}}class pi{constructor(e,t,s){this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class fi{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}async initialize(){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.src=s,n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.autoplay=!0,n.obeyMuteSwitch=!1;const r=++this.nextId_;this.contexts_.set(r,n);const o=new pi(r,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(r))}),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function gi(){return s()?new fi:new hi}class mi{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const t=gi();t.initialize();let s=null;t instanceof hi&&(s=t.mixer),Ut.init(t,s);const n=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(Ee)],s=>{const r=e.world;let o=0,i=0;const a=r.getEntitiesWithComponents([ui,oe]);for(const e of a){if(r.get(e,ui).enabled){const t=r.get(e,oe);o=t.position.x,i=t.position.y;break}}const l=r.getEntitiesWithComponents([ci,oe]);for(const e of l){const s=r.get(e,ci);if(!s.enabled||!s.clip)continue;const a=r.get(e,oe);if(s.playOnAwake&&!n.has(e)){const r=Ut.getBufferHandle(s.clip);if(r){const o=t.play(r,{bus:s.bus,volume:s.volume,loop:s.loop,playbackRate:s.pitch,priority:s.priority});n.set(e,o)}}if(s.spatial&&n.has(e)){const t=n.get(e),r=a.position.x-o,l=a.position.y-i,c=ai(Math.sqrt(r*r+l*l),{model:s.attenuationModel,refDistance:s.minDistance,maxDistance:s.maxDistance,rolloff:s.rolloff}),u=li(a.position.x,a.position.y,o,0,s.maxDistance);t.setVolume(s.volume*c),t.setPan(u)}}},{name:"AudioUpdateSystem"}))}cleanup(){}}const yi=new mi;class _i{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const r=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(r.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function xi(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}const wi=[Jn,cr,yr,Lr,Nr,Mr,Gr,Qr,ro,$r,Ir,oo,lo,ho,fo,xo,vo],vi=[...wi,ti];function bi(e,t){return function(e,t){const s=an.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),fs(e),mt(e),Is(e),Us(e),js(e),Gs(e);const r=new Js;s.setPipeline(r);let o=c();const i=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=pn(e,n,t,r));const i=s.getResource(ct);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)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.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}s.insertResource(ct,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Ys.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Ys.resize(t,l),Ws.isInitialized()&&Ws.getPassCount()>0&&!Ws.isBypassed()&&Ws.resize(t,l),s.hasResource(sn)){const e=s.getResource(sn).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=pn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:cn,width:t,height:l,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Ys.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Zt),s.addPlugin(ls),s.addPlugin(lt),s.addPlugin(on),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:vi,...t})}class Si{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await r(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Pi(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function Mi(e,t){try{return await e({instantiateWasm:Pi(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}R||(R=!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(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await d(s,n);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: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 h(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 n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),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 n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=I,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=ei,exports.App=an,exports.AssetPlugin=Qt,exports.AssetRefCounter=class{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let s=this.textureRefs_.get(e);s||(s=new Set,this.textureRefs_.set(e,s)),s.add(t)}removeTextureRef(e,t){const s=this.textureRefs_.get(e);s&&(s.delete(t),0===s.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let s=this.fontRefs_.get(e);s||(s=new Set,this.fontRefs_.set(e,s)),s.add(t)}removeFontRef(e,t){const s=this.fontRefs_.get(e);s&&(s.delete(t),0===s.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let s=this.materialRefs_.get(e);s||(s=new Set,this.materialRefs_.set(e,s)),s.add(t)}removeMaterialRef(e,t){const s=this.materialRefs_.get(e);s&&(s.delete(t),0===s.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,s]of this.textureRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllFontRefs(){const e=[];for(const[t,s]of this.fontRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}getAllMaterialRefs(){const e=[];for(const[t,s]of this.materialRefs_.entries())e.push({assetPath:t,refCount:s.size,entities:Array.from(s)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}},exports.AssetServer=Kt,exports.Assets=Jt,exports.AsyncCache=Ct,exports.Audio=Ut,exports.AudioBus=si,exports.AudioListener=ui,exports.AudioMixer=ni,exports.AudioPlugin=mi,exports.AudioPool=ri,exports.AudioSource=ci,exports.BitmapText=he,exports.BodyType=we,exports.BoxCollider=ye,exports.Button=pr,exports.ButtonState=hr,exports.Camera=ae,exports.Canvas=le,exports.CapsuleCollider=xe,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=de,exports.CircleCollider=_e,exports.ClearFlags=te,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=qe,exports.DEFAULT_DESIGN_HEIGHT=k,exports.DEFAULT_DESIGN_WIDTH=F,exports.DEFAULT_FALLBACK_DT=B,exports.DEFAULT_FIXED_TIMESTEP=U,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=D,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE={x:100,y:100},exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragState=Vr,exports.Draggable=Yr,exports.Draw=_s,exports.Dropdown=po,exports.EasingType=jo,exports.EntityCommands=Ge,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Ze,exports.EventRegistry=Je,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Qe,exports.FillDirection=bn,exports.FillMethod=kr,exports.FillOrigin=Br,exports.FocusManager=Ar,exports.FocusManagerState=Cr,exports.Focusable=Er,exports.GLDebug=Ks,exports.Geometry=Bs,exports.GetWorld=function(){return{_type:"get_world"}},exports.INVALID_ENTITY=0,exports.INVALID_FONT=O,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=$,exports.Image=Dr,exports.ImageType=Fr,exports.Input=it,exports.InputPlugin=at,exports.InputState=ot,exports.Interactable=ur,exports.ListView=co,exports.LocalTransform=re,exports.Logger=Ho,exports.LoopMode=No,exports.Material=xt,exports.MaterialLoader=At,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=fe,exports.Parent=ue,exports.Physics=Ao,exports.PhysicsEvents=So,exports.PhysicsPlugin=Eo,exports.PostProcess=Ws,exports.PrefabServer=os,exports.Prefabs=is,exports.PrefabsPlugin=as,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(sn);t.register({name:zo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(zo),this.loadPromise_=t.load(zo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;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 Lo(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await Do(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,zo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([ae]);for(const n of s){if(e.get(n,ae).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([le]);for(const r of n){const n=e.get(r,le);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(sn).getScene(zo),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,ne,i);const a={isActive:!0,projectionType:ee.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:te.ColorAndDepth};e.insert(o,ae,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(sn);await e.switchTo(zo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}},exports.ProgressBar=Hr,exports.ProgressBarDirection=Or,exports.ProgressBarPlugin=jr,exports.ProjectionType=ee,exports.Query=function(...e){return Ne(e)},exports.QueryInstance=Ye,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ve,exports.RenderPipeline=Js,exports.RenderTexture=Wo,exports.Renderer=Ys,exports.Res=Se,exports.ResMut=Pe,exports.RigidBody=me,exports.RuntimeConfig=L,exports.SafeArea=io,exports.ScaleMode=se,exports.SceneManager=sn,exports.SceneManagerState=tn,exports.SceneOwner=ge,exports.ScrollView=qr,exports.ShaderSources=Et,exports.Slider=eo,exports.SliderDirection=Zr,exports.SliderPlugin=no,exports.SpineAnimation=pe,exports.Sprite=ie,exports.SpriteAnimator=Bt,exports.SystemRunner=rt,exports.Text=Vn,exports.TextAlign=jn,exports.TextInput=Tr,exports.TextInputPlugin=Rr,exports.TextOverflow=Yn,exports.TextPlugin=Kn,exports.TextRenderer=Gn,exports.TextVerticalAlign=Nn,exports.Time=Ee,exports.Toggle=zr,exports.Transform=ne,exports.Tween=Zo,exports.TweenHandle=Yo,exports.TweenState={Running:0,Paused:1,Completed:2,Cancelled:3},exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UICameraInfo=ct,exports.UIEventQueue=fr,exports.UIEvents=gr,exports.UIInteraction=dr,exports.UIInteractionPlugin=Pr,exports.UILayoutPlugin=mr,exports.UIMask=er,exports.UIMaskPlugin=lr,exports.UIRect=Pn,exports.UIRenderOrderPlugin=wo,exports.Velocity=ce,exports.WeChatAssetProvider=Si,exports.WebAssetProvider=Lo,exports.World=$e,exports.WorldTransform=oe,exports.addStartupSystem=function(e){nt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){nt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){nt().push({schedule:e,system:t})},exports.animationPlugin=ti,exports.applyBuildRuntimeConfig=W,exports.applyDirectionalFill=An,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=L.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=L.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=L.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=L.canvasMatchWidthOrHeight)},exports.assetPlugin=Zt,exports.audioPlugin=yi,exports.calculateAttenuation=ai,exports.calculatePanning=li,exports.clearAnimClips=function(){Ft.clear()},exports.clearDrawCallbacks=Ms,exports.clearUserComponents=function(){const e=N();for(const t of e.keys())K.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Cn,exports.computeFillSize=function(e,t,s,n){switch(e){case bn.BottomToTop:case bn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case bn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case bn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case bn.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}},exports.computeUIRectLayout=Sn,exports.createAudioBackend=gi,exports.createMaskProcessor=ar,exports.createRuntimeSceneConfig=Uo,exports.createWebApp=bi,exports.debug=function(e,t,s){Xo.debug(e,t,s)},exports.defineComponent=Y,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=be,exports.defineSystem=st,exports.defineTag=function(e){const t=K.get(e)??N().get(e);if(t)return t;const s=j(e,{});return N().set(e,s),K.set(e,s),G(e,{},!0),s},exports.error=function(e,t,s){Xo.error(e,t,s)},exports.extractAnimClipTexturePaths=Rt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([fe]);for(const n of s){const s=e.get(n,fe);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=ln,exports.getAddressableType=function(e){return _(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of p)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return m},exports.getAnimClip=function(e){return Ft.get(e)},exports.getAssetMimeType=function(e){return f[e.toLowerCase()]},exports.getAssetTypeEntry=_,exports.getComponent=Q,exports.getComponentAssetFieldDescriptors=Wt,exports.getComponentAssetFields=zt,exports.getComponentDefaults=function(e){const t=Q(e);return t?H(t._default):null},exports.getComponentEntityFields=Ht,exports.getComponentSpineFieldDescriptor=$t,exports.getCustomExtensions=w,exports.getEditorType=function(e){return _(e)?.editorType??"unknown"},exports.getLogger=function(){return Xo},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=V,exports.getWeChatPackOptions=function(){return w().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Xo.info(e,t,s)},exports.initDrawAPI=fs,exports.initGLDebugAPI=Gs,exports.initGeometryAPI=Is,exports.initMaterialAPI=mt,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,sceneData:r,sceneName:o}=e,i=t.getResource(Jt);i&&(i.registerEmbeddedAssets(n),i.setEmbeddedOnly(!0)),ln(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await xi(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await xi(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Uo(o,r,{app:t,module:s,provider:new _i(n),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),u=t.getResource(sn);u.register(c),u.setInitial(o),await u.load(o);const d=e.canvas.width/e.canvas.height;qt(t.world,d),t.run()},exports.initPostProcessAPI=Us,exports.initRendererAPI=js,exports.initTweenAPI=qo,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=b(e),r=t[e]||t[n]||s[n]||s[e];return r?r.path:n}}(function(e){const t={},s={};for(const n in e.groups){const r=e.groups[n];for(const e in r.assets){const n=r.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),r=wx.createCanvas(),i=wx.getSystemInfoSync();r.width=i.windowWidth*i.pixelRatio,r.height=i.windowHeight*i.pixelRatio;const a=await e.engineFactory({canvas:r,instantiateWasm:Pi("esengine.wasm")}),l=r.getContext("webgl2")||r.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=bi(a,{glContextHandle:c,getViewportSize:()=>({width:r.width,height:r.height})});e.runtimeConfig&&W(u,e.runtimeConfig),ln(u);let d=null;e.spineFactory&&(d=await Mi(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await Mi(e.physicsFactory,"physics.wasm"));const p={app:u,module:a,provider:new Si(n),spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s},f=u.getResource(sn);for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`),s=JSON.parse(e);f.register(Uo(t,s,p))}e.firstScene&&(f.setInitial(e.firstScene),await f.load(e.firstScene));const g=r.width/r.height;qt(u.world,g),u.run()},exports.inputPlugin=lt,exports.instantiatePrefab=es,exports.intersectRects=tr,exports.invertMatrix4=sr,exports.isBuiltinComponent=q,exports.isCustomExtension=v,exports.isEditor=wr,exports.isKnownAssetExtension=x,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=vr,exports.isRuntime=function(){return!_r},exports.isTextureRef=dt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Gt,exports.loadPhysicsModule=bo,exports.loadRuntimeScene=Do,exports.loadSceneData=Nt,exports.loadSceneWithAssets=Yt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&x(y(e)))},exports.parseAnimClipData=It,exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=a,exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,r,o,i,a,l,c){const u=rr(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,g=p*h-f*d+s,m=p*d+f*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&m>=n-o*a&&m<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=ls,exports.progressBarPlugin=Nr,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=kt,exports.registerComponent=J,exports.registerComponentAssetFields=function(e,t){Lt.set(e,t)},exports.registerComponentEntityFields=function(e,t){Ot.set(e,t)},exports.registerDrawCallback=Ss,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Jt);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Tt,exports.remapEntityFields=Xt,exports.sceneManagerPlugin=on,exports.screenToWorld=nr,exports.setEditorMode=function(e){_r=e},exports.setListViewRenderer=function(e,t){if(!uo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=uo.get(e);s?s.renderer=t:uo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Xo.setMinLevel(e)},exports.setPlayMode=function(e){xr=e},exports.setWasmErrorHandler=Fe,exports.shutdownDrawAPI=gs,exports.shutdownGLDebugAPI=qs,exports.shutdownGeometryAPI=Fs,exports.shutdownMaterialAPI=yt,exports.shutdownPostProcessAPI=Ls,exports.shutdownRendererAPI=Ns,exports.shutdownTweenAPI=Ko,exports.sliderPlugin=ro,exports.spriteAnimatorSystemUpdate=Dt,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,ie))return;const i=e.get(t,ie);let a,l;switch(s){case bn.BottomToTop:case bn.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,ie,i))},exports.textInputPlugin=Ir,exports.textPlugin=Jn,exports.toBuildPath=b,exports.transitionTo=async function(e,t,s){const n=e.getResource(sn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Mr,exports.uiLayoutPlugin=yr,exports.uiMaskPlugin=cr,exports.uiPlugins=wi,exports.uiRenderOrderPlugin=vo,exports.unregisterAnimClip=function(e){Ft.delete(e)},exports.unregisterComponent=function(e){N().delete(e),K.delete(e)},exports.unregisterDrawCallback=Ps,exports.updateCameraAspectRatio=qt,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,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Xo.warn(e,t,s)},exports.wrapSceneSystem=nn,exports.wxFileExists=function(e){return new Promise(t=>{P().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=T,exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=A,exports.wxReadFile=function(e){return new Promise((t,s)=>{P().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(M(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{P().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(M(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{P().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(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 55fe1dc13..bd0597919 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 i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(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 d(e,n){return t().instantiateWasm(e,n)}function u(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function p(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 g(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}`)}}const y=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of y)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function P(e){for(const t of y)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function M(e){return w.has(e.toLowerCase())}function T(){return w}function E(e){return"string"==typeof e&&(!!e.includes("/")&&M(x(e)))}function C(){const e=[];for(const t of y)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function I(e){const t=v(e);return t?.wechatPackInclude??!1}function k(e){const t=v(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}let F=null;function B(){return F||(F=wx.getFileSystemManager()),F}function z(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(I(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function U(e){return new Promise((t,n)=>{B().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(z(e,t.errMsg)))}})})}function W(e,t="utf-8"){return new Promise((n,s)=>{B().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(z(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{B().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=B();try{return t.accessSync(e),!0}catch{return!1}}function O(e,t){return new Promise((n,s)=>{B().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function L(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 H(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function j(e){return H(await L(e))}let X=!1;const Y=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return p(e,t)}async readFile(e){return function(e){return B().readFileSync(e)}(k(e))}async readTextFile(e){return function(e,t="utf-8"){return B().readFileSync(e,t)}(k(e))}async fileExists(e){return D(k(e))}async loadImagePixels(e){return j(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const r=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},o=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(r),wx.onTouchMove(o),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(r),wx.offTouchMove(o),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},N=1920,V=1080,G=100,q=512,K={x:100,y:100},J="Arial",Q=24,Z=1.2,ee=.5,te=1/60,ne={x:0,y:-9.81},se=1/60,ie="default",re={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function oe(e){e.Text&&(e.Text._default.fontFamily=re.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=re.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=re.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=re.canvasMatchWidthOrHeight)}const ae={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function le(e,t){if(void 0!==t.maxDeltaTime&&(re.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(re.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(re.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(re.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(re.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");re.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(re.canvasScaleMode=ae[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(re.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ce=0,de=4294967295,ue=4294967295,he=0,fe=(e=0,t=0)=>({x:e,y:t}),pe=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ge=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ye=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function _e(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(_e);const t={};for(const n in e)t[n]=_e(e[n]);return t}let we=0;function xe(e,t){const n=++we,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{..._e(t),...e}:_e(t):e?{...t,...e}:{...t}}}function ve(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function be(e,t){const n=Re.get(e)??ve().get(e);if(n)return n;const s=xe(e,t);return ve().set(e,s),Re.set(e,s),Ee(e,t,!1),s}function Se(e){const t=Re.get(e)??ve().get(e);if(t)return t;const n=xe(e,{});return ve().set(e,n),Re.set(e,n),Ee(e,{},!0),n}function Pe(e){return ve().get(e)}function Me(){const e=ve();for(const t of e.keys())Re.delete(t);e.clear()}function Te(e){ve().delete(e),Re.delete(e)}function Ee(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function Ce(e){return!0===e._builtin}const Re=new Map;function Ae(e,t){Re.set(e,t)}function Ie(e){return Re.get(e)??Pe(e)}function ke(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Re.set(e,n),n}const Fe={Perspective:0,Orthographic:1},Be={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ze={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Ue=ke("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),We=Ue,$e=Ue,De=ke("Sprite",{texture:de,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,enabled:!0}),Oe=ke("Camera",{projectionType:Fe.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Be.ColorAndDepth}),Le=ke("Canvas",{designResolution:{x:N,y:V},pixelsPerUnit:100,scaleMode:ze.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),He=ke("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),je=ke("Parent",{entity:0}),Xe=ke("Children",{entities:[]}),Ye=ke("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:ue,enabled:!0}),Ne=ke("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,enabled:!0}),Ve=be("Name",{value:""}),Ge=be("SceneOwner",{scene:"",persistent:!1});function qe(e){const t=Ie(e);return t?_e(t._default):null}const Ke=ke("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Je=ke("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Qe=ke("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ze=ke("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),et={Static:0,Kinematic:1,Dynamic:2};let tt=0;function nt(e,t){const n=++tt;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function st(e){return{_type:"res",_resource:e}}function it(e){return{_type:"res_mut",_resource:e}}class rt{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_)}updateValue(e){this.value_=e}}class ot{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new rt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const at=nt({delta:0,elapsed:0,frameCount:0},"Time");function lt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=ct(t[e]),r=ct(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ct(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function dt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let ut=null;function ht(e){ut=e}function ft(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ut&&ut(e,t)}function pt(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[t]="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}:s}}return n}let gt=1;const yt=new WeakMap;function mt(e){let t=yt.get(e);return void 0===t&&(t=gt++,yt.set(e,t)),t}const _t=[];function wt(e,t=[],n=[]){_t.length=0;for(const t of e)_t.push(mt(t));_t.sort((e,t)=>e-t);let s=_t.join(",");if(t.length>0){_t.length=0;for(const e of t)_t.push(mt(e));_t.sort((e,t)=>e-t),s+="|+"+_t.join(",")}if(n.length>0){_t.length=0;for(const e of n)_t.push(mt(e));_t.sort((e,t)=>e-t),s+="|-"+_t.join(",")}return s}class xt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw ft(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){ft(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){ft(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ft(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Ce(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(Ce(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,pt(n))}catch(n){ft(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return Ce(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Ce(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Ce(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ft(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");Ce(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),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 e=lt(t._name,t._default,s);if(e.length>0)throw new Error(dt(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,pt(i))}catch(n){ft(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return ft(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return ft(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ft(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=lt(t._name,t._default,e);if(i.length>0)throw new Error(dt(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Re)if(Ce(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=ve();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??wt(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!Ce(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function vt(e){return{_type:"mut",_component:e}}function bt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function St(e){return{_filterType:"added",_component:e}}function Pt(e){return{_filterType:"changed",_component:e}}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Tt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Et(e){return bt(e)||Mt(e)||Tt(e)?e._component:e}function Ct(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{bt(e)&&s.push(t),Mt(e)?i.push({index:t,component:e._component}):Tt(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Ct(e,[...t,...s],n),without:(...s)=>Ct(e,t,[...n,...s])}}function Rt(...e){return Ct(e)}class At{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Et),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=wt(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,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(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function It(e){return{_type:"removed",_component:e}}class kt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Ft(){return{_type:"commands"}}class Bt{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=Ce(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 zt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Bt(this,null);return this.spawned_.push(e),e}entity(e){return new Bt(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Ut(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Wt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class $t{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Wt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Wt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Dt(e){return{_type:"event_writer",_event:e}}function Ot(e){return{_type:"event_reader",_event:e}}class Lt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ht{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var jt;function Xt(){return{_type:"get_world"}}!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"}(jt||(jt={}));let Yt=0;function Nt(e,t,n){const s=++Yt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Vt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Gt(e){Vt().push({schedule:jt.Update,system:e})}function qt(e){Vt().push({schedule:jt.Startup,system:e})}function Kt(e,t){Vt().push({schedule:e,system:t})}class Jt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof zt&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new At(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new zt(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Lt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ht(n)}case"removed":{const t=e;return new kt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Qt{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 Zt=nt(new Qt,"Input");class en{constructor(e){this.target_=e??null}build(e){const n=new Qt;e.insertResource(Zt,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(jt.Last,Nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const tn=new en,nn=nt({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var sn;function rn(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"}(sn||(sn={}));let on=null,an=null,ln=1;const cn=new Map;function dn(e){on=e,an=e.getResourceManager(),xn()}function un(){0!==gn&&on&&(on._free(gn),gn=0),cn.clear(),ln=1,pn=!1,mn.clear(),_n=null,an=null,on=null}function hn(){if(!an)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return an}const fn={createShader:(e,t)=>hn().createShader(e,t),releaseShader(e){e>0&&hn().releaseShader(e)},create(e){const t=ln++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??sn.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return cn.set(t,n),t},get:e=>cn.get(e),setUniform(e,t,n){const s=cn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,on?.invalidateMaterialCache(e))},getUniform(e,t){const n=cn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=cn.get(e);n&&(n.blendMode=t,on?.invalidateMaterialCache(e))},getBlendMode(e){const t=cn.get(e);return t?.blendMode??sn.Normal},setDepthTest(e,t){const n=cn.get(e);n&&(n.depthTest=t,on?.invalidateMaterialCache(e))},getShader(e){const t=cn.get(e);return t?.shader??0},release(e){cn.delete(e),on?.invalidateMaterialCache(e)},isValid:e=>cn.has(e),releaseAll(){cn.clear(),on?.clearMaterialCache()},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??sn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=cn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ln++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return cn.set(n,s),n},toAssetData(e,t){const n=cn.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=cn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let pn=!1,gn=0;const yn=16384,mn=new Map;let _n=null;function wn(e){const t=(0===gn&&on&&(gn=on._malloc(yn)),gn);if(0===t||!on)return{ptr:0,count:0};let n=0,s=0;const i=on.HEAPU8,r=on.HEAPU32,o=on.HEAPF32;for(const[a,l]of e){if(rn(l))continue;let e=mn.get(a);e||(_n||(_n=new TextEncoder),e=_n.encode(a),mn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>yn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${yn} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=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?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);r[t+n>>2]=u,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function xn(){if(!on||pn)return;on.materialDataProvider=(e,t,n,s,i)=>{const r=cn.get(e);if(!r)return on.HEAPU32[t>>2]=0,on.HEAPU32[n>>2]=0,on.HEAPU32[s>>2]=0,void(on.HEAPU32[i>>2]=0);on.HEAPU32[t>>2]=r.shader,on.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=wn(r.uniforms);on.HEAPU32[s>>2]=o,on.HEAPU32[i>>2]=a},pn=!0}const vn={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 bn{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Sn{constructor(e,t=""){this.cache_=new bn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(fn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())fn.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 i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:fn.createFromAsset(s,r),shaderHandle:r,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 Pn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Mn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:n.get(e.texture)??0}))}}const Tn=new Map;function En(e){Tn.set(e.name,e)}function Cn(e){Tn.delete(e)}function Rn(e){return Tn.get(e)}function An(){Tn.clear()}const In=be("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function kn(e,t){const n=e.getEntitiesWithComponents([In]);for(const s of n){const n=e.get(s,In);if(!n.enabled||!n.playing||!n.clip)continue;const i=Tn.get(n.clip);if(!i||0===i.frames.length)continue;const r=1/(i.fps*n.speed),o=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=o;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,De)){const t=i.frames[n.currentFrame],r=e.get(s,De);r.texture=t.texture,e.insert(s,De,r)}a&&e.insert(s,In,n)}}const Fn=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}]]);function Bn(e,t){Fn.set(e,t)}function zn(e){const t=Fn.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Un(e){return Fn.get(e)?.fields??[]}function Wn(e){return Fn.get(e)?.spine??null}const $n=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Dn(e,t){$n.set(e,t)}function On(e){return $n.get(e)}function Ln(e,t){const n=$n.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function Hn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Ve,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Ln(i,n),Nn(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function jn(e,t){return Hn(e,t)}async function Xn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,r=new Map;s&&await async function(e,t,n,s,i){const r=new Map;for(const e of Yn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Fn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...Yn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Fn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,r,n?.collectAssets);const o=Hn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const Yn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),r=Pn(i),o=new Map,a=r.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),o.set(e,0)}});await Promise.all(a);En(Mn(e,i,o))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Nn(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=Ie(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Vn(e,t){const n=e.getEntitiesWithComponents([Oe]);for(const s of n){const n=e.get(s,Oe);n&&(n.aspectRatio=t,e.insert(s,Oe,n))}}function Gn(e,t){const n=e.getEntitiesWithComponents([Ve]);for(const s of n){const n=e.get(s,Ve);if(n&&n.value===t)return s}return null}class qn{constructor(e){this.textureCache_=new bn,this.shaderCache_=new bn,this.jsonCache_=new bn,this.textCache_=new bn,this.binaryCache_=new bn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new bn,this.prefabCache_=new bn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=u(re.textCanvasSize,re.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Sn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),fn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===v(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(u,r,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=v(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of zn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=Wn(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 Xn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;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 i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.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.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return fn.createShader(s,i)}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:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return fn.createShader(i,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(k(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(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 o(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.getEmbedded(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 o(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.getEmbedded(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 o(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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 Kn=nt(null,"Assets");class Jn{build(e){const t=e.wasmModule;t?e.insertResource(Kn,new qn(t)):console.warn("AssetPlugin: No WASM module available")}}const Qn=new Jn;class Zn{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function es(e,t){const n=e.getResource(Kn);n&&n.registerEmbeddedAssets(t)}async function ts(e,t,n){const{entities:s,rootId:i}=await ss(t,n?.overrides??[],n,void 0,new Set),r={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,visible:e.visible}))},o=await Xn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const ns=10;async function ss(e,t,n,s,i,r=0){if(r>ns)throw new Error(`Prefab nesting depth exceeded ${ns}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await ss(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};is(u.components,o),rs(u,t),l.push(u)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function is(e,t){for(const n of e){const e=On(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}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))}}class os{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return ts(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const as=nt(null,"Prefabs");class ls{constructor(){this.name="PrefabsPlugin",this.dependencies=[Kn]}build(e){const t=e.getResource(Kn);e.insertResource(as,new os(e.world,t))}}const cs=new ls;let ds=null,us=0,hs=0,fs=0;const ps=new Float32Array(256);function gs(e){ds=e,us=ds._malloc(64),hs=ds._malloc(64),fs=ds._malloc(1024)}function ys(){ds&&(us&&(ds._free(us),us=0),hs&&(ds._free(hs),hs=0),fs&&(ds._free(fs),fs=0)),ds=null}function ms(){if(!ds)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ds}const _s={r:1,g:1,b:1,a:1},ws={begin(e){const t=ms();try{t.HEAPF32.set(e,us/4),t.draw_begin(us)}catch(e){ft(e,"Draw.begin")}},end(){try{ms().draw_end()}catch(e){ft(e,"Draw.end")}},line(e,t,n,s=1){try{ms().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ft(e,"Draw.line")}},rect(e,t,n,s=!0){try{ms().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ft(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{ms().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ft(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{ms().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ft(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{ms().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ft(e,"Draw.circleOutline")}},texture(e,t,n,s=_s){try{ms().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ft(e,"Draw.texture")}},textureRotated(e,t,n,s,i=_s){try{ms().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ft(e,"Draw.textureRotated")}},setLayer(e){ms().draw_setLayer(e)},setDepth(e){ms().draw_setDepth(e)},getDrawCallCount:()=>ds?ds.draw_getDrawCallCount():0,getPrimitiveCount:()=>ds?ds.draw_getPrimitiveCount():0,setBlendMode(e){ms().draw_setBlendMode(e)},setDepthTest(e){ms().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ms();s.HEAPF32.set(n,hs/4),s.draw_mesh(e,t,hs)}catch(n){ft(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ms(),i=fn.get(t);if(!i)return;if(ws.setBlendMode(i.blendMode),ws.setDepthTest(i.depthTest),0===i.uniforms.size)return void ws.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,hs/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=bs(t);if(!(s<0)){if(rn(n))ps[r++]=10,ps[r++]=s,ps[r++]=n.slot??e++,ps[r++]=n.textureId;else if("number"==typeof n)ps[r++]=1,ps[r++]=s,ps[r++]=n;else if(Array.isArray(n)){ps[r++]=n.length,ps[r++]=s;for(let e=0;e<n.length;e++)ps[r++]=n[e]}else"w"in n?(ps[r++]=4,ps[r++]=s,ps[r++]=n.x,ps[r++]=n.y,ps[r++]=n.z,ps[r++]=n.w):"z"in n?(ps[r++]=3,ps[r++]=s,ps[r++]=n.x,ps[r++]=n.y,ps[r++]=n.z):(ps[r++]=2,ps[r++]=s,ps[r++]=n.x,ps[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(ps.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,hs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),fs/4),s.draw_meshWithUniforms(e,i.shader,hs,fs,r)}catch(n){ft(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},xs={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},vs=new Set;function bs(e){const t=xs[e];return void 0!==t?t:(vs.has(e)||(vs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(xs).join(", ")}`)),-1)}const Ss=new Map;function Ps(e,t,n){Ss.set(e,{fn:t,scene:n??""})}function Ms(e){Ss.delete(e)}function Ts(){Ss.clear()}var Es;!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"}(Es||(Es={}));let Cs=null,Rs=0,As=0,Is=0;function ks(e){Cs=e,Rs=Cs._malloc(262144),As=Cs._malloc(65536),Is=Cs._malloc(256)}function Fs(){Cs&&(Rs&&Cs._free(Rs),As&&Cs._free(As),Is&&Cs._free(Is),Rs=0,As=0,Is=0),Cs=null}function Bs(){if(!Cs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Cs}const zs={create(e){const t=Bs(),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,Rs/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Is,i).set(r),t.geometry_init(n,Rs,s,Is,i,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,As,s).set(e.indices),t.geometry_setIndices16(n,As,s)}else{new Uint32Array(t.HEAPU8.buffer,As,s).set(e.indices),t.geometry_setIndices32(n,As,s)}}return n},updateVertices(e,t,n=0){const s=Bs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,Rs/4),s.geometry_updateVertices(e,Rs,i,n)},release(e){e>0&&Bs().geometry_release(e)},isValid:e=>!(!Cs||e<=0)&&Cs.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return zs.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:Es.Float2},{name:"a_texCoord",type:Es.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 i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return zs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Es.Float2},{name:"a_texCoord",type:Es.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,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return zs.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:Es.Float2},{name:"a_texCoord",type:Es.Float2}],indices:new Uint16Array(o)})}};let Us=null;function Ws(e){Us=e}function $s(){Us&&Os.isInitialized()&&Os.shutdown(),Us=null}function Ds(){if(!Us)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Us}const Os={init(e,t){try{return Ds().postprocess_init(e,t)}catch(n){return ft(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ds().postprocess_shutdown()}catch(e){ft(e,"PostProcess.shutdown")}},resize(e,t){try{Ds().postprocess_resize(e,t)}catch(n){ft(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ds().postprocess_addPass(e,t)}catch(t){return ft(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ds().postprocess_removePass(e)}catch(t){ft(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ds().postprocess_setPassEnabled(e,t)}catch(t){ft(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ds().postprocess_isPassEnabled(e)}catch(t){return ft(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ds().postprocess_setUniformFloat(e,t,n)}catch(n){ft(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ds().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ft(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ds().postprocess_begin()}catch(e){ft(e,"PostProcess.begin")}},end(){try{Ds().postprocess_end()}catch(e){ft(e,"PostProcess.end")}},getPassCount(){try{return Ds().postprocess_getPassCount()}catch(e){return ft(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Us)return!1;try{return Us.postprocess_isInitialized()}catch(e){return ft(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ds().postprocess_setBypass(e)}catch(e){ft(e,"PostProcess.setBypass")}},isBypassed(){if(!Us)return!0;try{return Us.postprocess_isBypassed()}catch(e){return ft(e,"PostProcess.isBypassed"),!0}},createBlur:()=>fn.createShader(Ls,"#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:()=>fn.createShader(Ls,"#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:()=>fn.createShader(Ls,"#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:()=>fn.createShader(Ls,"#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")},Ls="#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 Hs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Hs||(Hs={}));let js=null,Xs=0;function Ys(e){js=e,Xs=js._malloc(64)}function Ns(){js&&Xs&&(js._free(Xs),Xs=0),js=null}const Vs={init(e,t){js?.renderer_init(e,t)},resize(e,t){js?.renderer_resize(e,t)},begin(e,t){if(js&&Xs)try{js.HEAPF32.set(e,Xs/4),js.renderer_begin(Xs,t??0)}catch(e){ft(e,"Renderer.begin")}},flush(){try{js?.renderer_flush()}catch(e){ft(e,"Renderer.flush")}},end(){try{js?.renderer_end()}catch(e){ft(e,"Renderer.end")}},submitSprites(e){if(js)try{js.renderer_submitSprites(e._cpp)}catch(e){ft(e,"Renderer.submitSprites")}},submitBitmapText(e){if(js)try{js.renderer_submitBitmapText(e._cpp)}catch(e){ft(e,"Renderer.submitBitmapText")}},submitSpine(e){if(js)try{js.renderer_submitSpine?.(e._cpp)}catch(e){ft(e,"Renderer.submitSpine")}},setStage(e){js?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>js?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){js?.renderer_releaseTarget(e)},getTargetTexture:e=>js?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>js?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){js?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){js?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){js?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){js?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>js?js.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>js?{drawCalls:js.renderer_getDrawCalls(),triangles:js.renderer_getTriangles(),sprites:js.renderer_getSprites(),text:js.renderer_getText(),spine:js.renderer_getSpine?.()??0,meshes:js.renderer_getMeshes(),culled:js.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Gs=null;function qs(e){Gs=e}function Ks(){Gs=null}const Js={enable(){Gs?.gl_enableErrorCheck(!0)},disable(){Gs?.gl_enableErrorCheck(!1)},check:e=>Gs?.gl_checkErrors(e)??0,diagnose(){Gs?.renderer_diagnose()}};class Qs{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Vs.resize(s,i),Os.isInitialized()&&Os.getPassCount()>0&&Os.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Vs.setViewport(0,0,s,i),Vs.clearBuffers(3),Vs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(n,r),Vs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Vs.setViewport(s.x,s.y,s.w,s.h),Vs.setScissor(s.x,s.y,s.w,s.h,!0),Vs.clearBuffers(i),Vs.setScissor(0,0,0,0,!1),Vs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(n,r),Vs.end()}executeDrawCallbacks(e,t){const n=Ss;if(n.size>0){ws.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}ws.end();for(const e of s)Ms(e)}}}const Zs="__scene_transition_overlay__";class ei{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ti{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Ge,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ps(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Os.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Os.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Ge)){const n=this.app_.world.get(e,Ge);n.persistent=t,this.app_.world.insert(e,Ge,n)}}}class ni{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??re.sceneTransitionDuration,i=t.color??{...re.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Ps(Zs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;ws.setLayer(9999),ws.setDepth(9999),ws.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Ms(Zs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ms(Zs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ei(t);this.scenes_.set(e,n);const s=new ti(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Kn)?this.app_.getResource(Kn):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ei(t);this.scenes_.set(e,n);const s=new ti(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Kn)?this.app_.getResource(Kn):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Ge)){if(this.app_.world.get(e,Ge).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Ms(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Os.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Kn)&&(i.assetServer=this.app_.getResource(Kn));const r=await Xn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,Ge,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=ii(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Kn)?this.app_.getResource(Kn):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)fn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,De)){const t=n.get(e,De);s.sprite=t.color.a,t.color.a=0,n.insert(e,De,t),i=!0}if(n.has(e,Ne)){const t=n.get(e,Ne);s.spine=t.color.a,t.color.a=0,n.insert(e,Ne,t),i=!0}if(n.has(e,Ye)){const t=n.get(e,Ye);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Ye,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,De)){const t=n.get(e,De);t.color.a=s.sprite,n.insert(e,De,t)}if(void 0!==s.spine&&n.has(e,Ne)){const t=n.get(e,Ne);t.color.a=s.spine,n.insert(e,Ne,t)}if(void 0!==s.bitmapText&&n.has(e,Ye)){const t=n.get(e,Ye);t.color.a=s.bitmapText,n.insert(e,Ye,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Os.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const si=nt(null,"SceneManager");function ii(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(si).getSceneStatus(t)&&n._fn(...s)}}}const ri=Nt([it(si),st(at)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),oi={name:"SceneManager",build(e){const t=new ni(e);e.insertResource(si,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(si),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(jt.Startup,n),e.addSystemToSchedule(jt.Last,ri)}};class ai{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new $t,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(jt.Last);else{this.runSchedule(jt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(jt.FixedPreUpdate),this.runSchedule(jt.FixedUpdate),this.runSchedule(jt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(jt.PreUpdate),this.runSchedule(jt.Update),this.runSchedule(jt.PostUpdate),this.runSchedule(jt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new xt,this.resources_=new ot;for(const e of Object.values(jt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ai}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(jt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(jt.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return ht(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(si).register(e),this}setInitialScene(e){return this.getResource(si).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Jt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(at)||this.resources_.insert(at,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(jt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(jt.Last);else{this.runSchedule(jt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(jt.FixedPreUpdate),this.runSchedule(jt.FixedUpdate),this.runSchedule(jt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(jt.PreUpdate),this.runSchedule(jt.Update),this.runSchedule(jt.PostUpdate),this.runSchedule(jt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Jt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(at,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(jt.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,Ts();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Ks,Ns,$s,Fs,un,ys];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(at);t.delta=e,t.elapsed+=e,t.frameCount++}}function li(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const ci=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function di(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case ze.FixedWidth:return r;case ze.FixedHeight:return o;case ze.Expand:return Math.max(r,o);case ze.Shrink:return Math.min(r,o);case ze.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const ui=[];function hi(e){if(e<ui.length)return ui[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return ui.push(t),t}function fi(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,Ge);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,u=0;if(i.projectionType===Fe.Orthographic){if(u=i.orthoSize,l){u=di(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=u*o,a=gi(-d,d,-u,u,-i.farPlane,i.farPlane)}else a=mi(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const h=wi(r.position.x,r.position.y,r.position.z),f=hi(c.length);f.entity=e,f.viewProjection.set(vi(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=u,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const pi=new Float32Array(16);function gi(e,t,n,s,i,r){const o=pi;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const yi=new Float32Array(16);function mi(e,t,n,s){const i=yi;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const _i=new Float32Array(16);function wi(e,t,n){const s=_i;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}const xi=new Float32Array(16);function vi(e,t){const n=xi;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const bi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Si(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,u=r.bottom+e.y*l,h=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=u+n.y-i.y*o.y,y=p+i.y):(p=u+n.y,y=h+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+o.x*m,originY:p+o.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const Pi=ke("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}});let Mi=null,Ti=null;function Ei(e,t){e.has(t,De)||e.insert(t,De,{texture:de,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})}function Ci(e,t){switch(e){case bi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case bi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case bi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Ri(e,t){switch(e){case bi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case bi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case bi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Ai(e,t,n,s){switch(e){case bi.BottomToTop:case bi.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Ii(e,t,n,s){if(!e.has(t,Pi))return;const i=e.get(t,Pi),r=Ci(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Pi,i)}function ki(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Fi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Bi(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(Fi(o.charCodeAt(0))&&s.length>0&&Fi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Fi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function zi(e){let t=1;for(;t<e;)t*=2;return t}function Ui(e,t){let n=0,s=t;for(;e.has(s,je);){const t=e.get(s,je).entity;if(!e.valid(t))break;n++,s=t}return n}function Wi(e,t){if(Mi&&Ti){const e=Mi.getUIRectComputedWidth(Ti,t);if(e>0)return e}return e.size.x}function $i(e,t){if(Mi&&Ti){const e=Mi.getUIRectComputedHeight(Ti,t);if(e>0)return e}return e.size.y}function Di(e,t,n,s,i,r){if(!e.has(t,De))return;const o=e.get(t,De);let a,l;switch(n){case bi.BottomToTop:case bi.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,De,o))}function Oi(e,t,n){let s=t;for(;e.has(s,je);){const t=e.get(s,je).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Li(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Hi(e,t,n,s,i){if(!e.has(t,Pi))return;const r=e.get(t,Pi),o=Si(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,De)){const n=e.get(t,De);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,De,n))}if(e.has(t,Ue)){const n=e.get(t,Ue);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,Ue,n)}}function ji(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Xi=.1,Yi=30,Ni={r:.3,g:.5,b:.8,a:1},Vi={Left:0,Center:1,Right:2},Gi={Top:0,Middle:1,Bottom:2},qi={Visible:0,Clip:1,Ellipsis:2},Ki=be("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Vi.Left,verticalAlign:Gi.Top,wordWrap:!0,overflow:qi.Visible,lineHeight:1.2});class Ji{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=u(re.textCanvasSize,re.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,zi(this.frameMaxW_)),e.height=Math.max(e.height,zi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=zi(this.frameMaxW_),e.height=zi(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=Bi(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(r):u+2*d,p=i?Math.ceil(o):h+2*d;if(i&&e.overflow===qi.Ellipsis&&h>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,zi(f)),s.height=Math.max(s.height,zi(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=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(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===qi.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Gi.Top:x=d;break;case Gi.Middle:x=d+(p-2*d-w)/2;break;case Gi.Bottom:x=p-w-d;break;default:x=d}x<0&&(x=0)}else x=d;let v=x;for(const t of l){let s;switch(e.align){case Vi.Left:s=d;break;case Vi.Center:s=f/2;break;case Vi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===qi.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Vi.Left:return"left";case Vi.Center:return"center";case Vi.Right:return"right"}}}const Qi=ji({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Wi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?$i(e.uiRect,e.entity):0});class Zi{build(e){Ae("Text",Ki);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ji(t),s=e.world,i=new Map;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ki));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Ki)){if(s.valid(e)&&s.has(e,De)){const t=s.get(e,De);s.insert(e,De,{texture:de,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=s.getEntitiesWithComponents([Ki]);for(const t of e){const e=s.get(t,Ki),r=s.has(t,Pi)?s.get(t,Pi):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Qi.changed(a,o)){if(s.has(t,De)&&s.get(t,De).texture!==de)continue}Ei(s,t);const l=r?{size:{x:Wi(r,t),y:$i(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,De);s.insert(t,De,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,Qi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const er=new Zi,tr=0,nr=1,sr=ke("UIMask",{enabled:!0,mode:tr});function ir(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function rr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,P=r*d-o*c,M=u*y-h*g,T=u*m-f*g,E=u*_-p*g,C=h*m-f*y,R=h*_-p*y,A=f*_-p*m;let I=w*A-x*R+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,n[0]=(l*A-c*R+d*C)*I,n[1]=(r*R-i*A-o*C)*I,n[2]=(y*P-m*S+_*b)*I,n[3]=(f*S-h*P-p*b)*I,n[4]=(c*E-a*A-d*T)*I,n[5]=(s*A-r*E+o*T)*I,n[6]=(m*v-g*P-_*x)*I,n[7]=(u*P-f*v+p*x)*I,n[8]=(a*R-l*E+d*M)*I,n[9]=(i*E-s*R-o*M)*I,n[10]=(g*S-y*v+_*w)*I,n[11]=(h*v-u*S-p*w)*I,n[12]=(l*T-a*C-c*M)*I,n[13]=(s*C-i*T+r*M)*I,n[14]=(y*x-g*b-m*w)*I,n[15]=(u*b-h*x+f*w)*I),n}function or(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],u=n[3]*a+n[7]*l+n[15];return{x:c/u,y:d/u}}function ar(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function lr(e,t){return 2*Math.atan2(e,t)}function cr(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function dr(e,t,n,s,i,r,o,a,l,c){const d=lr(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-n,p=t-s,g=f*h-p*u+n,y=f*u+p*h+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function ur(e,t,n,s,i,r,o){if(!e.has(t,Pi)||!e.has(t,Ue))return null;const a=e.get(t,Pi),l=e.get(t,Ue),c=Wi(a,t)*l.worldScale.x,d=$i(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),w=lr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[u+g*x-m*v,h+g*v+m*x],[u+y*x-m*v,h+y*v+m*x],[u+y*x-_*v,h+y*v+_*x],[u+g*x-_*v,h+g*v+_*x]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=cr(e,t,n,s,i,r,o);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function hr(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([sr]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const n=t.get(e,sr);n.enabled&&(u.add(e),n.mode===nr?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;Oi(t,e,e=>{if(i.has(e)){if(t.get(e,sr).mode===tr)return n=!1,!0}return!1}),n&&d.push(e)}function u(s,d){const h=e.getChildEntities(n,s);for(const n of h){let s=d;if(i.has(n)){if(t.get(n,sr).mode===tr){const e=ur(t,n,r,o,a,l,c);e&&(s=ir(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),u(n,s)}}for(const e of d){const n=ur(t,e,r,o,a,l,c);n&&u(e,n)}}(e,t,n,c,u,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Oi(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class fr{build(e){if(Ae("UIMask",sr),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(hr(e.wasmModule,e.world))}}const pr=new fr,gr=ke("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),yr=ke("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),mr={Normal:0,Hovered:1,Pressed:2,Disabled:3},_r=be("Button",{state:mr.Normal,transition:null});class wr{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}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 xr=nt(new wr,"UIEvents");class vr{build(e){Ae("UIRect",Pi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Mi=e,Ti=t}(n,s);e.addSystemToSchedule(jt.PreUpdate,Nt([st(nn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(jt.PostUpdate,Nt([st(nn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(jt.PostUpdate,Nt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const br=new vr;let Sr=!1,Pr=!1;function Mr(e){Sr=e}function Tr(){return Sr}function Er(){return!Sr}function Cr(e){Pr=e}function Rr(){return Pr}const Ar=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(rr(t,e),n=!1),e)}}();function Ir(e,t,n,s){t.emit(n,s,n),Oi(e,n,i=>{if(!e.has(i,gr))return!1;const r=e.get(i,gr);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class kr{build(e){Ae("Interactable",gr),Ae("Button",_r);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new wr;e.insertResource(xr,i);let r=null,o=null;e.addSystemToSchedule(jt.PreUpdate,Nt([st(Zt),st(nn)],(e,a)=>{if(i.drain(),Tr()&&!Rr())return;const l=t.getEntitiesWithComponents([yr]);for(const e of l){const n=t.get(e,yr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,yr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,u=a.screenH-e.mouseY*c;Ar.update(a.viewProjection);const h=or(d,u,Ar.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,h.x,h.y,p,g,y);const m=n.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,yr)){const e=t.get(r,yr);e.hovered=!1,t.insert(r,yr,e),i.emit(r,"hover_exit")}if(null!==_){Li(t,_,yr);const e=t.get(_,yr);e.hovered=!0,t.insert(_,yr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,yr);e.pressed=!0,e.justPressed=!0,t.insert(_,yr,e),o=_,Ir(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,yr)){const e=t.get(o,yr);e.pressed=!1,e.justReleased=!0,t.insert(o,yr,e),Ir(t,i,o,"release"),o===r&&Ir(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(jt.Update,Nt([],()=>{const e=t.getEntitiesWithComponents([_r]);for(const n of e){if(Li(t,n,gr,{enabled:!0}),!t.has(n,yr))continue;const e=t.get(n,yr),s=t.get(n,_r),i=t.get(n,gr),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=mr.Pressed:e.hovered?s.state=mr.Hovered:s.state=mr.Normal:s.state=mr.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,De)){const r=t.get(n,De);r.color=ki(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,De,r)}}},{name:"ButtonSystem"}))}}const Fr=new kr,Br=be("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}),zr=be("Focusable",{tabIndex:0,isFocused:!1});class Ur{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Wr=nt(new Ur,"FocusManager");class $r{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ae("TextInput",Br),Tr()&&!Rr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=u(re.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;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}();if(!f)return;const p=f;function g(){const t=e.getResource(Wr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Br)?s:null}const y=()=>{l||null===g()||v()},m=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,Br);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(xr).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,Br);s.focused=!1,s.dirty=!0;e.getResource(Wr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,Br);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(xr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=n.get(t,Br);e.focused=!1,e.dirty=!0}e.getResource(Wr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let P=null;function M(e,l,d,u){(i.width<d||i.height<u)&&(i.width=zi(Math.max(i.width,d)),i.height=zi(Math.max(i.height,u))),r.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,r.fillRect(0,0,d,u),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,u),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=Bi(r,p,d-2*m);let t=m;for(const n of e)r.fillText(n,m,t),t+=y}else{const e=(u-l.fontSize)/2;r.fillText(p,m,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=Bi(r,l.value,d-2*m);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=m+r.measureText(c).width,n=m+o*y,s=y}else t=m+r.measureText(e).width,n=(u-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,d,u),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,u,o,w.length,1,!0);s.set(e,b);const S=n.get(e,De);S.texture=b,S.size.x=d,S.size.y=u,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,De,S)}e.addSystemToSchedule(jt.Update,Nt([st(Wr)],e=>{const t=n.getEntitiesWithComponents([Br]);for(const e of t)Li(n,e,zr,{tabIndex:0,isFocused:!1}),Li(n,e,gr,{enabled:!0,blockRaycast:!0});const s=g();if(s!==P){if(null!==P&&n.valid(P)&&n.has(P,Br)){const e=n.get(P,Br);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Br);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),P=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,Br).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Br)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Br,Pi]);for(const e of a){const t=n.get(e,Br);if(!t.dirty)continue;const s=n.get(e,Pi),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(Ei(n,e),M(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Dr=new $r,Or={Simple:0,Sliced:1,Tiled:2,Filled:3},Lr={Horizontal:0,Vertical:1},Hr={Left:0,Right:1,Bottom:2,Top:3},jr=be("Image",{texture:de,color:{r:1,g:1,b:1,a:1},imageType:Or.Simple,fillMethod:Lr.Horizontal,fillOrigin:Hr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Xr=ji({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Wi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?$i(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Yr=new class{build(e){Ae("Image",jr);const t=e.world,n=new Map;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,jr)||n.delete(e);const e=t.getEntitiesWithComponents([jr]);for(const s of e){const e=t.get(s,jr),i=t.has(s,Pi)?t.get(s,Pi):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Xr.changed(o,r))continue;Ei(t,s);const a=t.get(s,De);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Wi(i,s),a.size.y=$i(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Or.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Lr.Horizontal?e.fillOrigin===Hr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Hr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Or.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,De,a),n.set(s,Xr.take(r))}else a.color.a=0,t.insert(s,De,a),n.set(s,Xr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Nr=be("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Vr=be("ToggleGroup",{allowSwitchOff:!1});const Gr=new class{build(e){Ae("Toggle",Nr),Ae("ToggleGroup",Vr);const t=e.world,n=new Set;e.addSystemToSchedule(jt.Update,Nt([st(xr)],e=>{const s=t.getEntitiesWithComponents([Nr]);if(!Tr()||Rr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Nr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Nr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,Nr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Li(t,n,gr,{enabled:!0}),!t.has(n,yr))continue;const s=t.get(n,yr),i=t.get(n,Nr),o=t.get(n,gr);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Vr);if(i.isOn&&o){if(!t.get(s,Vr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Nr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Nr);i.isOn&&(i.isOn=!1,t.insert(s,Nr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,De)){const e=t.get(n,De);e.color=ki(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,De,e)}}}for(const e of s){const n=t.get(e,Nr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,De)){const e=t.get(n.graphicEntity,De);e.enabled=n.isOn,t.insert(n.graphicEntity,De,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},qr=bi,Kr=be("ProgressBar",{value:0,fillEntity:0,direction:bi.LeftToRight});function Jr(e,t,n,s){if(!e.has(t,Pi))return;const i=e.get(t,Pi),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=Si(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,De)){const n=e.get(t,De);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,De,n))}if(e.has(t,Ue)){const n=e.get(t,Ue),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,Ue,n))}}class Qr{build(e){Ae("ProgressBar",Kr);const t=e.world;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{const e=t.getEntitiesWithComponents([Kr,Pi]);for(const n of e){const e=t.get(n,Kr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Pi),i=Math.max(0,Math.min(1,e.value));Ii(t,e.fillEntity,e.direction,i);const r=Wi(s,n),o=$i(s,n);Jr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Zr=new Qr,eo=be("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),to=be("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const no=new class{build(e){Ae("Draggable",eo),Ae("DragState",to);const t=e.world,n=e.getResource(xr);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(jt.PreUpdate,Nt([st(Zt),st(nn)],(e,o)=>{if(Tr()&&!Rr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([eo,yr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,eo).enabled)continue;if(t.get(s,yr).hovered){let e=0;t.has(s,De)&&(e=t.get(s,De).layer);const i=Ui(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,to)||t.insert(n,to);const e=t.get(n,to),r=t.get(n,Ue);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,to)){t.get(s,to).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(s,eo);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,to).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,to))return void(r=null);const s=t.get(r,to),i=t.get(r,eo),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const u=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=u.x,d=u.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,Ue)){const e=function(e,t,n,s){if(!e.has(t,je))return{x:n,y:s};const i=e.get(t,je).entity;if(!e.valid(i)||!e.has(i,Ue))return{x:n,y:s};const r=e.get(i,Ue),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=lr(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,Ue);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,Ue,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},so=be("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function io(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function ro(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const oo=new class{build(e){Ae("ScrollView",so);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(jt.PostUpdate,Nt([st(Zt),st(nn),st(at)],(e,i,r)=>{const o=Tr()&&!Rr(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([so,Pi]);for(const r of l){Li(t,r,sr,{enabled:!0,mode:tr});const l=t.get(r,so),c=t.get(r,Pi);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const u=Wi(c,r),h=$i(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Xe)){const e=t.get(l.contentEntity,Xe).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,Ue))continue;const e=t.get(o,Ue);let a=0,l=0,c=.5,d=.5;if(t.has(o,Pi)){const e=t.get(o,Pi);a=Wi(e,o)||e.size.x,l=$i(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,De)){const e=t.get(o,De);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<n&&(n=u),h>s&&(s=h),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-u),y=Math.max(0,p-h);if(!o&&i.valid){Li(t,r,gr,{enabled:!0,blockRaycast:!0});const n=t.has(r,yr)?t.get(r,yr):null;if(n?.justPressed&&(d.isDragging=!0,d.lastWorldX=s.x,d.lastWorldY=s.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=s.x-d.lastWorldX,t=s.y-d.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=io(l.scrollX,0,g,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=io(l.scrollY,0,y,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=io(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=io(l.scrollX,0,g,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=ro(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Xi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Xi?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=ro(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Xi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Xi?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Ue)){const e=t.get(l.contentEntity,Ue),n=e.position.x,s=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(n-d.lastAppliedX)>.01)&&(d.contentBaseX=n),(isNaN(d.lastAppliedY)||Math.abs(s-d.lastAppliedY)>.01)&&(d.contentBaseY=s),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,Ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},ao=bi,lo=be("Slider",{value:0,minValue:0,maxValue:1,direction:bi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function co(e,t,n,s,i,r){const o=Wi(s,i)*n.worldScale.x,a=$i(s,i)*n.worldScale.y,l=lr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-n.worldPosition.x,h=t-n.worldPosition.y,f=u*d-h*c,p=u*c+h*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case bi.LeftToRight:return o>0?(f-g)/o:0;case bi.RightToLeft:return o>0?1-(f-g)/o:0;case bi.BottomToTop:return a>0?(p-y)/a:0;case bi.TopToBottom:return a>0?1-(p-y)/a:0}}function uo(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case bi.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case bi.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case bi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case bi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class ho{build(e){Ae("Slider",lo);const t=e.world;let n=null;e.addSystemToSchedule(jt.PreUpdate,Nt([st(Zt),st(nn),st(xr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([lo,Pi]);for(const o of r){const r=t.get(o,lo),a=t.get(o,Pi);if(!Tr()||Rr()){if(t.has(o,Ue)){Li(t,o,gr,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Li(t,r.handleEntity,gr,{enabled:!0,blockRaycast:!1});const l=t.get(o,Ue),c=t.has(o,yr)?t.get(o,yr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,yr)&&(d=t.get(r.handleEntity,yr).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=co(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,lo,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=Wi(a,o),u=$i(a,o),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(Ii(t,r.fillEntity,r.direction,c),Hi(t,r.fillEntity,h,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Pi)){const e=t.get(r.handleEntity,Pi);uo(e,r.direction,c),t.insert(r.handleEntity,Pi,e),Hi(t,r.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const fo=new ho;const po=new class{build(e){Ae("Focusable",zr);const t=e.world,n=new Ur;e.insertResource(Wr,n),e.addSystemToSchedule(jt.Update,Nt([st(Zt),st(xr)],(e,s)=>{if(Tr()&&!Rr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([zr]);for(const e of i){if(!t.has(e,yr))continue;t.get(e,yr).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,gr)){if(!t.get(n,gr).enabled)continue}const s=t.get(n,zr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,zr)){t.get(i,zr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,zr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},go=be("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function yo(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const mo=new class{build(e){Ae("SafeArea",go);const t=e.world;let n=yo(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=yo(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=yo(),s=!0});e.addSystemToSchedule(jt.PreUpdate,Nt([st(nn)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([go,Pi]);for(const e of d){const s=t.get(e,go),i=t.get(e,Pi),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,Pi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},_o=be("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let wo=null;function xo(e,t){if(!wo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=wo.get(e);n?n.renderer=t:wo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const vo=new class{build(e){Ae("ListView",_o);const t=e.world,n=new Map;wo=n,e.addSystemToSchedule(jt.PostUpdate,Nt([st(Zt)],e=>{const s=Tr()&&!Rr();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([_o,Pi]);for(const r of i){Li(t,r,gr,{enabled:!0,blockRaycast:!0}),Li(t,r,sr,{enabled:!0,mode:tr});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,_o),a=t.get(r,Pi),l=$i(a,r),c=Wi(a,r);if(!s){const n=t.has(r,yr)?t.get(r,yr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const u=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),h=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<u||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=u;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ve,{value:`ListItem_${e}`}),t.insert(n,Pi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Ue)){const s=t.get(n,Ue);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Ue,s)}}i.visibleStart=u,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},bo=be("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const So=new class{build(e){Ae("Dropdown",bo);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Ue))return;const n=t.get(e,Ue);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Ue,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,De)){const n=t.get(e,De);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,De,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,De),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Yi;t.insert(i,Pi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Ue,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,De,{texture:de,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*Yi;t.insert(r,Ve,{value:`Option_${e}`}),t.insert(r,Pi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Yi},offsetMax:{x:0,y:0},size:{x:o,y:Yi},pivot:{x:.5,y:.5}}),t.insert(r,Ue,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,De,{texture:de,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Yi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,gr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,Ue,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Ki,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Vi.Left,verticalAlign:Gi.Middle,wordWrap:!1,overflow:qi.Clip,lineHeight:1.2}),t.insert(c,Pi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Yi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}u(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Ki))return;const s=t.get(n,Ki);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Ki,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,gr)&&t.insert(e,gr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,De))){const s=t.get(e,De);t.insert(e,De,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function u(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,De))continue;const i=n===e.highlightIndex?{...Ni}:{r:.95,g:.95,b:.95,a:1};t.insert(s,De,{texture:de,color:i,size:{x:e.ddWidth,y:Yi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,yr))continue;if(t.get(n,yr).hovered)return!0}return!1}e.addSystemToSchedule(jt.Update,Nt([st(Zt),st(xr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Tr()&&!Rr(),p=t.getEntitiesWithComponents([bo]);for(const g of p){const p=t.get(g,bo);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Li(t,g,gr,{enabled:!0,blockRaycast:!0});const m=t.has(g,yr)?t.get(g,yr):null;if(m?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,yr))continue;if(t.get(n,yr).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,yr))continue;if(t.get(s,yr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,u(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,u(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,u(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||h(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Po=0,Mo=0,To=2,Eo=be("LayoutGroup",{direction:Po,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Mo,reverseOrder:!1});const Co=new class{build(e){Ae("LayoutGroup",Eo);const t=e.world;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{const e=t.getEntitiesWithComponents([Eo,Pi,Xe]);for(const n of e){const e=t.get(n,Eo),s=t.get(n,Pi),i=t.get(n,Xe);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,Pi)&&t.has(e,Ue)&&r.push({entity:e,rect:t.get(e,Pi)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Wi(s,n),a=$i(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,u=e.direction===Po;let h=0;for(let n=0;n<r.length;n++){const s=r[n],i=Wi(s.rect,s.entity),f=$i(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;u?(y=-l*o+d.left+h+p*i,m=e.childAlignment===Mo?(1-c)*a-d.top-(1-g)*f:e.childAlignment===To?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,h+=i,n<r.length-1&&(h+=e.spacing)):(y=e.childAlignment===Mo?-l*o+d.left+p*i:e.childAlignment===To?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,m=(1-c)*a-d.top-h-(1-g)*f,h+=f,n<r.length-1&&(h+=e.spacing));const _=t.get(s.entity,Ue);_.position.x=y,_.position.y=m,t.insert(s.entity,Ue,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};ke("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),ke("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class Ro{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(jt.PostUpdate,Nt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Ao=new Ro;async function Io(e,t,n){const s=e.getResource(si);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function ko(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Fo=nt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Bo=nt(null,"PhysicsAPI");function zo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Uo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wo{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(Fo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ko(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([Le]);for(const n of t){const t=e.world.get(n,Le);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(jt.PostUpdate,Nt([st(at)],a=>{const l=o.getEntitiesWithComponents([Ke,Ue]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,Ke),l=o.get(i,Ue);if(t.has(i)){const e=n.get(i);!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(i,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 o=zo(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),$o(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===et.Kinematic){const e=zo(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,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 i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,Ue);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(o,je)){const t=e.world.get(o,je);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Ue)){const n=e.world.get(t.entity,Ue),s=zo(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);u=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=u,d.position.y=h;const p=Uo(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,Ue,d)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.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=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(Fo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Bo,Do._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function $o(e,t,n){const s=e.world;if(s.has(n,Je)){const e=s.get(n,Je);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,Qe)){const e=s.get(n,Qe);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,Ze)){const e=s.get(n,Ze);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 Do{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(Do.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)}}const Oo={nearest:0,linear:1},Lo={repeat:0,clamp:1,mirror:2};function Ho(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Oo[s.filterMode??"linear"]??1,a=Lo[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function jo(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 Xo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,g=a*h,y=a*f,m=l*h,_=l*f,w=c*f,x=d*u,v=d*h,b=d*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Yo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Un(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=Ho(e,await n.loadPixels(r),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${r}`,e),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 i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let d={},u=null;if(i&&(u=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"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=Wn(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===v(c)?.contentType;let u,h;if(o){const e=await i.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);h=n.length,u=t._malloc(h+1),t.HEAPU8.set(n,u),t.HEAPU8[u+h]=0}const f=n.loadSkeleton(u,h,s,s.length,o);if(t._free(u),f<0)continue;r[a]=f;const p=jo(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=Ho(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,u,n,s)),r){const t={gravity:o?.gravity??{...ne},fixedTimestep:o?.fixedTimestep??se,subStepCount:o?.subStepCount??4};new Wo("",t,()=>Promise.resolve(r)).build(e)}const h=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Un(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=v(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=Ho(e,c,!1),u=e.getResourceManager();s[r]=u.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Un(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=fn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=fn.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Un(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(n,c,h,f);const p=jn(e.world,n);if(l&&e.hasResource(si))for(const t of p.values())e.world.insert(t,Ge,{scene:l,persistent:!1});if(i&&u){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=Wn(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(u,n,d,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=te);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,Ne)?c.get(r,Ne):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&s.update(o,l*u);let h=0;if(c.has(r,Ue)){const e=Xo(c.get(r,Ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),u=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,u,f);const p=n.HEAPU32[u>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,d,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,h),t._free(_),t._free(w),n._free(c),n._free(d),n._free(u),n._free(f)}h&&t._free(h)}})}(e,t,i,u,s)}if(a){const t=e.getResource(Kn);t&&t.setAddressableManifest(a)}}function No(e,t,n){return{name:e,async setup(){await Yo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Vo{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Wn(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Un(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=v(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}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(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Go="__preview__";class qo{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(si);t.register({name:Go,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Go),this.loadPromise_=t.load(Go).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Vo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Yo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Go)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Oe]);for(const s of n){if(e.get(s,Oe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Le]);for(const i of s){const s=e.get(i,Le);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(si).getScene(Go),r=i?i.spawn():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},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,Ue,o);const a={isActive:!0,projectionType:Fe.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Be.ColorAndDepth};e.insert(r,Oe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(si);await e.switchTo(Go),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Ko={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Vs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Vs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Vs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Vs.releaseRenderTarget(e._handle),Ko.create({width:t,height:n,depth:!0})),begin(e,t){Vs.begin(t,e._handle)},end(){Vs.end()},getDepthTexture:e=>Vs.getTargetDepthTexture(e._handle)};var Jo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Jo||(Jo={}));class Qo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Jo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Jo.Debug:console.debug(t,n);break;case Jo.Info:console.log(t,n);break;case Jo.Warn:console.warn(t,n);break;case Jo.Error:console.error(t,n)}}}class Zo{constructor(){this.handlers_=[],this.minLevel_=Jo.Info,this.addHandler(new Qo)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Jo.Debug,e,t,n)}info(e,t,n){this.log(Jo.Info,e,t,n)}warn(e,t,n){this.log(Jo.Warn,e,t,n)}error(e,t,n){this.log(Jo.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ea=new Zo;function ta(){return ea}function na(e){ea.setMinLevel(e)}function sa(e,t,n){ea.debug(e,t,n)}function ia(e,t,n){ea.info(e,t,n)}function ra(e,t,n){ea.warn(e,t,n)}function oa(e,t,n){ea.error(e,t,n)}const aa={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},la={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},ca={Running:0,Paused:1,Completed:2,Cancelled:3},da={None:0,Restart:1,PingPong:2};class ua{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ha=null,fa=null;function pa(e,t){ha=e,fa=t}function ga(){ha=null,fa=null}function ya(){if(!ha)throw new Error("Tween API not initialized");return ha}function ma(){if(!fa)throw new Error("Tween API not initialized");return fa}const _a={to(e,t,n,s,i,r){const o=ya(),a=ma(),l=r?.easing??aa.Linear,c=r?.delay??0,d=r?.loop??da.None,u=r?.loopCount??0,h=o._anim_createTween(a,e,t,n,s,i,l,c,d,u);return new ua(o,a,h)},cancel(e){ya()._anim_cancelTween(ma(),e.entity)},cancelAll(e){ya()._anim_cancelAllTweens(ma(),e)},update(e){ya()._anim_updateTweens(ma(),e)}};class wa{constructor(){this.name="AnimationPlugin"}build(e){pa(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(jt.Update,Nt([st(at)],e=>{_a.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(jt.Update,Nt([st(at)],e=>{kn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ga()}}const xa=new wa;class va{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function ba(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Sa(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:r}=e,o=t.getResource(Kn);o&&(o.registerEmbeddedAssets(s),o.setEmbeddedOnly(!0)),li(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ba(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await ba(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=No(r,i,{app:t,module:n,provider:new va(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(si);d.register(c),d.setInitial(r),await d.load(r);const u=e.canvas.width/e.canvas.height;Vn(t.world,u),t.run()}const Pa=[er,pr,br,Yr,Zr,Fr,no,oo,fo,Gr,Dr,po,mo,vo,So,Co,Ao],Ma=[...Pa,xa];function Ta(e,t){return function(e,t){const n=ai.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),gs(e),dn(e),ks(e),Ws(e),Ys(e),qs(e);const i=new Qs;n.setPipeline(i);let r=h();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=fi(e,s,t,i));const o=n.getResource(nn);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(nn,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Vs.setClearColor(e.x,e.y,e.z,e.w)}const d=(h()-r)/1e3;let u;if(Vs.resize(t,l),Os.isInitialized()&&Os.getPassCount()>0&&!Os.isBypassed()&&Os.resize(t,l),n.hasResource(si)){const e=n.getResource(si).getActiveScenes();e.length>0&&(u=new Set(e))}i.setActiveScenes(u??null);const f=fi(e,s,t,l,n.world,u);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:ci,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Vs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(jt.First,l),n.addSystemToSchedule(jt.Last,c),n.addPlugin(Qn),n.addPlugin(cs),n.addPlugin(tn),n.addPlugin(oi),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ma,...t})}class Ea{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Ca(e){return(t,n)=>(d(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Ra(e,t){try{return await e({instantiateWasm:Ca(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Aa(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=k(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),r=wx.createCanvas(),o=wx.getSystemInfoSync();r.width=o.windowWidth*o.pixelRatio,r.height=o.windowHeight*o.pixelRatio;const a=await e.engineFactory({canvas:r,instantiateWasm:Ca("esengine.wasm")}),c=r.getContext("webgl2")||r.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const d=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=Ta(a,{glContextHandle:d,getViewportSize:()=>({width:r.width,height:r.height})});e.runtimeConfig&&le(u,e.runtimeConfig),li(u);let h=null;e.spineFactory&&(h=await Ra(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Ra(e.physicsFactory,"physics.wasm"));const p={app:u,module:a,provider:new Ea(i),spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n},g=u.getResource(si);for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`),n=JSON.parse(e);g.register(No(t,n,p))}e.firstScene&&(g.setInitial(e.firstScene),await g.load(e.firstScene));const y=r.width/r.height;Vn(u.world,y),u.run()}X||(X=!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},i=await p(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 g(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 i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}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 i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Y;export{St as Added,wa as AnimationPlugin,ai as App,Jn as AssetPlugin,Zn as AssetRefCounter,qn as AssetServer,Kn as Assets,bn as AsyncCache,Ye as BitmapText,sn as BlendMode,et as BodyType,Je as BoxCollider,_r as Button,mr as ButtonState,Oe as Camera,Le as Canvas,Ze as CapsuleCollider,Pt as Changed,Xe as Children,Qe as CircleCollider,Be as ClearFlags,Ft as Commands,zt as CommandsInstance,V as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,te as DEFAULT_FALLBACK_DT,se as DEFAULT_FIXED_TIMESTEP,J as DEFAULT_FONT_FAMILY,Q as DEFAULT_FONT_SIZE,ne as DEFAULT_GRAVITY,Z as DEFAULT_LINE_HEIGHT,ee as DEFAULT_MAX_DELTA_TIME,G as DEFAULT_PIXELS_PER_UNIT,ie as DEFAULT_SPINE_SKIN,K as DEFAULT_SPRITE_SIZE,q as DEFAULT_TEXT_CANVAS_SIZE,Es as DataType,to as DragState,eo as Draggable,ws as Draw,bo as Dropdown,aa as EasingType,Bt as EntityCommands,Ot as EventReader,Ht as EventReaderInstance,$t as EventRegistry,Dt as EventWriter,Lt as EventWriterInstance,bi as FillDirection,Lr as FillMethod,Hr as FillOrigin,Wr as FocusManager,Ur as FocusManagerState,zr as Focusable,Js as GLDebug,zs as Geometry,Xt as GetWorld,ce as INVALID_ENTITY,ue as INVALID_FONT,he as INVALID_MATERIAL,de as INVALID_TEXTURE,jr as Image,Or as ImageType,Zt as Input,en as InputPlugin,Qt as InputState,gr as Interactable,_o as ListView,We as LocalTransform,Jo as LogLevel,Zo as Logger,da as LoopMode,fn as Material,Sn as MaterialLoader,vt as Mut,Ve as Name,je as Parent,Do as Physics,Fo as PhysicsEvents,Wo as PhysicsPlugin,Os as PostProcess,os as PrefabServer,as as Prefabs,ls as PrefabsPlugin,qo as PreviewPlugin,Kr as ProgressBar,qr as ProgressBarDirection,Qr as ProgressBarPlugin,Fe as ProjectionType,Rt as Query,At as QueryInstance,It as Removed,kt as RemovedQueryInstance,Qs as RenderPipeline,Hs as RenderStage,Ko as RenderTexture,Vs as Renderer,st as Res,it as ResMut,Ke as RigidBody,re as RuntimeConfig,go as SafeArea,ze as ScaleMode,si as SceneManager,ni as SceneManagerState,Ge as SceneOwner,jt as Schedule,so as ScrollView,vn as ShaderSources,lo as Slider,ao as SliderDirection,ho as SliderPlugin,Ne as SpineAnimation,De as Sprite,In as SpriteAnimator,Jt as SystemRunner,Ki as Text,Vi as TextAlign,Br as TextInput,$r as TextInputPlugin,qi as TextOverflow,Zi as TextPlugin,Ji as TextRenderer,Gi as TextVerticalAlign,at as Time,Nr as Toggle,Ue as Transform,_a as Tween,ua as TweenHandle,ca as TweenState,la as TweenTarget,nn as UICameraInfo,wr as UIEventQueue,xr as UIEvents,yr as UIInteraction,kr as UIInteractionPlugin,vr as UILayoutPlugin,sr as UIMask,fr as UIMaskPlugin,Pi as UIRect,Ro as UIRenderOrderPlugin,He as Velocity,Ea as WeChatAssetProvider,Vo as WebAssetProvider,xt as World,$e as WorldTransform,qt as addStartupSystem,Gt as addSystem,Kt as addSystemToSchedule,xa as animationPlugin,le as applyBuildRuntimeConfig,Ii as applyDirectionalFill,oe as applyRuntimeConfig,Qn as assetPlugin,An as clearAnimClips,Ts as clearDrawCallbacks,Me as clearUserComponents,ye as color,Ci as computeFillAnchors,Ai as computeFillSize,Ri as computeHandleAnchors,Si as computeUIRectLayout,hr as createMaskProcessor,No as createRuntimeSceneConfig,Ta as createWebApp,sa as debug,be as defineComponent,Ut as defineEvent,nt as defineResource,Nt as defineSystem,Se as defineTag,oa as error,Pn as extractAnimClipTexturePaths,Gn as findEntityByName,li as flushPendingSystems,S as getAddressableType,P as getAddressableTypeByEditorType,T as getAllAssetExtensions,Rn as getAnimClip,A as getAssetMimeType,v as getAssetTypeEntry,Ie as getComponent,Un as getComponentAssetFieldDescriptors,zn as getComponentAssetFields,qe as getComponentDefaults,On as getComponentEntityFields,Wn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,ta as getLogger,t as getPlatform,s as getPlatformType,Pe as getUserComponent,R as getWeChatPackOptions,ia as info,gs as initDrawAPI,qs as initGLDebugAPI,ks as initGeometryAPI,dn as initMaterialAPI,Sa as initPlayableRuntime,Ws as initPostProcessAPI,Ys as initRendererAPI,pa as initTweenAPI,Aa as initWeChatRuntime,tn as inputPlugin,ts as instantiatePrefab,ir as intersectRects,rr as invertMatrix4,Ce as isBuiltinComponent,I as isCustomExtension,Tr as isEditor,M as isKnownAssetExtension,n as isPlatformInitialized,Rr as isPlayMode,Er as isRuntime,rn as isTextureRef,i as isWeChat,r as isWeb,Nn as loadComponent,ko as loadPhysicsModule,Yo as loadRuntimeScene,jn as loadSceneData,Xn as loadSceneWithAssets,E as looksLikeAssetPath,Mn as parseAnimClipData,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,dr as pointInOBB,ar as pointInWorldRect,cs as prefabsPlugin,Zr as progressBarPlugin,me as quat,En as registerAnimClip,Ae as registerComponent,Bn as registerComponentAssetFields,Dn as registerComponentEntityFields,Ps as registerDrawCallback,es as registerEmbeddedAssets,xn as registerMaterialCallback,Ln as remapEntityFields,oi as sceneManagerPlugin,or as screenToWorld,Mr as setEditorMode,xo as setListViewRenderer,na as setLogLevel,Cr as setPlayMode,ht as setWasmErrorHandler,ys as shutdownDrawAPI,Ks as shutdownGLDebugAPI,Fs as shutdownGeometryAPI,un as shutdownMaterialAPI,$s as shutdownPostProcessAPI,Ns as shutdownRendererAPI,ga as shutdownTweenAPI,fo as sliderPlugin,kn as spriteAnimatorSystemUpdate,Di as syncFillSpriteSize,Dr as textInputPlugin,er as textPlugin,k as toBuildPath,Io as transitionTo,Fr as uiInteractionPlugin,br as uiLayoutPlugin,pr as uiMaskPlugin,Pa as uiPlugins,Ao as uiRenderOrderPlugin,Cn as unregisterAnimClip,Te as unregisterComponent,Ms as unregisterDrawCallback,Vn as updateCameraAspectRatio,fe as vec2,pe as vec3,ge as vec4,ra as warn,ii as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,H as wxGetImagePixels,L as wxLoadImage,j as wxLoadImagePixels,U as wxReadFile,W as wxReadTextFile,O 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 i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(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(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function p(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"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 m(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}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function P(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function M(e){return w.has(e.toLowerCase())}function T(){return w}function E(e){return"string"==typeof e&&(!!e.includes("/")&&M(x(e)))}function C(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return y[e.toLowerCase()]}function I(e){const t=v(e);return t?.wechatPackInclude??!1}function k(e){const t=v(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}let F=null;function B(){return F||(F=wx.getFileSystemManager()),F}function z(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(I(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return n.includes("no such file")||n.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function U(e){return new Promise((t,n)=>{B().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(z(e,t.errMsg)))}})})}function W(e,t="utf-8"){return new Promise((n,s)=>{B().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(z(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{B().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=B();try{return t.accessSync(e),!0}catch{return!1}}function O(e,t){return new Promise((n,s)=>{B().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function L(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 H(e){const{width:t,height:n}=e,{ctx:s}=function(e,t){const n=wx.createCanvas();n.width=e,n.height=t;const s=n.getContext("2d");return{canvas:n,ctx:s}}(t,n);s.clearRect(0,0,t,n),s.drawImage(e,0,0);const i=s.getImageData(0,0,t,n);return{width:t,height:n,pixels:new Uint8Array(i.data.buffer)}}async function j(e){return H(await L(e))}let X=!1;const Y=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return p(e,t)}async readFile(e){return function(e){return B().readFileSync(e)}(k(e))}async readTextFile(e){return function(e,t="utf-8"){return B().readFileSync(e,t)}(k(e))}async fileExists(e){return D(k(e))}async loadImagePixels(e){return j(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(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){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const r=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},o=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(r),wx.onTouchMove(o),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(r),wx.offTouchMove(o),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},N=1920,V=1080,G=100,q=512,K={x:100,y:100},J="Arial",Q=24,Z=1.2,ee=.5,te=1/60,ne={x:0,y:-9.81},se=1/60,ie="default",re={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function oe(e){e.Text&&(e.Text._default.fontFamily=re.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=re.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=re.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=re.canvasMatchWidthOrHeight)}const ae={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function le(e,t){if(void 0!==t.maxDeltaTime&&(re.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(re.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(re.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(re.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(re.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");re.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(re.canvasScaleMode=ae[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(re.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const ce=0,ue=4294967295,he=4294967295,de=0,fe=(e=0,t=0)=>({x:e,y:t}),pe=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),me=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ge=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),ye=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function _e(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(_e);const t={};for(const n in e)t[n]=_e(e[n]);return t}let we=0;function xe(e,t){const n=++we,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{..._e(t),...e}:_e(t):e?{...t,...e}:{...t}}}function ve(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function be(e,t){const n=Re.get(e)??ve().get(e);if(n)return n;const s=xe(e,t);return ve().set(e,s),Re.set(e,s),Ee(e,t,!1),s}function Se(e){const t=Re.get(e)??ve().get(e);if(t)return t;const n=xe(e,{});return ve().set(e,n),Re.set(e,n),Ee(e,{},!0),n}function Pe(e){return ve().get(e)}function Me(){const e=ve();for(const t of e.keys())Re.delete(t);e.clear()}function Te(e){ve().delete(e),Re.delete(e)}function Ee(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function Ce(e){return!0===e._builtin}const Re=new Map;function Ae(e,t){Re.set(e,t)}function Ie(e){return Re.get(e)??Pe(e)}function ke(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Re.set(e,n),n}const Fe={Perspective:0,Orthographic:1},Be={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ze={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Ue=ke("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),We=Ue,$e=Ue,De=ke("Sprite",{texture:ue,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,enabled:!0}),Oe=ke("Camera",{projectionType:Fe.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Be.ColorAndDepth}),Le=ke("Canvas",{designResolution:{x:N,y:V},pixelsPerUnit:100,scaleMode:ze.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),He=ke("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),je=ke("Parent",{entity:0}),Xe=ke("Children",{entities:[]}),Ye=ke("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:he,enabled:!0}),Ne=ke("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,enabled:!0}),Ve=be("Name",{value:""}),Ge=be("SceneOwner",{scene:"",persistent:!1});function qe(e){const t=Ie(e);return t?_e(t._default):null}const Ke=ke("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Je=ke("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Qe=ke("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ze=ke("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),et={Static:0,Kinematic:1,Dynamic:2};let tt=0;function nt(e,t){const n=++tt;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function st(e){return{_type:"res",_resource:e}}function it(e){return{_type:"res_mut",_resource:e}}class rt{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_)}updateValue(e){this.value_=e}}class ot{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new rt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const at=nt({delta:0,elapsed:0,frameCount:0},"Time");function lt(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=ct(t[e]),r=ct(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ct(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ut(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let ht=null;function dt(e){ht=e}function ft(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ht&&ht(e,t)}function pt(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[t]="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}:s}}return n}let mt=1;const gt=new WeakMap;function yt(e){let t=gt.get(e);return void 0===t&&(t=mt++,gt.set(e,t)),t}const _t=[];function wt(e,t=[],n=[]){_t.length=0;for(const t of e)_t.push(yt(t));_t.sort((e,t)=>e-t);let s=_t.join(",");if(t.length>0){_t.length=0;for(const e of t)_t.push(yt(e));_t.sort((e,t)=>e-t),s+="|+"+_t.join(",")}if(n.length>0){_t.length=0;for(const e of n)_t.push(yt(e));_t.sort((e,t)=>e-t),s+="|-"+_t.join(",")}return s}class xt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw ft(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){ft(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){ft(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ft(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Ce(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(Ce(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,pt(n))}catch(n){ft(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return Ce(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Ce(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Ce(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ft(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");Ce(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),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 e=lt(t._name,t._default,s);if(e.length>0)throw new Error(ut(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,pt(i))}catch(n){ft(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return ft(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return ft(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ft(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=lt(t._name,t._default,e);if(i.length>0)throw new Error(ut(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Re)if(Ce(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=ve();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??wt(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!Ce(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function vt(e){return{_type:"mut",_component:e}}function bt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function St(e){return{_filterType:"added",_component:e}}function Pt(e){return{_filterType:"changed",_component:e}}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Tt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Et(e){return bt(e)||Mt(e)||Tt(e)?e._component:e}function Ct(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{bt(e)&&s.push(t),Mt(e)?i.push({index:t,component:e._component}):Tt(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Ct(e,[...t,...s],n),without:(...s)=>Ct(e,t,[...n,...s])}}function Rt(...e){return Ct(e)}class At{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Et),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=wt(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of n)if(!r||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=u;for(let e=0;e<s;e++)o[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=u}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,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(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function It(e){return{_type:"removed",_component:e}}class kt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function Ft(){return{_type:"commands"}}class Bt{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=Ce(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 zt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Bt(this,null);return this.spawned_.push(e),e}entity(e){return new Bt(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Ut(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Wt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class $t{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Wt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Wt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Dt(e){return{_type:"event_writer",_event:e}}function Ot(e){return{_type:"event_reader",_event:e}}class Lt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ht{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var jt;function Xt(){return{_type:"get_world"}}!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"}(jt||(jt={}));let Yt=0;function Nt(e,t,n){const s=++Yt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Vt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Gt(e){Vt().push({schedule:jt.Update,system:e})}function qt(e){Vt().push({schedule:jt.Startup,system:e})}function Kt(e,t){Vt().push({schedule:e,system:t})}class Jt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof zt&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new At(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new zt(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Lt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ht(n)}case"removed":{const t=e;return new kt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Qt{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 Zt=nt(new Qt,"Input");class en{constructor(e){this.target_=e??null}build(e){const n=new Qt;e.insertResource(Zt,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(jt.Last,Nt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const tn=new en,nn=nt({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var sn;function rn(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"}(sn||(sn={}));let on=null,an=null,ln=1;const cn=new Map;function un(e){on=e,an=e.getResourceManager(),xn()}function hn(){0!==mn&&on&&(on._free(mn),mn=0),cn.clear(),ln=1,pn=!1,yn.clear(),_n=null,an=null,on=null}function dn(){if(!an)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return an}const fn={createShader:(e,t)=>dn().createShader(e,t),releaseShader(e){e>0&&dn().releaseShader(e)},create(e){const t=ln++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??sn.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(e.uniforms)for(const[t,s]of Object.entries(e.uniforms))n.uniforms.set(t,s);return cn.set(t,n),t},get:e=>cn.get(e),setUniform(e,t,n){const s=cn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,on?.invalidateMaterialCache(e))},getUniform(e,t){const n=cn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=cn.get(e);n&&(n.blendMode=t,on?.invalidateMaterialCache(e))},getBlendMode(e){const t=cn.get(e);return t?.blendMode??sn.Normal},setDepthTest(e,t){const n=cn.get(e);n&&(n.depthTest=t,on?.invalidateMaterialCache(e))},getShader(e){const t=cn.get(e);return t?.shader??0},release(e){cn.delete(e),on?.invalidateMaterialCache(e)},isValid:e=>cn.has(e),releaseAll(){cn.clear(),on?.clearMaterialCache()},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??sn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=cn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=ln++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return cn.set(n,s),n},toAssetData(e,t){const n=cn.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=cn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let pn=!1,mn=0;const gn=16384,yn=new Map;let _n=null;function wn(e){const t=(0===mn&&on&&(mn=on._malloc(gn)),mn);if(0===t||!on)return{ptr:0,count:0};let n=0,s=0;const i=on.HEAPU8,r=on.HEAPU32,o=on.HEAPF32;for(const[a,l]of e){if(rn(l))continue;let e=yn.get(a);e||(_n||(_n=new TextEncoder),e=_n.encode(a),yn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>gn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${gn} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.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]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function xn(){if(!on||pn)return;on.materialDataProvider=(e,t,n,s,i)=>{const r=cn.get(e);if(!r)return on.HEAPU32[t>>2]=0,on.HEAPU32[n>>2]=0,on.HEAPU32[s>>2]=0,void(on.HEAPU32[i>>2]=0);on.HEAPU32[t>>2]=r.shader,on.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=wn(r.uniforms);on.HEAPU32[s>>2]=o,on.HEAPU32[i>>2]=a},pn=!0}const vn={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 bn{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Sn{constructor(e,t=""){this.cache_=new bn,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(fn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())fn.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 i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:fn.createFromAsset(s,r),shaderHandle:r,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 Pn(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Mn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:n.get(e.texture)??0}))}}const Tn=new Map;function En(e){Tn.set(e.name,e)}function Cn(e){Tn.delete(e)}function Rn(e){return Tn.get(e)}function An(){Tn.clear()}const In=be("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function kn(e,t){const n=e.getEntitiesWithComponents([In]);for(const s of n){const n=e.get(s,In);if(!n.enabled||!n.playing||!n.clip)continue;const i=Tn.get(n.clip);if(!i||0===i.frames.length)continue;const r=1/(i.fps*n.speed),o=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=o;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,De)){const t=i.frames[n.currentFrame],r=e.get(s,De);r.texture=t.texture,e.insert(s,De,r)}a&&e.insert(s,In,n)}}class Fn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const n=this.bufferCache_.get(e);return n?this.backend_.play(n,{bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0}):(this.preload(e).then(()=>{const n=this.bufferCache_.get(e);n&&this.backend_.play(n,{bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0})}),this.createPendingHandle())}static playBGM(e,t){const n=e=>{this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade):this.bgmHandle_&&this.bgmHandle_.stop(),this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:t?.fadeIn?0:t?.volume??1,loop:!0}),t?.fadeIn&&this.fadeIn(this.bgmHandle_,t.fadeIn,t?.volume??1)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&n(t)})}static stopBGM(e){this.bgmHandle_&&(e&&e>0?this.fadeOut(this.bgmHandle_,e):this.bgmHandle_.stop(),this.bgmHandle_=null)}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const r=(performance.now()-s)/1e3,o=Math.min(r/t,1);e.setVolume(o*n),o<1&&e.isPlaying&&requestAnimationFrame(i)};requestAnimationFrame(i)}static fadeOut(e,t){const n=performance.now(),s=()=>{const i=(performance.now()-n)/1e3,r=Math.min(i/t,1);e.setVolume(1-r),r<1&&e.isPlaying?requestAnimationFrame(s):e.stop()};requestAnimationFrame(s)}static createPendingHandle(){return{id:-1,stop(){},pause(){},resume(){},setVolume(){},setPan(){},setLoop(){},setPlaybackRate(){},isPlaying:!1,currentTime:0,duration:0}}}Fn.mixer_=null,Fn.bufferCache_=new Map,Fn.bgmHandle_=null;const Bn=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function zn(e,t){Bn.set(e,t)}function Un(e){const t=Bn.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function Wn(e){return Bn.get(e)?.fields??[]}function $n(e){return Bn.get(e)?.spine??null}const Dn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function On(e,t){Dn.set(e,t)}function Ln(e){return Dn.get(e)}function Hn(e,t){const n=Dn.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function jn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Ve,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Hn(i,n),Vn(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function Xn(e,t){return jn(e,t)}async function Yn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,r=new Map;s&&await async function(e,t,n,s,i){const r=new Map;for(const e of Nn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Bn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...Nn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),u=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Bn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,r,n?.collectAssets);const o=jn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const Nn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),r=Pn(i),o=new Map,a=r.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),o.set(e,0)}});await Promise.all(a);En(Mn(e,i,o))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Fn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Vn(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=Ie(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Gn(e,t){const n=e.getEntitiesWithComponents([Oe]);for(const s of n){const n=e.get(s,Oe);n&&(n.aspectRatio=t,e.insert(s,Oe,n))}}function qn(e,t){const n=e.getEntitiesWithComponents([Ve]);for(const s of n){const n=e.get(s,Ve);if(n&&n.value===t)return s}return null}class Kn{constructor(e){this.textureCache_=new bn,this.shaderCache_=new bn,this.jsonCache_=new bn,this.textCache_=new bn,this.binaryCache_=new bn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new bn,this.prefabCache_=new bn,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(re.textCanvasSize,re.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Sn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),fn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===v(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,r,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=v(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of Un(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=$n(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 Yn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;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 i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.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.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return fn.createShader(s,i)}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:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return fn.createShader(i,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(k(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(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 o(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.getEmbedded(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 o(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.getEmbedded(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 o(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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 Jn=nt(null,"Assets");class Qn{build(e){const t=e.wasmModule;t?e.insertResource(Jn,new Kn(t)):console.warn("AssetPlugin: No WASM module available")}}const Zn=new Qn;class es{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function ts(e,t){const n=e.getResource(Jn);n&&n.registerEmbeddedAssets(t)}async function ns(e,t,n){const{entities:s,rootId:i}=await is(t,n?.overrides??[],n,void 0,new Set),r={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,visible:e.visible}))},o=await Yn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const ss=10;async function is(e,t,n,s,i,r=0){if(r>ss)throw new Error(`Prefab nesting depth exceeded ${ss}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await is(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};rs(h.components,o),os(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function rs(e,t){for(const n of e){const e=Ln(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function os(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 as{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return ns(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ls=nt(null,"Prefabs");class cs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Jn]}build(e){const t=e.getResource(Jn);e.insertResource(ls,new as(e.world,t))}}const us=new cs;let hs=null,ds=0,fs=0,ps=0;const ms=new Float32Array(256);function gs(e){hs=e,ds=hs._malloc(64),fs=hs._malloc(64),ps=hs._malloc(1024)}function ys(){hs&&(ds&&(hs._free(ds),ds=0),fs&&(hs._free(fs),fs=0),ps&&(hs._free(ps),ps=0)),hs=null}function _s(){if(!hs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return hs}const ws={r:1,g:1,b:1,a:1},xs={begin(e){const t=_s();try{t.HEAPF32.set(e,ds/4),t.draw_begin(ds)}catch(e){ft(e,"Draw.begin")}},end(){try{_s().draw_end()}catch(e){ft(e,"Draw.end")}},line(e,t,n,s=1){try{_s().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ft(e,"Draw.line")}},rect(e,t,n,s=!0){try{_s().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ft(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{_s().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ft(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{_s().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ft(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{_s().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ft(e,"Draw.circleOutline")}},texture(e,t,n,s=ws){try{_s().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ft(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ws){try{_s().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ft(e,"Draw.textureRotated")}},setLayer(e){_s().draw_setLayer(e)},setDepth(e){_s().draw_setDepth(e)},getDrawCallCount:()=>hs?hs.draw_getDrawCallCount():0,getPrimitiveCount:()=>hs?hs.draw_getPrimitiveCount():0,setBlendMode(e){_s().draw_setBlendMode(e)},setDepthTest(e){_s().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=_s();s.HEAPF32.set(n,fs/4),s.draw_mesh(e,t,fs)}catch(n){ft(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=_s(),i=fn.get(t);if(!i)return;if(xs.setBlendMode(i.blendMode),xs.setDepthTest(i.depthTest),0===i.uniforms.size)return void xs.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,fs/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Ss(t);if(!(s<0)){if(rn(n))ms[r++]=10,ms[r++]=s,ms[r++]=n.slot??e++,ms[r++]=n.textureId;else if("number"==typeof n)ms[r++]=1,ms[r++]=s,ms[r++]=n;else if(Array.isArray(n)){ms[r++]=n.length,ms[r++]=s;for(let e=0;e<n.length;e++)ms[r++]=n[e]}else"w"in n?(ms[r++]=4,ms[r++]=s,ms[r++]=n.x,ms[r++]=n.y,ms[r++]=n.z,ms[r++]=n.w):"z"in n?(ms[r++]=3,ms[r++]=s,ms[r++]=n.x,ms[r++]=n.y,ms[r++]=n.z):(ms[r++]=2,ms[r++]=s,ms[r++]=n.x,ms[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(ms.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,fs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),ps/4),s.draw_meshWithUniforms(e,i.shader,fs,ps,r)}catch(n){ft(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},vs={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},bs=new Set;function Ss(e){const t=vs[e];return void 0!==t?t:(bs.has(e)||(bs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(vs).join(", ")}`)),-1)}const Ps=new Map;function Ms(e,t,n){Ps.set(e,{fn:t,scene:n??""})}function Ts(e){Ps.delete(e)}function Es(){Ps.clear()}var Cs;!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"}(Cs||(Cs={}));let Rs=null,As=0,Is=0,ks=0;function Fs(e){Rs=e,As=Rs._malloc(262144),Is=Rs._malloc(65536),ks=Rs._malloc(256)}function Bs(){Rs&&(As&&Rs._free(As),Is&&Rs._free(Is),ks&&Rs._free(ks),As=0,Is=0,ks=0),Rs=null}function zs(){if(!Rs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Rs}const Us={create(e){const t=zs(),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,As/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ks,i).set(r),t.geometry_init(n,As,s,ks,i,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,Is,s).set(e.indices),t.geometry_setIndices16(n,Is,s)}else{new Uint32Array(t.HEAPU8.buffer,Is,s).set(e.indices),t.geometry_setIndices32(n,Is,s)}}return n},updateVertices(e,t,n=0){const s=zs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,As/4),s.geometry_updateVertices(e,As,i,n)},release(e){e>0&&zs().geometry_release(e)},isValid:e=>!(!Rs||e<=0)&&Rs.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Us.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:Cs.Float2},{name:"a_texCoord",type:Cs.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 i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Us.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:Cs.Float2},{name:"a_texCoord",type:Cs.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,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Us.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:Cs.Float2},{name:"a_texCoord",type:Cs.Float2}],indices:new Uint16Array(o)})}};let Ws=null;function $s(e){Ws=e}function Ds(){Ws&&Ls.isInitialized()&&Ls.shutdown(),Ws=null}function Os(){if(!Ws)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ws}const Ls={init(e,t){try{return Os().postprocess_init(e,t)}catch(n){return ft(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Os().postprocess_shutdown()}catch(e){ft(e,"PostProcess.shutdown")}},resize(e,t){try{Os().postprocess_resize(e,t)}catch(n){ft(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Os().postprocess_addPass(e,t)}catch(t){return ft(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Os().postprocess_removePass(e)}catch(t){ft(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Os().postprocess_setPassEnabled(e,t)}catch(t){ft(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Os().postprocess_isPassEnabled(e)}catch(t){return ft(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Os().postprocess_setUniformFloat(e,t,n)}catch(n){ft(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Os().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ft(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Os().postprocess_begin()}catch(e){ft(e,"PostProcess.begin")}},end(){try{Os().postprocess_end()}catch(e){ft(e,"PostProcess.end")}},getPassCount(){try{return Os().postprocess_getPassCount()}catch(e){return ft(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ws)return!1;try{return Ws.postprocess_isInitialized()}catch(e){return ft(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Os().postprocess_setBypass(e)}catch(e){ft(e,"PostProcess.setBypass")}},isBypassed(){if(!Ws)return!0;try{return Ws.postprocess_isBypassed()}catch(e){return ft(e,"PostProcess.isBypassed"),!0}},createBlur:()=>fn.createShader(Hs,"#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:()=>fn.createShader(Hs,"#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:()=>fn.createShader(Hs,"#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:()=>fn.createShader(Hs,"#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")},Hs="#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 js;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(js||(js={}));let Xs=null,Ys=0;function Ns(e){Xs=e,Ys=Xs._malloc(64)}function Vs(){Xs&&Ys&&(Xs._free(Ys),Ys=0),Xs=null}const Gs={init(e,t){Xs?.renderer_init(e,t)},resize(e,t){Xs?.renderer_resize(e,t)},begin(e,t){if(Xs&&Ys)try{Xs.HEAPF32.set(e,Ys/4),Xs.renderer_begin(Ys,t??0)}catch(e){ft(e,"Renderer.begin")}},flush(){try{Xs?.renderer_flush()}catch(e){ft(e,"Renderer.flush")}},end(){try{Xs?.renderer_end()}catch(e){ft(e,"Renderer.end")}},submitSprites(e){if(Xs)try{Xs.renderer_submitSprites(e._cpp)}catch(e){ft(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Xs)try{Xs.renderer_submitBitmapText(e._cpp)}catch(e){ft(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Xs)try{Xs.renderer_submitSpine?.(e._cpp)}catch(e){ft(e,"Renderer.submitSpine")}},setStage(e){Xs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Xs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Xs?.renderer_releaseTarget(e)},getTargetTexture:e=>Xs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Xs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Xs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Xs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Xs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Xs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Xs?Xs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Xs?{drawCalls:Xs.renderer_getDrawCalls(),triangles:Xs.renderer_getTriangles(),sprites:Xs.renderer_getSprites(),text:Xs.renderer_getText(),spine:Xs.renderer_getSpine?.()??0,meshes:Xs.renderer_getMeshes(),culled:Xs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let qs=null;function Ks(e){qs=e}function Js(){qs=null}const Qs={enable(){qs?.gl_enableErrorCheck(!0)},disable(){qs?.gl_enableErrorCheck(!1)},check:e=>qs?.gl_checkErrors(e)??0,diagnose(){qs?.renderer_diagnose()}};class Zs{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Gs.resize(s,i),Ls.isInitialized()&&Ls.getPassCount()>0&&Ls.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Gs.setViewport(0,0,s,i),Gs.clearBuffers(3),Gs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Gs.submitSprites(t),Gs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Gs.submitSpine(t),Gs.flush(),this.executeDrawCallbacks(n,r),Gs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Gs.setViewport(s.x,s.y,s.w,s.h),Gs.setScissor(s.x,s.y,s.w,s.h,!0),Gs.clearBuffers(i),Gs.setScissor(0,0,0,0,!1),Gs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Gs.submitSprites(t),Gs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Gs.submitSpine(t),Gs.flush(),this.executeDrawCallbacks(n,r),Gs.end()}executeDrawCallbacks(e,t){const n=Ps;if(n.size>0){xs.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}xs.end();for(const e of s)Ts(e)}}}const ei="__scene_transition_overlay__";class ti{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ni{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Ge,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ms(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Ls.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Ls.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Ge)){const n=this.app_.world.get(e,Ge);n.persistent=t,this.app_.world.insert(e,Ge,n)}}}class si{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??re.sceneTransitionDuration,i=t.color??{...re.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Ms(ei,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;xs.setLayer(9999),xs.setDepth(9999),xs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,Ts(ei),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ts(ei),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ti(t);this.scenes_.set(e,n);const s=new ni(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Jn)?this.app_.getResource(Jn):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new ti(t);this.scenes_.set(e,n);const s=new ni(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Jn)?this.app_.getResource(Jn):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Ge)){if(this.app_.world.get(e,Ge).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Ts(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Ls.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Jn)&&(i.assetServer=this.app_.getResource(Jn));const r=await Yn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,Ge,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=ri(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Jn)?this.app_.getResource(Jn):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)fn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,De)){const t=n.get(e,De);s.sprite=t.color.a,t.color.a=0,n.insert(e,De,t),i=!0}if(n.has(e,Ne)){const t=n.get(e,Ne);s.spine=t.color.a,t.color.a=0,n.insert(e,Ne,t),i=!0}if(n.has(e,Ye)){const t=n.get(e,Ye);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Ye,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,De)){const t=n.get(e,De);t.color.a=s.sprite,n.insert(e,De,t)}if(void 0!==s.spine&&n.has(e,Ne)){const t=n.get(e,Ne);t.color.a=s.spine,n.insert(e,Ne,t)}if(void 0!==s.bitmapText&&n.has(e,Ye)){const t=n.get(e,Ye);t.color.a=s.bitmapText,n.insert(e,Ye,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Ls.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const ii=nt(null,"SceneManager");function ri(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ii).getSceneStatus(t)&&n._fn(...s)}}}const oi=Nt([it(ii),st(at)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ai={name:"SceneManager",build(e){const t=new si(e);e.insertResource(ii,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ii),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(jt.Startup,n),e.addSystemToSchedule(jt.Last,oi)}};class li{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new $t,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(jt.Last);else{this.runSchedule(jt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(jt.FixedPreUpdate),this.runSchedule(jt.FixedUpdate),this.runSchedule(jt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(jt.PreUpdate),this.runSchedule(jt.Update),this.runSchedule(jt.PostUpdate),this.runSchedule(jt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new xt,this.resources_=new ot;for(const e of Object.values(jt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new li}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(jt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(jt.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return dt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ii).register(e),this}setInitialScene(e){return this.getResource(ii).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Jt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(at)||this.resources_.insert(at,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(jt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(jt.Last);else{this.runSchedule(jt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(jt.FixedPreUpdate),this.runSchedule(jt.FixedUpdate),this.runSchedule(jt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(jt.PreUpdate),this.runSchedule(jt.Update),this.runSchedule(jt.PostUpdate),this.runSchedule(jt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Jt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(at,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(jt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Es();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Js,Vs,Ds,Bs,hn,ys];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(at);t.delta=e,t.elapsed+=e,t.frameCount++}}function ci(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const ui=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function hi(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case ze.FixedWidth:return r;case ze.FixedHeight:return o;case ze.Expand:return Math.max(r,o);case ze.Shrink:return Math.min(r,o);case ze.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const di=[];function fi(e){if(e<di.length)return di[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return di.push(t),t}function pi(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,Ge);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===Fe.Orthographic){if(h=i.orthoSize,l){h=hi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}u=h*o,a=gi(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=_i(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const d=xi(r.position.x,r.position.y,r.position.z),f=fi(c.length);f.entity=e,f.viewProjection.set(bi(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const mi=new Float32Array(16);function gi(e,t,n,s,i,r){const o=mi;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const yi=new Float32Array(16);function _i(e,t,n,s){const i=yi;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const wi=new Float32Array(16);function xi(e,t,n){const s=wi;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}const vi=new Float32Array(16);function bi(e,t){const n=vi;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const Si={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Pi(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,u=r.left+t.x*a,h=r.bottom+e.y*l,d=r.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*o.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,g=p+i.y):(p=h+n.y,g=d+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+o.x*y,originY:p+o.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Mi=ke("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}});let Ti=null,Ei=null;function Ci(e,t){e.has(t,De)||e.insert(t,De,{texture:ue,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})}function Ri(e,t){switch(e){case Si.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Si.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Si.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Ai(e,t){switch(e){case Si.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Si.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Si.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function Ii(e,t,n,s){switch(e){case Si.BottomToTop:case Si.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function ki(e,t,n,s){if(!e.has(t,Mi))return;const i=e.get(t,Mi),r=Ri(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Mi,i)}function Fi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Bi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function zi(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(Bi(o.charCodeAt(0))&&s.length>0&&Bi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Bi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Ui(e){let t=1;for(;t<e;)t*=2;return t}function Wi(e,t){let n=0,s=t;for(;e.has(s,je);){const t=e.get(s,je).entity;if(!e.valid(t))break;n++,s=t}return n}function $i(e,t){if(Ti&&Ei){const e=Ti.getUIRectComputedWidth(Ei,t);if(e>0)return e}return e.size.x}function Di(e,t){if(Ti&&Ei){const e=Ti.getUIRectComputedHeight(Ei,t);if(e>0)return e}return e.size.y}function Oi(e,t,n,s,i,r){if(!e.has(t,De))return;const o=e.get(t,De);let a,l;switch(n){case Si.BottomToTop:case Si.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,De,o))}function Li(e,t,n){let s=t;for(;e.has(s,je);){const t=e.get(s,je).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Hi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function ji(e,t,n,s,i){if(!e.has(t,Mi))return;const r=e.get(t,Mi),o=Pi(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,De)){const n=e.get(t,De);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,De,n))}if(e.has(t,Ue)){const n=e.get(t,Ue);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,Ue,n)}}function Xi(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Yi=.1,Ni=30,Vi={r:.3,g:.5,b:.8,a:1},Gi={Left:0,Center:1,Right:2},qi={Top:0,Middle:1,Bottom:2},Ki={Visible:0,Clip:1,Ellipsis:2},Ji=be("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Gi.Left,verticalAlign:qi.Top,wordWrap:!0,overflow:Ki.Visible,lineHeight:1.2});class Qi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(re.textCanvasSize,re.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ui(this.frameMaxW_)),e.height=Math.max(e.height,Ui(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ui(this.frameMaxW_),e.height=Ui(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=zi(n,e.content,a?r: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=i?Math.ceil(r):h+2*u,p=i?Math.ceil(o):d+2*u;if(i&&e.overflow===Ki.Ellipsis&&d>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Ui(f)),s.height=Math.max(s.height,Ui(p)));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}, ${_})`,i&&e.overflow===Ki.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case qi.Top:x=u;break;case qi.Middle:x=u+(p-2*u-w)/2;break;case qi.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let s;switch(e.align){case Gi.Left:s=u;break;case Gi.Center:s=f/2;break;case Gi.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===Ki.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Gi.Left:return"left";case Gi.Center:return"center";case Gi.Right:return"right"}}}const Zi=Xi({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?$i(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0});class er{build(e){Ae("Text",Ji);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Qi(t),s=e.world,i=new Map;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ji));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Ji)){if(s.valid(e)&&s.has(e,De)){const t=s.get(e,De);s.insert(e,De,{texture:ue,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=s.getEntitiesWithComponents([Ji]);for(const t of e){const e=s.get(t,Ji),r=s.has(t,Mi)?s.get(t,Mi):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Zi.changed(a,o)){if(s.has(t,De)&&s.get(t,De).texture!==ue)continue}Ci(s,t);const l=r?{size:{x:$i(r,t),y:Di(r,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,De);s.insert(t,De,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Zi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const tr=new er,nr=0,sr=1,ir=ke("UIMask",{enabled:!0,mode:nr});function rr(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function or(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=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-i*a,x=s*c-r*a,v=s*u-o*a,b=i*c-r*l,S=i*u-o*l,P=r*u-o*c,M=h*g-d*m,T=h*y-f*m,E=h*_-p*m,C=d*y-f*g,R=d*_-p*g,A=f*_-p*y;let I=w*A-x*R+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(r*R-i*A-o*C)*I,n[2]=(g*P-y*S+_*b)*I,n[3]=(f*S-d*P-p*b)*I,n[4]=(c*E-a*A-u*T)*I,n[5]=(s*A-r*E+o*T)*I,n[6]=(y*v-m*P-_*x)*I,n[7]=(h*P-f*v+p*x)*I,n[8]=(a*R-l*E+u*M)*I,n[9]=(i*E-s*R-o*M)*I,n[10]=(m*S-g*v+_*w)*I,n[11]=(d*v-h*S-p*w)*I,n[12]=(l*T-a*C-c*M)*I,n[13]=(s*C-i*T+r*M)*I,n[14]=(g*x-m*b-y*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function ar(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*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 lr(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function cr(e,t){return 2*Math.atan2(e,t)}function ur(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function hr(e,t,n,s,i,r,o,a,l,c){const u=cr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*o&&m<=n+i*(1-o)&&g>=s-r*a&&g<=s+r*(1-a)}function dr(e,t,n,s,i,r,o){if(!e.has(t,Mi)||!e.has(t,Ue))return null;const a=e.get(t,Mi),l=e.get(t,Ue),c=$i(a,t)*l.worldScale.x,u=Di(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),y=-u*p,_=u*(1-p),w=cr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-y*v,d+m*v+y*x],[h+g*x-y*v,d+g*v+y*x],[h+g*x-_*v,d+g*v+_*x],[h+m*x-_*v,d+m*v+_*x]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=ur(e,t,n,s,i,r,o);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function fr(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ir]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,ir);n.enabled&&(h.add(e),n.mode===sr?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const u=[];for(const e of s){let n=!0;Li(t,e,e=>{if(i.has(e)){if(t.get(e,ir).mode===nr)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(i.has(n)){if(t.get(n,ir).mode===nr){const e=dr(t,n,r,o,a,l,c);e&&(s=rr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=dr(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Li(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class pr{build(e){if(Ae("UIMask",ir),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(fr(e.wasmModule,e.world))}}const mr=new pr,gr=ke("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),yr=ke("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),_r={Normal:0,Hovered:1,Pressed:2,Disabled:3},wr=be("Button",{state:_r.Normal,transition:null});class xr{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}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 vr=nt(new xr,"UIEvents");class br{build(e){Ae("UIRect",Mi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Ti=e,Ei=t}(n,s);e.addSystemToSchedule(jt.PreUpdate,Nt([st(nn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(jt.PostUpdate,Nt([st(nn)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(jt.PostUpdate,Nt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Sr=new br;let Pr=!1,Mr=!1;function Tr(e){Pr=e}function Er(){return Pr}function Cr(){return!Pr}function Rr(e){Mr=e}function Ar(){return Mr}const Ir=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(or(t,e),n=!1),e)}}();function kr(e,t,n,s){t.emit(n,s,n),Li(e,n,i=>{if(!e.has(i,gr))return!1;const r=e.get(i,gr);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class Fr{build(e){Ae("Interactable",gr),Ae("Button",wr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new xr;e.insertResource(vr,i);let r=null,o=null;e.addSystemToSchedule(jt.PreUpdate,Nt([st(Zt),st(nn)],(e,a)=>{if(i.drain(),Er()&&!Ar())return;const l=t.getEntitiesWithComponents([yr]);for(const e of l){const n=t.get(e,yr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,yr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Ir.update(a.viewProjection);const d=ar(u,h,Ir.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,d.x,d.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,yr)){const e=t.get(r,yr);e.hovered=!1,t.insert(r,yr,e),i.emit(r,"hover_exit")}if(null!==_){Hi(t,_,yr);const e=t.get(_,yr);e.hovered=!0,t.insert(_,yr,e),i.emit(_,"hover_enter")}r=_}if(m&&null!==_){const e=t.get(_,yr);e.pressed=!0,e.justPressed=!0,t.insert(_,yr,e),o=_,kr(t,i,_,"press")}if(g&&null!==o){if(t.valid(o)&&t.has(o,yr)){const e=t.get(o,yr);e.pressed=!1,e.justReleased=!0,t.insert(o,yr,e),kr(t,i,o,"release"),o===r&&kr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(jt.Update,Nt([],()=>{const e=t.getEntitiesWithComponents([wr]);for(const n of e){if(Hi(t,n,gr,{enabled:!0}),!t.has(n,yr))continue;const e=t.get(n,yr),s=t.get(n,wr),i=t.get(n,gr),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=_r.Pressed:e.hovered?s.state=_r.Hovered:s.state=_r.Normal:s.state=_r.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,De)){const r=t.get(n,De);r.color=Fi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,De,r)}}},{name:"ButtonSystem"}))}}const Br=new Fr,zr=be("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}),Ur=be("Focusable",{tabIndex:0,isFocused:!1});class Wr{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const $r=nt(new Wr,"FocusManager");class Dr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ae("TextInput",zr),Er()&&!Ar())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(re.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,u=0,d=0;const f=function(){if("undefined"==typeof document||!document.body)return null;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}();if(!f)return;const p=f;function m(){const t=e.getResource($r);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,zr)?s:null}const g=()=>{l||null===m()||v()},y=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,zr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(vr).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const s=n.get(t,zr);s.focused=!1,s.dirty=!0;e.getResource($r).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,zr);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(vr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=n.get(t,zr);e.focused=!1,e.dirty=!0}e.getResource($r).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let P=null;function M(e,l,u,h){(i.width<u||i.height<h)&&(i.width=Ui(Math.max(i.width,u)),i.height=Ui(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,r.fillRect(0,0,u,h),r.save(),r.beginPath(),r.rect(l.padding,0,u-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=zi(r,p,u-2*y);let t=y;for(const n of e)r.fillText(n,y,t),t+=g}else{const e=(h-l.fontSize)/2;r.fillText(p,y,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=zi(r,l.value,u-2*y);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=y+r.measureText(c).width,n=y+o*g,s=g}else t=y+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,u,h),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,De);S.texture=b,S.size.x=u,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,De,S)}e.addSystemToSchedule(jt.Update,Nt([st($r)],e=>{const t=n.getEntitiesWithComponents([zr]);for(const e of t)Hi(n,e,Ur,{tabIndex:0,isFocused:!1}),Hi(n,e,gr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==P){if(null!==P&&n.valid(P)&&n.has(P,zr)){const e=n.get(P,zr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,zr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),P=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const r=m();if(null!==r&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(r,zr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,zr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([zr,Mi]);for(const e of a){const t=n.get(e,zr);if(!t.dirty)continue;const s=n.get(e,Mi),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(Ci(n,e),M(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Or=new Dr,Lr={Simple:0,Sliced:1,Tiled:2,Filled:3},Hr={Horizontal:0,Vertical:1},jr={Left:0,Right:1,Bottom:2,Top:3},Xr=be("Image",{texture:ue,color:{r:1,g:1,b:1,a:1},imageType:Lr.Simple,fillMethod:Hr.Horizontal,fillOrigin:jr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Yr=Xi({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?$i(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Nr=new class{build(e){Ae("Image",Xr);const t=e.world,n=new Map;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Xr)||n.delete(e);const e=t.getEntitiesWithComponents([Xr]);for(const s of e){const e=t.get(s,Xr),i=t.has(s,Mi)?t.get(s,Mi):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Yr.changed(o,r))continue;Ci(t,s);const a=t.get(s,De);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=$i(i,s),a.size.y=Di(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Lr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Hr.Horizontal?e.fillOrigin===jr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===jr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Lr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,De,a),n.set(s,Yr.take(r))}else a.color.a=0,t.insert(s,De,a),n.set(s,Yr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Vr=be("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Gr=be("ToggleGroup",{allowSwitchOff:!1});const qr=new class{build(e){Ae("Toggle",Vr),Ae("ToggleGroup",Gr);const t=e.world,n=new Set;e.addSystemToSchedule(jt.Update,Nt([st(vr)],e=>{const s=t.getEntitiesWithComponents([Vr]);if(!Er()||Ar()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Vr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Vr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,Vr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Hi(t,n,gr,{enabled:!0}),!t.has(n,yr))continue;const s=t.get(n,yr),i=t.get(n,Vr),o=t.get(n,gr);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Gr);if(i.isOn&&o){if(!t.get(s,Gr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Vr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Vr);i.isOn&&(i.isOn=!1,t.insert(s,Vr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,De)){const e=t.get(n,De);e.color=Fi(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,De,e)}}}for(const e of s){const n=t.get(e,Vr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,De)){const e=t.get(n.graphicEntity,De);e.enabled=n.isOn,t.insert(n.graphicEntity,De,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Kr=Si,Jr=be("ProgressBar",{value:0,fillEntity:0,direction:Si.LeftToRight});function Qr(e,t,n,s){if(!e.has(t,Mi))return;const i=e.get(t,Mi),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=Pi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,De)){const n=e.get(t,De);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,De,n))}if(e.has(t,Ue)){const n=e.get(t,Ue),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,Ue,n))}}class Zr{build(e){Ae("ProgressBar",Jr);const t=e.world;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{const e=t.getEntitiesWithComponents([Jr,Mi]);for(const n of e){const e=t.get(n,Jr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Mi),i=Math.max(0,Math.min(1,e.value));ki(t,e.fillEntity,e.direction,i);const r=$i(s,n),o=Di(s,n);Qr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const eo=new Zr,to=be("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),no=be("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const so=new class{build(e){Ae("Draggable",to),Ae("DragState",no);const t=e.world,n=e.getResource(vr);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(jt.PreUpdate,Nt([st(Zt),st(nn)],(e,o)=>{if(Er()&&!Ar())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([to,yr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,to).enabled)continue;if(t.get(s,yr).hovered){let e=0;t.has(s,De)&&(e=t.get(s,De).layer);const i=Wi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,no)||t.insert(n,no);const e=t.get(n,no),r=t.get(n,Ue);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,no)){t.get(s,no).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,to);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=u.dragThreshold){r=s,s=null;t.get(r,no).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,no))return void(r=null);const s=t.get(r,no),i=t.get(r,to),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(r,Ue)){const e=function(e,t,n,s){if(!e.has(t,je))return{x:n,y:s};const i=e.get(t,je).entity;if(!e.valid(i)||!e.has(i,Ue))return{x:n,y:s};const r=e.get(i,Ue),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=cr(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/o,y:(n*c+s*u)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,Ue);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,Ue,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},io=be("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function ro(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function oo(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-r*c)*a}}const ao=new class{build(e){Ae("ScrollView",io);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(jt.PostUpdate,Nt([st(Zt),st(nn),st(at)],(e,i,r)=>{const o=Er()&&!Ar(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([io,Mi]);for(const r of l){Hi(t,r,ir,{enabled:!0,mode:nr});const l=t.get(r,io),c=t.get(r,Mi);let u=n.get(r);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,u));const h=$i(c,r),d=Di(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Xe)){const e=t.get(l.contentEntity,Xe).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,Ue))continue;const e=t.get(o,Ue);let a=0,l=0,c=.5,u=.5;if(t.has(o,Mi)){const e=t.get(o,Mi);a=$i(e,o)||e.size.x,l=Di(e,o)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(o,De)){const e=t.get(o,De);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!o&&i.valid){Hi(t,r,gr,{enabled:!0,blockRaycast:!0});const n=t.has(r,yr)?t.get(r,yr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=ro(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=ro(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ro(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ro(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=oo(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Yi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Yi?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=oo(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Yi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Yi?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Ue)){const e=t.get(l.contentEntity,Ue),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,Ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},lo=Si,co=be("Slider",{value:0,minValue:0,maxValue:1,direction:Si.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function uo(e,t,n,s,i,r){const o=$i(s,i)*n.worldScale.x,a=Di(s,i)*n.worldScale.y,l=cr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*o,g=-s.pivot.y*a;switch(r){case Si.LeftToRight:return o>0?(f-m)/o:0;case Si.RightToLeft:return o>0?1-(f-m)/o:0;case Si.BottomToTop:return a>0?(p-g)/a:0;case Si.TopToBottom:return a>0?1-(p-g)/a:0}}function ho(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Si.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Si.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Si.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Si.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class fo{build(e){Ae("Slider",co);const t=e.world;let n=null;e.addSystemToSchedule(jt.PreUpdate,Nt([st(Zt),st(nn),st(vr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([co,Mi]);for(const o of r){const r=t.get(o,co),a=t.get(o,Mi);if(!Er()||Ar()){if(t.has(o,Ue)){Hi(t,o,gr,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Hi(t,r.handleEntity,gr,{enabled:!0,blockRaycast:!1});const l=t.get(o,Ue),c=t.has(o,yr)?t.get(o,yr):null;let u=c?.justPressed??!1;if(!u&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,yr)&&(u=t.get(r.handleEntity,yr).justPressed),u&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=uo(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,co,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,u=$i(a,o),h=Di(a,o),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(ki(t,r.fillEntity,r.direction,c),ji(t,r.fillEntity,d,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Mi)){const e=t.get(r.handleEntity,Mi);ho(e,r.direction,c),t.insert(r.handleEntity,Mi,e),ji(t,r.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const po=new fo;const mo=new class{build(e){Ae("Focusable",Ur);const t=e.world,n=new Wr;e.insertResource($r,n),e.addSystemToSchedule(jt.Update,Nt([st(Zt),st(vr)],(e,s)=>{if(Er()&&!Ar())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Ur]);for(const e of i){if(!t.has(e,yr))continue;t.get(e,yr).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,gr)){if(!t.get(n,gr).enabled)continue}const s=t.get(n,Ur);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ur)){t.get(i,Ur).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Ur).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},go=be("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function yo(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const _o=new class{build(e){Ae("SafeArea",go);const t=e.world;let n=yo(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=yo(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=yo(),s=!0});e.addSystemToSchedule(jt.PreUpdate,Nt([st(nn)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([go,Mi]);for(const e of u){const s=t.get(e,go),i=t.get(e,Mi),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},u=!0),u&&t.insert(e,Mi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},wo=be("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let xo=null;function vo(e,t){if(!xo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=xo.get(e);n?n.renderer=t:xo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const bo=new class{build(e){Ae("ListView",wo);const t=e.world,n=new Map;xo=n,e.addSystemToSchedule(jt.PostUpdate,Nt([st(Zt)],e=>{const s=Er()&&!Ar();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([wo,Mi]);for(const r of i){Hi(t,r,gr,{enabled:!0,blockRaycast:!0}),Hi(t,r,ir,{enabled:!0,mode:nr});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,wo),a=t.get(r,Mi),l=Di(a,r),c=$i(a,r);if(!s){const n=t.has(r,yr)?t.get(r,yr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const u=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,u));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),d=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ve,{value:`ListItem_${e}`}),t.insert(n,Mi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Ue)){const s=t.get(n,Ue);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Ue,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},So=be("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Po=new class{build(e){Ae("Dropdown",So);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Ue))return;const n=t.get(e,Ue);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Ue,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,De)){const n=t.get(e,De);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,De,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const r=t.get(e,De),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Ni;t.insert(i,Mi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Ue,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,De,{texture:ue,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*Ni;t.insert(r,Ve,{value:`Option_${e}`}),t.insert(r,Mi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Ni},offsetMax:{x:0,y:0},size:{x:o,y:Ni},pivot:{x:.5,y:.5}}),t.insert(r,Ue,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,De,{texture:ue,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Ni},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,gr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,Ue,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Ji,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Gi.Left,verticalAlign:qi.Middle,wordWrap:!1,overflow:Ki.Clip,lineHeight:1.2}),t.insert(c,Mi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Ni},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Ji))return;const s=t.get(n,Ji);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Ji,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,gr)&&t.insert(e,gr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,De))){const s=t.get(e,De);t.insert(e,De,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,De))continue;const i=n===e.highlightIndex?{...Vi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,De,{texture:ue,color:i,size:{x:e.ddWidth,y:Ni},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,yr))continue;if(t.get(n,yr).hovered)return!0}return!1}e.addSystemToSchedule(jt.Update,Nt([st(Zt),st(vr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Er()&&!Ar(),p=t.getEntitiesWithComponents([So]);for(const m of p){const p=t.get(m,So);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Hi(t,m,gr,{enabled:!0,blockRaycast:!0});const y=t.has(m,yr)?t.get(m,yr):null;if(y?.justPressed&&(p.isOpen?o(m,p,g):r(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,yr))continue;if(t.get(n,yr).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,yr))continue;if(t.get(s,yr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&o(m,p,g),e.isMouseButtonPressed(0)&&(y?.hovered||d(g)||o(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Mo=0,To=0,Eo=2,Co=be("LayoutGroup",{direction:Mo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:To,reverseOrder:!1});const Ro=new class{build(e){Ae("LayoutGroup",Co);const t=e.world;e.addSystemToSchedule(jt.PreUpdate,Nt([],()=>{const e=t.getEntitiesWithComponents([Co,Mi,Xe]);for(const n of e){const e=t.get(n,Co),s=t.get(n,Mi),i=t.get(n,Xe);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,Mi)&&t.has(e,Ue)&&r.push({entity:e,rect:t.get(e,Mi)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=$i(s,n),a=Di(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===Mo;let d=0;for(let n=0;n<r.length;n++){const s=r[n],i=$i(s.rect,s.entity),f=Di(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;h?(g=-l*o+u.left+d+p*i,y=e.childAlignment===To?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Eo?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,n<r.length-1&&(d+=e.spacing)):(g=e.childAlignment===To?-l*o+u.left+p*i:e.childAlignment===Eo?(1-l)*o-u.right-(1-p)*i:(.5-l)*o+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-d-(1-m)*f,d+=f,n<r.length-1&&(d+=e.spacing));const _=t.get(s.entity,Ue);_.position.x=g,_.position.y=y,t.insert(s.entity,Ue,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};ke("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),ke("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class Ao{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(jt.PostUpdate,Nt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Io=new Ao;async function ko(e,t,n){const s=e.getResource(ii);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Fo(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const Bo=nt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),zo=nt(null,"PhysicsAPI");function Uo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Wo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class $o{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(Bo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Fo(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([Le]);for(const n of t){const t=e.world.get(n,Le);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(jt.PostUpdate,Nt([st(at)],a=>{const l=o.getEntitiesWithComponents([Ke,Ue]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,Ke),l=o.get(i,Ue);if(t.has(i)){const e=n.get(i);!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(i,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 o=Uo(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Do(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===et.Kinematic){const e=Uo(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,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 i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const u=e.world.get(o,Ue);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(o,je)){const t=e.world.get(o,je);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Ue)){const n=e.world.get(t.entity,Ue),s=Uo(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),u=Math.sin(-s);h=(i*o-r*u)/(0!==n.worldScale.x?n.worldScale.x:1),d=(i*u+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Wo(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(o,Ue,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.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(Bo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(zo,Oo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Do(e,t,n){const s=e.world;if(s.has(n,Je)){const e=s.get(n,Je);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,Qe)){const e=s.get(n,Qe);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,Ze)){const e=s.get(n,Ze);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 Oo{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(Oo.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)}}const Lo={nearest:0,linear:1},Ho={repeat:0,clamp:1,mirror:2};function jo(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Lo[s.filterMode??"linear"]??1,a=Ho[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Xo(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 Yo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.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,v=u*d,b=u*f;return new Float32Array([(1-(y+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*r,(1-(p+w))*r,(_+x)*r,0,(g+v)*o,(_-x)*o,(1-(p+y))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function No(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Wn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=jo(e,await n.loadPixels(r),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${r}`,e),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 i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let u={},h=null;if(i&&(h=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"])}}(i),u=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=$n(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===v(c)?.contentType;let h,d;if(o){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),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,o);if(t._free(h),f<0)continue;r[a]=f;const p=Xo(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=jo(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...ne},fixedTimestep:o?.fixedTimestep??se,subStepCount:o?.subStepCount??4};new $o("",t,()=>Promise.resolve(r)).build(e)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Wn(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=v(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=jo(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Wn(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=fn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=fn.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Wn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(n,c,d,f);const p=Xn(e.world,n);if(l&&e.hasResource(ii))for(const t of p.values())e.world.insert(t,Ge,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=$n(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,u,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=te);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,Ne)?c.get(r,Ne):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(o,l*h);let d=0;if(c.has(r,Ue)){const e=Yo(c.get(r,Ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(y),t.renderer_submitTriangles(_,i,w,r,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,i,h,s)}if(a){const t=e.getResource(Jn);t&&t.setAddressableManifest(a)}}function Vo(e,t,n){return{name:e,async setup(){await No(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Go{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=$n(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Wn(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=v(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}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(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const qo="__preview__";class Ko{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(ii);t.register({name:qo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(qo),this.loadPromise_=t.load(qo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Go(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await No(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,qo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Oe]);for(const s of n){if(e.get(s,Oe).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([Le]);for(const i of s){const s=e.get(i,Le);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(ii).getScene(qo),r=i?i.spawn():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},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,Ue,o);const a={isActive:!0,projectionType:Fe.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Be.ColorAndDepth};e.insert(r,Oe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ii);await e.switchTo(qo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Jo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Gs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Gs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Gs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Gs.releaseRenderTarget(e._handle),Jo.create({width:t,height:n,depth:!0})),begin(e,t){Gs.begin(t,e._handle)},end(){Gs.end()},getDepthTexture:e=>Gs.getTargetDepthTexture(e._handle)};var Qo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Qo||(Qo={}));class Zo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Qo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Qo.Debug:console.debug(t,n);break;case Qo.Info:console.log(t,n);break;case Qo.Warn:console.warn(t,n);break;case Qo.Error:console.error(t,n)}}}class ea{constructor(){this.handlers_=[],this.minLevel_=Qo.Info,this.addHandler(new Zo)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Qo.Debug,e,t,n)}info(e,t,n){this.log(Qo.Info,e,t,n)}warn(e,t,n){this.log(Qo.Warn,e,t,n)}error(e,t,n){this.log(Qo.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ta=new ea;function na(){return ta}function sa(e){ta.setMinLevel(e)}function ia(e,t,n){ta.debug(e,t,n)}function ra(e,t,n){ta.info(e,t,n)}function oa(e,t,n){ta.warn(e,t,n)}function aa(e,t,n){ta.error(e,t,n)}const la={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},ca={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},ua={Running:0,Paused:1,Completed:2,Cancelled:3},ha={None:0,Restart:1,PingPong:2};class da{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let fa=null,pa=null;function ma(e,t){fa=e,pa=t}function ga(){fa=null,pa=null}function ya(){if(!fa)throw new Error("Tween API not initialized");return fa}function _a(){if(!pa)throw new Error("Tween API not initialized");return pa}const wa={to(e,t,n,s,i,r){const o=ya(),a=_a(),l=r?.easing??la.Linear,c=r?.delay??0,u=r?.loop??ha.None,h=r?.loopCount??0,d=o._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new da(o,a,d)},cancel(e){ya()._anim_cancelTween(_a(),e.entity)},cancelAll(e){ya()._anim_cancelAllTweens(_a(),e)},update(e){ya()._anim_updateTweens(_a(),e)}};class xa{constructor(){this.name="AnimationPlugin"}build(e){ma(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(jt.Update,Nt([st(at)],e=>{wa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(jt.Update,Nt([st(at)],e=>{kn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ga()}}const va=new xa;class ba{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=t.volume??1,this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof ba?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class Sa{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new ba(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new ba(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new ba(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new ba(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new ba(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new ba(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class Pa{constructor(e,t=16){this.pool_=[],this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,priority:0,startTime:0}}acquire(e=0){let t=this.pool_.find(e=>!e.inUse);return t||(t=this.createNode(),this.pool_.push(t)),t.inUse=!0,t.priority=e,t.startTime=this.context_.currentTime,t.gain.gain.value=1,t.panner.pan.value=0,t}release(e){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0}get activeCount(){return this.pool_.filter(e=>e.inUse).length}get capacity(){return this.pool_.length}}var Ma;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ma||(Ma={}));const Ta={model:Ma.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Ea(e,t=Ta){const{model:n,refDistance:s,maxDistance:i,rolloff:r}=t,o=Math.max(e,.001);switch(n){case Ma.Linear:return 1-(Math.min(Math.max(o,s),i)-s)/(i-s);case Ma.Inverse:return s/Math.max(o,s);case Ma.Exponential:return Math.pow(Math.max(o,s)/s,-r);default:return 1}}function Ca(e,t,n,s,i){const r=e-n;return Math.max(-1,Math.min(1,r/i))}const Ra=be("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ma.Inverse,rolloff:1,priority:0,enabled:!0}),Aa=be("AudioListener",{enabled:!0});class Ia{constructor(e,t,n,s,i){this.playing_=!0,this.id=e,this.source_=t,this.poolNode_=n,this.pool_=s,this.context_=i}stop(){this.playing_=!1,this.pool_.release(this.poolNode_)}pause(){this.playing_&&(this.playing_=!1,this.source_.playbackRate.value=0)}resume(){this.playing_||(this.playing_=!0,this.source_.playbackRate.value=1)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.source_.loop=e}setPlaybackRate(e){this.source_.playbackRate.value=e}get isPlaying(){return this.playing_}get currentTime(){return this.playing_?this.context_.currentTime-this.poolNode_.startTime:0}get duration(){return this.source_.buffer?.duration??0}markEnded(){this.playing_=!1}}class ka{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.nextBufferId_=0,this.nextHandleId_=0}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new Sa(this.context_,e.mixerConfig),this.pool_=new Pa(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e)};document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("mousedown",e,{once:!0}),document.addEventListener("keydown",e,{once:!0})}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=await fetch(e),n=await t.arrayBuffer(),s=await this.context_.decodeAudioData(n),i=++this.nextBufferId_;return this.buffers_.set(i,s),{id:i,duration:s.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(t.priority??0),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const r=t.bus??"sfx",o=this.mixer_.getBus(r)??this.mixer_.sfx;s.panner.connect(o.node),i.start(0,t.startOffset??0);const a=++this.nextHandleId_,l=new Ia(a,i,s,this.pool_,this.context_);return i.onended=()=>{i.loop||(l.markEnded(),this.pool_.release(s),l.onEnd?.())},l}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.context_?.close(),this.context_=null}}class Fa{constructor(e,t,n){this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class Ba{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}async initialize(){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.src=n,s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.autoplay=!0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const r=new Fa(i,s,this.contexts_);return s.onEnded(()=>{r.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),r}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function za(){return i()?new Ba:new ka}class Ua{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const t=za();t.initialize();let n=null;t instanceof ka&&(n=t.mixer),Fn.init(t,n);const s=new Map;e.addSystemToSchedule(jt.PreUpdate,Nt([st(at)],n=>{const i=e.world;let r=0,o=0;const a=i.getEntitiesWithComponents([Aa,$e]);for(const e of a){if(i.get(e,Aa).enabled){const t=i.get(e,$e);r=t.position.x,o=t.position.y;break}}const l=i.getEntitiesWithComponents([Ra,$e]);for(const e of l){const n=i.get(e,Ra);if(!n.enabled||!n.clip)continue;const a=i.get(e,$e);if(n.playOnAwake&&!s.has(e)){const i=Fn.getBufferHandle(n.clip);if(i){const r=t.play(i,{bus:n.bus,volume:n.volume,loop:n.loop,playbackRate:n.pitch,priority:n.priority});s.set(e,r)}}if(n.spatial&&s.has(e)){const t=s.get(e),i=a.position.x-r,l=a.position.y-o,c=Ea(Math.sqrt(i*i+l*l),{model:n.attenuationModel,refDistance:n.minDistance,maxDistance:n.maxDistance,rolloff:n.rolloff}),u=Ca(a.position.x,a.position.y,r,0,n.maxDistance);t.setVolume(n.volume*c),t.setPan(u)}}},{name:"AudioUpdateSystem"}))}cleanup(){}}const Wa=new Ua;class $a{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Da(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Oa(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:r}=e,o=t.getResource(Jn);o&&(o.registerEmbeddedAssets(s),o.setEmbeddedOnly(!0)),ci(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Da(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Da(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Vo(r,i,{app:t,module:n,provider:new $a(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),u=t.getResource(ii);u.register(c),u.setInitial(r),await u.load(r);const h=e.canvas.width/e.canvas.height;Gn(t.world,h),t.run()}const La=[tr,mr,Sr,Nr,eo,Br,so,ao,po,qr,Or,mo,_o,bo,Po,Ro,Io],Ha=[...La,va];function ja(e,t){return function(e,t){const n=li.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),gs(e),un(e),Fs(e),$s(e),Ns(e),Ks(e);const i=new Zs;n.setPipeline(i);let r=d();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=pi(e,s,t,i));const o=n.getResource(nn);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(nn,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Gs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-r)/1e3;let h;if(Gs.resize(t,l),Ls.isInitialized()&&Ls.getPassCount()>0&&!Ls.isBypassed()&&Ls.resize(t,l),n.hasResource(ii)){const e=n.getResource(ii).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=pi(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:ui,width:t,height:l,elapsed:u});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Gs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(jt.First,l),n.addSystemToSchedule(jt.Last,c),n.addPlugin(Zn),n.addPlugin(us),n.addPlugin(tn),n.addPlugin(ai),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ha,...t})}class Xa{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Ya(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Na(e,t){try{return await e({instantiateWasm:Ya(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Va(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=k(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),r=wx.createCanvas(),o=wx.getSystemInfoSync();r.width=o.windowWidth*o.pixelRatio,r.height=o.windowHeight*o.pixelRatio;const a=await e.engineFactory({canvas:r,instantiateWasm:Ya("esengine.wasm")}),c=r.getContext("webgl2")||r.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),h=ja(a,{glContextHandle:u,getViewportSize:()=>({width:r.width,height:r.height})});e.runtimeConfig&&le(h,e.runtimeConfig),ci(h);let d=null;e.spineFactory&&(d=await Na(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Na(e.physicsFactory,"physics.wasm"));const p={app:h,module:a,provider:new Xa(i),spineModule:d,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n},m=h.getResource(ii);for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`),n=JSON.parse(e);m.register(Vo(t,n,p))}e.firstScene&&(m.setInitial(e.firstScene),await m.load(e.firstScene));const g=r.width/r.height;Gn(h.world,g),h.run()}X||(X=!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},i=await p(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.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 m(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 i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}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 i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Y;export{St as Added,xa as AnimationPlugin,li as App,Qn as AssetPlugin,es as AssetRefCounter,Kn as AssetServer,Jn as Assets,bn as AsyncCache,Ma as AttenuationModel,Fn as Audio,ba as AudioBus,Aa as AudioListener,Sa as AudioMixer,Ua as AudioPlugin,Pa as AudioPool,Ra as AudioSource,Ye as BitmapText,sn as BlendMode,et as BodyType,Je as BoxCollider,wr as Button,_r as ButtonState,Oe as Camera,Le as Canvas,Ze as CapsuleCollider,Pt as Changed,Xe as Children,Qe as CircleCollider,Be as ClearFlags,Ft as Commands,zt as CommandsInstance,V as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,te as DEFAULT_FALLBACK_DT,se as DEFAULT_FIXED_TIMESTEP,J as DEFAULT_FONT_FAMILY,Q as DEFAULT_FONT_SIZE,ne as DEFAULT_GRAVITY,Z as DEFAULT_LINE_HEIGHT,ee as DEFAULT_MAX_DELTA_TIME,G as DEFAULT_PIXELS_PER_UNIT,ie as DEFAULT_SPINE_SKIN,K as DEFAULT_SPRITE_SIZE,q as DEFAULT_TEXT_CANVAS_SIZE,Cs as DataType,no as DragState,to as Draggable,xs as Draw,So as Dropdown,la as EasingType,Bt as EntityCommands,Ot as EventReader,Ht as EventReaderInstance,$t as EventRegistry,Dt as EventWriter,Lt as EventWriterInstance,Si as FillDirection,Hr as FillMethod,jr as FillOrigin,$r as FocusManager,Wr as FocusManagerState,Ur as Focusable,Qs as GLDebug,Us as Geometry,Xt as GetWorld,ce as INVALID_ENTITY,he as INVALID_FONT,de as INVALID_MATERIAL,ue as INVALID_TEXTURE,Xr as Image,Lr as ImageType,Zt as Input,en as InputPlugin,Qt as InputState,gr as Interactable,wo as ListView,We as LocalTransform,Qo as LogLevel,ea as Logger,ha as LoopMode,fn as Material,Sn as MaterialLoader,vt as Mut,Ve as Name,je as Parent,Oo as Physics,Bo as PhysicsEvents,$o as PhysicsPlugin,Ls as PostProcess,as as PrefabServer,ls as Prefabs,cs as PrefabsPlugin,Ko as PreviewPlugin,Jr as ProgressBar,Kr as ProgressBarDirection,Zr as ProgressBarPlugin,Fe as ProjectionType,Rt as Query,At as QueryInstance,It as Removed,kt as RemovedQueryInstance,Zs as RenderPipeline,js as RenderStage,Jo as RenderTexture,Gs as Renderer,st as Res,it as ResMut,Ke as RigidBody,re as RuntimeConfig,go as SafeArea,ze as ScaleMode,ii as SceneManager,si as SceneManagerState,Ge as SceneOwner,jt as Schedule,io as ScrollView,vn as ShaderSources,co as Slider,lo as SliderDirection,fo as SliderPlugin,Ne as SpineAnimation,De as Sprite,In as SpriteAnimator,Jt as SystemRunner,Ji as Text,Gi as TextAlign,zr as TextInput,Dr as TextInputPlugin,Ki as TextOverflow,er as TextPlugin,Qi as TextRenderer,qi as TextVerticalAlign,at as Time,Vr as Toggle,Ue as Transform,wa as Tween,da as TweenHandle,ua as TweenState,ca as TweenTarget,nn as UICameraInfo,xr as UIEventQueue,vr as UIEvents,yr as UIInteraction,Fr as UIInteractionPlugin,br as UILayoutPlugin,ir as UIMask,pr as UIMaskPlugin,Mi as UIRect,Ao as UIRenderOrderPlugin,He as Velocity,Xa as WeChatAssetProvider,Go as WebAssetProvider,xt as World,$e as WorldTransform,qt as addStartupSystem,Gt as addSystem,Kt as addSystemToSchedule,va as animationPlugin,le as applyBuildRuntimeConfig,ki as applyDirectionalFill,oe as applyRuntimeConfig,Zn as assetPlugin,Wa as audioPlugin,Ea as calculateAttenuation,Ca as calculatePanning,An as clearAnimClips,Es as clearDrawCallbacks,Me as clearUserComponents,ge as color,Ri as computeFillAnchors,Ii as computeFillSize,Ai as computeHandleAnchors,Pi as computeUIRectLayout,za as createAudioBackend,fr as createMaskProcessor,Vo as createRuntimeSceneConfig,ja as createWebApp,ia as debug,be as defineComponent,Ut as defineEvent,nt as defineResource,Nt as defineSystem,Se as defineTag,aa as error,Pn as extractAnimClipTexturePaths,qn as findEntityByName,ci as flushPendingSystems,S as getAddressableType,P as getAddressableTypeByEditorType,T as getAllAssetExtensions,Rn as getAnimClip,A as getAssetMimeType,v as getAssetTypeEntry,Ie as getComponent,Wn as getComponentAssetFieldDescriptors,Un as getComponentAssetFields,qe as getComponentDefaults,Ln as getComponentEntityFields,$n as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,na as getLogger,t as getPlatform,s as getPlatformType,Pe as getUserComponent,R as getWeChatPackOptions,ra as info,gs as initDrawAPI,Ks as initGLDebugAPI,Fs as initGeometryAPI,un as initMaterialAPI,Oa as initPlayableRuntime,$s as initPostProcessAPI,Ns as initRendererAPI,ma as initTweenAPI,Va as initWeChatRuntime,tn as inputPlugin,ns as instantiatePrefab,rr as intersectRects,or as invertMatrix4,Ce as isBuiltinComponent,I as isCustomExtension,Er as isEditor,M as isKnownAssetExtension,n as isPlatformInitialized,Ar as isPlayMode,Cr as isRuntime,rn as isTextureRef,i as isWeChat,r as isWeb,Vn as loadComponent,Fo as loadPhysicsModule,No as loadRuntimeScene,Xn as loadSceneData,Yn as loadSceneWithAssets,E as looksLikeAssetPath,Mn as parseAnimClipData,o as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,hr as pointInOBB,lr as pointInWorldRect,us as prefabsPlugin,eo as progressBarPlugin,ye as quat,En as registerAnimClip,Ae as registerComponent,zn as registerComponentAssetFields,On as registerComponentEntityFields,Ms as registerDrawCallback,ts as registerEmbeddedAssets,xn as registerMaterialCallback,Hn as remapEntityFields,ai as sceneManagerPlugin,ar as screenToWorld,Tr as setEditorMode,vo as setListViewRenderer,sa as setLogLevel,Rr as setPlayMode,dt as setWasmErrorHandler,ys as shutdownDrawAPI,Js as shutdownGLDebugAPI,Bs as shutdownGeometryAPI,hn as shutdownMaterialAPI,Ds as shutdownPostProcessAPI,Vs as shutdownRendererAPI,ga as shutdownTweenAPI,po as sliderPlugin,kn as spriteAnimatorSystemUpdate,Oi as syncFillSpriteSize,Or as textInputPlugin,tr as textPlugin,k as toBuildPath,ko as transitionTo,Br as uiInteractionPlugin,Sr as uiLayoutPlugin,mr as uiMaskPlugin,La as uiPlugins,Io as uiRenderOrderPlugin,Cn as unregisterAnimClip,Te as unregisterComponent,Ts as unregisterDrawCallback,Gn as updateCameraAspectRatio,fe as vec2,pe as vec3,me as vec4,oa as warn,ri as wrapSceneSystem,$ as wxFileExists,D as wxFileExistsSync,H as wxGetImagePixels,L as wxLoadImage,j as wxLoadImagePixels,U as wxReadFile,W as wxReadTextFile,O 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 b097a4bc7..58c390340 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -1736,7 +1736,7 @@ interface SceneLoadOptions {
assetBaseUrl?: string;
collectAssets?: LoadedSceneAssets;
}
-type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip';
+type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio';
interface AssetFieldDescriptor {
field: string;
type: AssetFieldType;
@@ -3447,6 +3447,195 @@ interface AnimClipAssetData {
declare function extractAnimClipTexturePaths(data: AnimClipAssetData): string[];
declare function parseAnimClipData(clipPath: string, data: AnimClipAssetData, textureHandles: Map<string, number>): SpriteAnimClip;
+interface AudioHandle {
+ readonly id: number;
+ stop(): void;
+ pause(): void;
+ resume(): void;
+ setVolume(volume: number): void;
+ setPan(pan: number): void;
+ setLoop(loop: boolean): void;
+ setPlaybackRate(rate: number): void;
+ readonly isPlaying: boolean;
+ readonly currentTime: number;
+ readonly duration: number;
+ onEnd?: () => void;
+}
+interface AudioBufferHandle {
+ readonly id: number;
+ readonly duration: number;
+}
+interface PlayConfig {
+ volume?: number;
+ pan?: number;
+ loop?: boolean;
+ playbackRate?: number;
+ bus?: string;
+ priority?: number;
+ startOffset?: number;
+}
+interface PlatformAudioBackend {
+ readonly name: string;
+ initialize(): Promise<void>;
+ ensureResumed(): Promise<void>;
+ loadBuffer(url: string): Promise<AudioBufferHandle>;
+ unloadBuffer(handle: AudioBufferHandle): void;
+ play(buffer: AudioBufferHandle, config: PlayConfig): AudioHandle;
+ suspend(): void;
+ resume(): void;
+ dispose(): void;
+}
+
+interface AudioBusConfig {
+ name: string;
+ volume?: number;
+ muted?: boolean;
+ parent?: string;
+}
+declare class AudioBus {
+ private readonly name_;
+ private readonly gainNode_;
+ private muted_;
+ private volume_;
+ private children_;
+ constructor(context: AudioContext, config: AudioBusConfig);
+ get name(): string;
+ get node(): GainNode;
+ get volume(): number;
+ set volume(v: number);
+ get muted(): boolean;
+ set muted(m: boolean);
+ connect(destination: AudioBus | AudioNode): void;
+ addChild(child: AudioBus): void;
+}
+
+interface AudioMixerConfig {
+ masterVolume?: number;
+ musicVolume?: number;
+ sfxVolume?: number;
+ uiVolume?: number;
+ voiceVolume?: number;
+}
+declare class AudioMixer {
+ readonly master: AudioBus;
+ readonly music: AudioBus;
+ readonly sfx: AudioBus;
+ readonly ui: AudioBus;
+ readonly voice: AudioBus;
+ private readonly context_;
+ private readonly buses_;
+ constructor(context: AudioContext, config?: AudioMixerConfig);
+ getBus(name: string): AudioBus | undefined;
+ createBus(config: AudioBusConfig): AudioBus;
+}
+
+declare class Audio {
+ private static backend_;
+ private static mixer_;
+ private static bufferCache_;
+ private static bgmHandle_;
+ static init(backend: PlatformAudioBackend, mixer?: AudioMixer | null): void;
+ static preload(url: string): Promise<void>;
+ static preloadAll(urls: string[]): Promise<void>;
+ static playSFX(url: string, config?: {
+ volume?: number;
+ pitch?: number;
+ pan?: number;
+ priority?: number;
+ }): AudioHandle;
+ static playBGM(url: string, config?: {
+ volume?: number;
+ fadeIn?: number;
+ crossFade?: number;
+ }): void;
+ static stopBGM(fadeOut?: number): void;
+ static setMasterVolume(volume: number): void;
+ static setMusicVolume(volume: number): void;
+ static setSFXVolume(volume: number): void;
+ static setUIVolume(volume: number): void;
+ static muteBus(busName: string, muted: boolean): void;
+ static getBufferHandle(url: string): AudioBufferHandle | undefined;
+ private static fadeIn;
+ private static fadeOut;
+ private static createPendingHandle;
+}
+
+interface PooledAudioNode {
+ gain: GainNode;
+ panner: StereoPannerNode;
+ source: AudioBufferSourceNode | null;
+ inUse: boolean;
+ priority: number;
+ startTime: number;
+}
+declare class AudioPool {
+ private readonly context_;
+ private readonly pool_;
+ constructor(context: AudioContext, initialSize?: number);
+ private createNode;
+ acquire(priority?: number): PooledAudioNode;
+ release(node: PooledAudioNode): void;
+ get activeCount(): number;
+ get capacity(): number;
+}
+
+interface AudioPluginConfig {
+ maxPoolSize?: number;
+ masterVolume?: number;
+ musicVolume?: number;
+ sfxVolume?: number;
+}
+declare class AudioPlugin implements Plugin {
+ name: string;
+ private config_;
+ constructor(config?: AudioPluginConfig);
+ build(app: App): void;
+ cleanup(): void;
+}
+declare const audioPlugin: AudioPlugin;
+
+interface AudioSourceData {
+ clip: string;
+ bus: string;
+ volume: number;
+ pitch: number;
+ loop: boolean;
+ playOnAwake: boolean;
+ spatial: boolean;
+ minDistance: number;
+ maxDistance: number;
+ attenuationModel: number;
+ rolloff: number;
+ priority: number;
+ enabled: boolean;
+}
+declare const AudioSource: ComponentDef<AudioSourceData>;
+interface AudioListenerData {
+ enabled: boolean;
+}
+declare const AudioListener: ComponentDef<AudioListenerData>;
+
+declare function createAudioBackend(): PlatformAudioBackend;
+
+declare enum AttenuationModel {
+ Linear = 0,
+ Inverse = 1,
+ Exponential = 2
+}
+interface SpatialAudioConfig {
+ model: AttenuationModel;
+ refDistance: number;
+ maxDistance: number;
+ rolloff: number;
+}
+declare function calculateAttenuation(distance: number, config?: SpatialAudioConfig): number;
+declare function calculatePanning(sourceX: number, sourceY: number, listenerX: number, listenerY: number, maxDistance: number): number;
+
+interface WebAudioBackendOptions {
+ initialPoolSize?: number;
+ mixerConfig?: AudioMixerConfig;
+}
+
/**
* @file playableRuntime.ts
* @brief Playable ad runtime initialization (single-HTML builds)
@@ -3474,5 +3663,5 @@ declare const uiPlugins: Plugin[];
declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;
-export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, 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, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragState, Draggable, Draw, Dropdown, EasingType, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, Focusable, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImageType, Input, InputPlugin, InputState, Interactable, ListView, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ShaderSources, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, Toggle, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, clearAnimClips, clearDrawCallbacks, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineEvent, defineResource, defineSystem, defineTag, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAnimClip, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, parseAnimClipData, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, remapEntityFields, sceneManagerPlugin, screenToWorld, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, syncFillSpriteSize, textInputPlugin, textPlugin, toBuildPath, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };
-export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnimClipAssetData, AnyComponentDef, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, BezierPoints, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, PlayableRuntimeConfig, Plugin, PluginDependency, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeSceneOptions, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, TweenOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
+export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragState, Draggable, Draw, Dropdown, EasingType, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, Focusable, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImageType, Input, InputPlugin, InputState, Interactable, ListView, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ShaderSources, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, Toggle, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, clearAnimClips, clearDrawCallbacks, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createAudioBackend, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineEvent, defineResource, defineSystem, defineTag, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAnimClip, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, parseAnimClipData, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, remapEntityFields, sceneManagerPlugin, screenToWorld, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, syncFillSpriteSize, textInputPlugin, textPlugin, toBuildPath, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };
+export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnimClipAssetData, AnyComponentDef, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, AudioBufferHandle, AudioBusConfig, AudioHandle, AudioListenerData, AudioMixerConfig, AudioPluginConfig, AudioSourceData, BezierPoints, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, Plugin, PluginDependency, PooledAudioNode, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeSceneOptions, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpatialAudioConfig, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, TweenOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WebAudioBackendOptions, WorldTransformData };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 592940d47..95c0603f1 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 i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(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 d(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}const p=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 loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}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),i=t=>e.onKeyUp(t.code),r=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=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)}},d=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",r),n.addEventListener("mousedown",o),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",d),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",r),n.removeEventListener("mousedown",o),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",d),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},g=1920,y=1080,m=100,_=512,w={x:100,y:100},x="Arial",v=24,b=1.2,S=.5,P=1/60,M={x:0,y:-9.81},T=1/60,E="default",R={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function C(e){e.Text&&(e.Text._default.fontFamily=R.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=R.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=R.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=R.canvasMatchWidthOrHeight)}const A={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function I(e,t){if(void 0!==t.maxDeltaTime&&(R.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(R.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(R.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(R.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(R.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");R.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(R.canvasScaleMode=A[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(R.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const k=0,F=4294967295,B=4294967295,z=0,U=(e=0,t=0)=>({x:e,y:t}),$=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),D=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),L=(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 O(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(O);const t={};for(const n in e)t[n]=O(e[n]);return t}let H=0;function X(e,t){const n=++H,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{...O(t),...e}:O(t):e?{...t,...e}:{...t}}}function j(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Y(e,t){const n=Q.get(e)??j().get(e);if(n)return n;const s=X(e,t);return j().set(e,s),Q.set(e,s),K(e,t,!1),s}function N(e){const t=Q.get(e)??j().get(e);if(t)return t;const n=X(e,{});return j().set(e,n),Q.set(e,n),K(e,{},!0),n}function V(e){return j().get(e)}function G(){const e=j();for(const t of e.keys())Q.delete(t);e.clear()}function q(e){j().delete(e),Q.delete(e)}function K(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function J(e){return!0===e._builtin}const Q=new Map;function Z(e,t){Q.set(e,t)}function ee(e){return Q.get(e)??V(e)}function te(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Q.set(e,n),n}const ne={Perspective:0,Orthographic:1},se={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ie={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},re=te("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),oe=re,ae=re,le=te("Sprite",{texture:F,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,enabled:!0}),ce=te("Camera",{projectionType:ne.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:se.ColorAndDepth}),de=te("Canvas",{designResolution:{x:g,y:y},pixelsPerUnit:100,scaleMode:ie.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=te("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),ue=te("Parent",{entity:0}),fe=te("Children",{entities:[]}),pe=te("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B,enabled:!0}),ge=te("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,enabled:!0}),ye=Y("Name",{value:""}),me=Y("SceneOwner",{scene:"",persistent:!1});function _e(e){const t=ee(e);return t?O(t._default):null}const we=te("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),xe=te("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=te("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be=te("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Se={Static:0,Kinematic:1,Dynamic:2};let Pe=0;function Me(e,t){const n=++Pe;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Te(e){return{_type:"res",_resource:e}}function Ee(e){return{_type:"res_mut",_resource:e}}class Re{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_)}updateValue(e){this.value_=e}}class Ce{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Re(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ae=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ie(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=ke(t[e]),r=ke(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Fe(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Be=null;function ze(e){Be=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Be&&Be(e,t)}function $e(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[t]="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}:s}}return n}let De=1;const Le=new WeakMap;function We(e){let t=Le.get(e);return void 0===t&&(t=De++,Le.set(e,t)),t}const Oe=[];function He(e,t=[],n=[]){Oe.length=0;for(const t of e)Oe.push(We(t));Oe.sort((e,t)=>e-t);let s=Oe.join(",");if(t.length>0){Oe.length=0;for(const e of t)Oe.push(We(e));Oe.sort((e,t)=>e-t),s+="|+"+Oe.join(",")}if(n.length>0){Oe.length=0;for(const e of n)Oe.push(We(e));Oe.sort((e,t)=>e-t),s+="|-"+Oe.join(",")}return s}class Xe{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ue(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ue(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Ue(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,n){return J(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(J(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,$e(n))}catch(n){Ue(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return J(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return J(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(J(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Ue(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");J(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),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 e=Ie(t._name,t._default,s);if(e.length>0)throw new Error(Fe(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,$e(i))}catch(n){Ue(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return Ue(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Ue(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ue(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=Ie(t._name,t._default,e);if(i.length>0)throw new Error(Fe(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Q)if(J(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=j();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??He(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!J(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function je(e){return{_type:"mut",_component:e}}function Ye(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ne(e){return{_filterType:"added",_component:e}}function Ve(e){return{_filterType:"changed",_component:e}}function Ge(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function qe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ke(e){return Ye(e)||Ge(e)||qe(e)?e._component:e}function Je(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),Ge(e)?i.push({index:t,component:e._component}):qe(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Je(e,[...t,...s],n),without:(...s)=>Je(e,t,[...n,...s])}}function Qe(...e){return Je(e)}class Ze{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Ke),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=He(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,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(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function et(e){return{_type:"removed",_component:e}}class tt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function nt(){return{_type:"commands"}}class st{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=J(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 it{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new st(this,null);return this.spawned_.push(e),e}entity(e){return new st(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}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":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function rt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class ot{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class at{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ot)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ot,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function lt(e){return{_type:"event_writer",_event:e}}function ct(e){return{_type:"event_reader",_event:e}}class dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class ht{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ut;function ft(){return{_type:"get_world"}}!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"}(ut||(ut={}));let pt=0;function gt(e,t,n){const s=++pt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function yt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function mt(e){yt().push({schedule:ut.Update,system:e})}function _t(e){yt().push({schedule:ut.Startup,system:e})}function wt(e,t){yt().push({schedule:e,system:t})}class xt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof it&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ze(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new it(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new ht(n)}case"removed":{const t=e;return new tt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class vt{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 bt=Me(new vt,"Input");class St{constructor(e){this.target_=e??null}build(e){const n=new vt;e.insertResource(bt,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(ut.Last,gt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Pt=new St,Mt=Me({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Tt;function Et(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"}(Tt||(Tt={}));let Rt=null,Ct=null,At=1;const It=new Map;function kt(e){Rt=e,Ct=e.getResourceManager(),Ht()}function Ft(){0!==$t&&Rt&&(Rt._free($t),$t=0),It.clear(),At=1,Ut=!1,Lt.clear(),Wt=null,Ct=null,Rt=null}function Bt(){if(!Ct)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ct}const zt={createShader:(e,t)=>Bt().createShader(e,t),releaseShader(e){e>0&&Bt().releaseShader(e)},create(e){const t=At++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Tt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};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),s.dirty_=!0,Rt?.invalidateMaterialCache(e))},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,Rt?.invalidateMaterialCache(e))},getBlendMode(e){const t=It.get(e);return t?.blendMode??Tt.Normal},setDepthTest(e,t){const n=It.get(e);n&&(n.depthTest=t,Rt?.invalidateMaterialCache(e))},getShader(e){const t=It.get(e);return t?.shader??0},release(e){It.delete(e),Rt?.invalidateMaterialCache(e)},isValid:e=>It.has(e),releaseAll(){It.clear(),Rt?.clearMaterialCache()},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??Tt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=It.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=At++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};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 Ut=!1,$t=0;const Dt=16384,Lt=new Map;let Wt=null;function Ot(e){const t=(0===$t&&Rt&&($t=Rt._malloc(Dt)),$t);if(0===t||!Rt)return{ptr:0,count:0};let n=0,s=0;const i=Rt.HEAPU8,r=Rt.HEAPU32,o=Rt.HEAPF32;for(const[a,l]of e){if(Et(l))continue;let e=Lt.get(a);e||(Wt||(Wt=new TextEncoder),e=Wt.encode(a),Lt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>Dt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Dt} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[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++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Ht(){if(!Rt||Ut)return;Rt.materialDataProvider=(e,t,n,s,i)=>{const r=It.get(e);if(!r)return Rt.HEAPU32[t>>2]=0,Rt.HEAPU32[n>>2]=0,Rt.HEAPU32[s>>2]=0,void(Rt.HEAPU32[i>>2]=0);Rt.HEAPU32[t>>2]=r.shader,Rt.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Ot(r.uniforms);Rt.HEAPU32[s>>2]=o,Rt.HEAPU32[i>>2]=a},Ut=!0}const Xt={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 jt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Yt{constructor(e,t=""){this.cache_=new jt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(zt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())zt.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 i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:zt.createFromAsset(s,r),shaderHandle:r,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 Nt(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Vt(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:n.get(e.texture)??0}))}}const Gt=new Map;function qt(e){Gt.set(e.name,e)}function Kt(e){Gt.delete(e)}function Jt(e){return Gt.get(e)}function Qt(){Gt.clear()}const Zt=Y("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function en(e,t){const n=e.getEntitiesWithComponents([Zt]);for(const s of n){const n=e.get(s,Zt);if(!n.enabled||!n.playing||!n.clip)continue;const i=Gt.get(n.clip);if(!i||0===i.frames.length)continue;const r=1/(i.fps*n.speed),o=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=o;if(n.frameTimer>=r&&(n.frameTimer-=r,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,le)){const t=i.frames[n.currentFrame],r=e.get(s,le);r.texture=t.texture,e.insert(s,le,r)}a&&e.insert(s,Zt,n)}}const tn=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}]]);function nn(e,t){tn.set(e,t)}function sn(e){const t=tn.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function rn(e){return tn.get(e)?.fields??[]}function on(e){return tn.get(e)?.spine??null}const an=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function ln(e,t){an.set(e,t)}function cn(e){return an.get(e)}function dn(e,t){const n=an.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function hn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,ye,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)dn(i,n),gn(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function un(e,t){return hn(e,t)}async function fn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,r=new Map;s&&await async function(e,t,n,s,i){const r=new Map;for(const e of pn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=tn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...pn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=tn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,r,n?.collectAssets);const o=hn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const pn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),r=Nt(i),o=new Map,a=r.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(i);o.set(e,r.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),o.set(e,0)}});await Promise.all(a);qt(Vt(e,i,o))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function gn(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=ee(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function yn(e,t){const n=e.getEntitiesWithComponents([ce]);for(const s of n){const n=e.get(s,ce);n&&(n.aspectRatio=t,e.insert(s,ce,n))}}function mn(e,t){const n=e.getEntitiesWithComponents([ye]);for(const s of n){const n=e.get(s,ye);if(n&&n.value===t)return s}return null}const _n=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],wn={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},xn=new Map,vn=new Set;for(const e of _n)for(const t of e.extensions)xn.set(t,e),vn.add(t);function bn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Sn(e){return xn.get(bn(e))}function Pn(e){return Sn(e)?.editorType??"unknown"}function Mn(e){return Sn(e)?.addressableType??null}function Tn(e){for(const t of _n)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function En(e){return vn.has(e.toLowerCase())}function Rn(){return vn}function Cn(e){return"string"==typeof e&&(!!e.includes("/")&&En(bn(e)))}function An(){const e=[];for(const t of _n)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function In(){return An().map(e=>({type:"suffix",value:e}))}function kn(e){return wn[e.toLowerCase()]}function Fn(e){const t=Sn(e);return t?.wechatPackInclude??!1}function Bn(e){const t=Sn(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}class zn{constructor(e){this.textureCache_=new jt,this.shaderCache_=new jt,this.jsonCache_=new jt,this.textCache_=new jt,this.binaryCache_=new jt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new jt,this.prefabCache_=new jt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(R.textCanvasSize,R.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Yt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,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);if(this.materialLoader_.releaseAll(),zt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===Sn(e)?.contentType,h=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,r,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Sn(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of sn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=on(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 fn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;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 i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.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.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return zt.createShader(s,i)}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:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return zt.createShader(i,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(Bn(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(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 o(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.getEmbedded(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 o(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.getEmbedded(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 o(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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 Un=Me(null,"Assets");class $n{build(e){const t=e.wasmModule;t?e.insertResource(Un,new zn(t)):console.warn("AssetPlugin: No WASM module available")}}const Dn=new $n;class Ln{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Wn(e,t){const n=e.getResource(Un);n&&n.registerEmbeddedAssets(t)}async function On(e,t,n){const{entities:s,rootId:i}=await Xn(t,n?.overrides??[],n,void 0,new Set),r={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,visible:e.visible}))},o=await fn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const Hn=10;async function Xn(e,t,n,s,i,r=0){if(r>Hn)throw new Error(`Prefab nesting depth exceeded ${Hn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Xn(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};jn(h.components,o),Yn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function jn(e,t){for(const n of e){const e=cn(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function Yn(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 Nn{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return On(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Vn=Me(null,"Prefabs");class Gn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Un]}build(e){const t=e.getResource(Un);e.insertResource(Vn,new Nn(e.world,t))}}const qn=new Gn;let Kn=null,Jn=0,Qn=0,Zn=0;const es=new Float32Array(256);function ts(e){Kn=e,Jn=Kn._malloc(64),Qn=Kn._malloc(64),Zn=Kn._malloc(1024)}function ns(){Kn&&(Jn&&(Kn._free(Jn),Jn=0),Qn&&(Kn._free(Qn),Qn=0),Zn&&(Kn._free(Zn),Zn=0)),Kn=null}function ss(){if(!Kn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Kn}const is={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jn/4),t.draw_begin(Jn)}catch(e){Ue(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,n,s=1){try{ss().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ue(e,"Draw.line")}},rect(e,t,n,s=!0){try{ss().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{ss().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{ss().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{ss().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,n,s=is){try{ss().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,n,s,i=is){try{ss().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Kn?Kn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Kn?Kn.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ss();s.HEAPF32.set(n,Qn/4),s.draw_mesh(e,t,Qn)}catch(n){Ue(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ss(),i=zt.get(t);if(!i)return;if(rs.setBlendMode(i.blendMode),rs.setDepthTest(i.depthTest),0===i.uniforms.size)return void rs.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Qn/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=ls(t);if(!(s<0)){if(Et(n))es[r++]=10,es[r++]=s,es[r++]=n.slot??e++,es[r++]=n.textureId;else if("number"==typeof n)es[r++]=1,es[r++]=s,es[r++]=n;else if(Array.isArray(n)){es[r++]=n.length,es[r++]=s;for(let e=0;e<n.length;e++)es[r++]=n[e]}else"w"in n?(es[r++]=4,es[r++]=s,es[r++]=n.x,es[r++]=n.y,es[r++]=n.z,es[r++]=n.w):"z"in n?(es[r++]=3,es[r++]=s,es[r++]=n.x,es[r++]=n.y,es[r++]=n.z):(es[r++]=2,es[r++]=s,es[r++]=n.x,es[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(es.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Qn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Zn/4),s.draw_meshWithUniforms(e,i.shader,Qn,Zn,r)}catch(n){Ue(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},os={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},as=new Set;function ls(e){const t=os[e];return void 0!==t?t:(as.has(e)||(as.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(os).join(", ")}`)),-1)}const cs=new Map;function ds(e,t,n){cs.set(e,{fn:t,scene:n??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var fs;!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"}(fs||(fs={}));let ps=null,gs=0,ys=0,ms=0;function _s(e){ps=e,gs=ps._malloc(262144),ys=ps._malloc(65536),ms=ps._malloc(256)}function ws(){ps&&(gs&&ps._free(gs),ys&&ps._free(ys),ms&&ps._free(ms),gs=0,ys=0,ms=0),ps=null}function xs(){if(!ps)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ps}const vs={create(e){const t=xs(),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,gs/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ms,i).set(r),t.geometry_init(n,gs,s,ms,i,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,ys,s).set(e.indices),t.geometry_setIndices16(n,ys,s)}else{new Uint32Array(t.HEAPU8.buffer,ys,s).set(e.indices),t.geometry_setIndices32(n,ys,s)}}return n},updateVertices(e,t,n=0){const s=xs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,gs/4),s.geometry_updateVertices(e,gs,i,n)},release(e){e>0&&xs().geometry_release(e)},isValid:e=>!(!ps||e<=0)&&ps.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return vs.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:fs.Float2},{name:"a_texCoord",type:fs.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 i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return vs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:fs.Float2},{name:"a_texCoord",type:fs.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,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return vs.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:fs.Float2},{name:"a_texCoord",type:fs.Float2}],indices:new Uint16Array(o)})}};let bs=null;function Ss(e){bs=e}function Ps(){bs&&Ts.isInitialized()&&Ts.shutdown(),bs=null}function Ms(){if(!bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return bs}const Ts={init(e,t){try{return Ms().postprocess_init(e,t)}catch(n){return Ue(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ms().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{Ms().postprocess_resize(e,t)}catch(n){Ue(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ms().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ms().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ms().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ms().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ms().postprocess_setUniformFloat(e,t,n)}catch(n){Ue(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ms().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Ue(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ms().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{Ms().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return Ms().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!bs)return!1;try{return bs.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ms().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!bs)return!0;try{return bs.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>zt.createShader(Es,"#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:()=>zt.createShader(Es,"#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:()=>zt.createShader(Es,"#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:()=>zt.createShader(Es,"#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")},Es="#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 Rs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rs||(Rs={}));let Cs=null,As=0;function Is(e){Cs=e,As=Cs._malloc(64)}function ks(){Cs&&As&&(Cs._free(As),As=0),Cs=null}const Fs={init(e,t){Cs?.renderer_init(e,t)},resize(e,t){Cs?.renderer_resize(e,t)},begin(e,t){if(Cs&&As)try{Cs.HEAPF32.set(e,As/4),Cs.renderer_begin(As,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{Cs?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{Cs?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(Cs)try{Cs.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Cs)try{Cs.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Cs)try{Cs.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){Cs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Cs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Cs?.renderer_releaseTarget(e)},getTargetTexture:e=>Cs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Cs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Cs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Cs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Cs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Cs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Cs?Cs.getResourceManager().measureBitmapText(e,t,n,s):{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 Bs=null;function zs(e){Bs=e}function Us(){Bs=null}const $s={enable(){Bs?.gl_enableErrorCheck(!0)},disable(){Bs?.gl_enableErrorCheck(!1)},check:e=>Bs?.gl_checkErrors(e)??0,diagnose(){Bs?.renderer_diagnose()}};class Ds{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Fs.resize(s,i),Ts.isInitialized()&&Ts.getPassCount()>0&&Ts.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Fs.setViewport(0,0,s,i),Fs.clearBuffers(3),Fs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(n,r),Fs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Fs.setViewport(s.x,s.y,s.w,s.h),Fs.setScissor(s.x,s.y,s.w,s.h,!0),Fs.clearBuffers(i),Fs.setScissor(0,0,0,0,!1),Fs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(n,r),Fs.end()}executeDrawCallbacks(e,t){const n=cs;if(n.size>0){rs.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}rs.end();for(const e of s)hs(e)}}}const Ls="__scene_transition_overlay__";class Ws{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Os{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,me,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),ds(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,me)){const n=this.app_.world.get(e,me);n.persistent=t,this.app_.world.insert(e,me,n)}}}class Hs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??R.sceneTransitionDuration,i=t.color??{...R.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},ds(Ls,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,hs(Ls),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(Ls),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ws(t);this.scenes_.set(e,n);const s=new Os(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Un)?this.app_.getResource(Un):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ws(t);this.scenes_.set(e,n);const s=new Os(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Un)?this.app_.getResource(Un):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,me)){if(this.app_.world.get(e,me).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())hs(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Ts.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Un)&&(i.assetServer=this.app_.getResource(Un));const r=await fn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,me,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=js(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(Un)?this.app_.getResource(Un):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)zt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,le)){const t=n.get(e,le);s.sprite=t.color.a,t.color.a=0,n.insert(e,le,t),i=!0}if(n.has(e,ge)){const t=n.get(e,ge);s.spine=t.color.a,t.color.a=0,n.insert(e,ge,t),i=!0}if(n.has(e,pe)){const t=n.get(e,pe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,pe,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,le)){const t=n.get(e,le);t.color.a=s.sprite,n.insert(e,le,t)}if(void 0!==s.spine&&n.has(e,ge)){const t=n.get(e,ge);t.color.a=s.spine,n.insert(e,ge,t)}if(void 0!==s.bitmapText&&n.has(e,pe)){const t=n.get(e,pe);t.color.a=s.bitmapText,n.insert(e,pe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Ts.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Xs=Me(null,"SceneManager");function js(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Xs).getSceneStatus(t)&&n._fn(...s)}}}const Ys=gt([Ee(Xs),Te(Ae)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ns={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Xs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Xs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ut.Startup,n),e.addSystemToSchedule(ut.Last,Ys)}};class Vs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new at,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(ut.Last);else{this.runSchedule(ut.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ut.FixedPreUpdate),this.runSchedule(ut.FixedUpdate),this.runSchedule(ut.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ut.PreUpdate),this.runSchedule(ut.Update),this.runSchedule(ut.PostUpdate),this.runSchedule(ut.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Xe,this.resources_=new Ce;for(const e of Object.values(ut))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Vs}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(ut.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ut.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return ze(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Xs).register(e),this}setInitialScene(e){return this.getResource(Xs).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new xt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ae)||this.resources_.insert(Ae,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ut.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(ut.Last);else{this.runSchedule(ut.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ut.FixedPreUpdate),this.runSchedule(ut.FixedUpdate),this.runSchedule(ut.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ut.PreUpdate),this.runSchedule(ut.Update),this.runSchedule(ut.PostUpdate),this.runSchedule(ut.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new xt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ae,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ut.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,us();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Us,ks,Ps,ws,Ft,ns];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ae);t.delta=e,t.elapsed+=e,t.frameCount++}}function Gs(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ks(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case ie.FixedWidth:return r;case ie.FixedHeight:return o;case ie.Expand:return Math.max(r,o);case ie.Shrink:return Math.min(r,o);case ie.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const Js=[];function Qs(e){if(e<Js.length)return Js[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return Js.push(t),t}function Zs(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,me);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===ne.Orthographic){if(h=i.orthoSize,l){h=Ks(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=ti(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=si(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=ri(r.position.x,r.position.y,r.position.z),f=Qs(c.length);f.entity=e,f.viewProjection.set(ai(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ei=new Float32Array(16);function ti(e,t,n,s,i,r){const o=ei;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const ni=new Float32Array(16);function si(e,t,n,s){const i=ni;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const ii=new Float32Array(16);function ri(e,t,n){const s=ii;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}const oi=new Float32Array(16);function ai(e,t){const n=oi;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const li={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ci(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+o.x*m,originY:p+o.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const di=te("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}});let hi=null,ui=null;function fi(e,t){e.has(t,le)||e.insert(t,le,{texture:F,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})}function pi(e,t){switch(e){case li.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case li.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case li.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function gi(e,t){switch(e){case li.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case li.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case li.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function yi(e,t,n,s){switch(e){case li.BottomToTop:case li.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function mi(e,t,n,s){if(!e.has(t,di))return;const i=e.get(t,di),r=pi(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,di,i)}function _i(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function wi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function xi(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(wi(o.charCodeAt(0))&&s.length>0&&wi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!wi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function vi(e){let t=1;for(;t<e;)t*=2;return t}function bi(e,t){let n=0,s=t;for(;e.has(s,ue);){const t=e.get(s,ue).entity;if(!e.valid(t))break;n++,s=t}return n}function Si(e,t){if(hi&&ui){const e=hi.getUIRectComputedWidth(ui,t);if(e>0)return e}return e.size.x}function Pi(e,t){if(hi&&ui){const e=hi.getUIRectComputedHeight(ui,t);if(e>0)return e}return e.size.y}function Mi(e,t,n,s,i,r){if(!e.has(t,le))return;const o=e.get(t,le);let a,l;switch(n){case li.BottomToTop:case li.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,le,o))}function Ti(e,t,n){let s=t;for(;e.has(s,ue);){const t=e.get(s,ue).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ei(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ri(e,t,n,s,i){if(!e.has(t,di))return;const r=e.get(t,di),o=ci(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,le)){const n=e.get(t,le);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,le,n))}if(e.has(t,re)){const n=e.get(t,re);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,re,n)}}function Ci(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Ai=.1,Ii=30,ki={r:.3,g:.5,b:.8,a:1},Fi={Left:0,Center:1,Right:2},Bi={Top:0,Middle:1,Bottom:2},zi={Visible:0,Clip:1,Ellipsis:2},Ui=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Fi.Left,verticalAlign:Bi.Top,wordWrap:!0,overflow:zi.Visible,lineHeight:1.2});class $i{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(R.textCanvasSize,R.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,vi(this.frameMaxW_)),e.height=Math.max(e.height,vi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=vi(this.frameMaxW_),e.height=vi(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=xi(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===zi.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,vi(f)),s.height=Math.max(s.height,vi(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=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(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===zi.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Bi.Top:x=d;break;case Bi.Middle:x=d+(p-2*d-w)/2;break;case Bi.Bottom:x=p-w-d;break;default:x=d}x<0&&(x=0)}else x=d;let v=x;for(const t of l){let s;switch(e.align){case Fi.Left:s=d;break;case Fi.Center:s=f/2;break;case Fi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===zi.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(f,p,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Fi.Left:return"left";case Fi.Center:return"center";case Fi.Right:return"right"}}}const Di=Ci({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Si(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Pi(e.uiRect,e.entity):0});class Li{build(e){Z("Text",Ui);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new $i(t),s=e.world,i=new Map;e.addSystemToSchedule(ut.PreUpdate,gt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Ui));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Ui)){if(s.valid(e)&&s.has(e,le)){const t=s.get(e,le);s.insert(e,le,{texture:F,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=s.getEntitiesWithComponents([Ui]);for(const t of e){const e=s.get(t,Ui),r=s.has(t,di)?s.get(t,di):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Di.changed(a,o)){if(s.has(t,le)&&s.get(t,le).texture!==F)continue}fi(s,t);const l=r?{size:{x:Si(r,t),y:Pi(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,le);s.insert(t,le,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),i.set(t,Di.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Wi=new Li,Oi=0,Hi=1,Xi=te("UIMask",{enabled:!0,mode:Oi});function ji(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function Yi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,P=r*d-o*c,M=h*y-u*g,T=h*m-f*g,E=h*_-p*g,R=u*m-f*y,C=u*_-p*y,A=f*_-p*m;let I=w*A-x*C+v*R+b*E-S*T+P*M;return 0===I||(I=1/I,n[0]=(l*A-c*C+d*R)*I,n[1]=(r*C-i*A-o*R)*I,n[2]=(y*P-m*S+_*b)*I,n[3]=(f*S-u*P-p*b)*I,n[4]=(c*E-a*A-d*T)*I,n[5]=(s*A-r*E+o*T)*I,n[6]=(m*v-g*P-_*x)*I,n[7]=(h*P-f*v+p*x)*I,n[8]=(a*C-l*E+d*M)*I,n[9]=(i*E-s*C-o*M)*I,n[10]=(g*S-y*v+_*w)*I,n[11]=(u*v-h*S-p*w)*I,n[12]=(l*T-a*R-c*M)*I,n[13]=(s*R-i*T+r*M)*I,n[14]=(y*x-g*b-m*w)*I,n[15]=(h*b-u*x+f*w)*I),n}function Ni(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function Vi(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function Gi(e,t){return 2*Math.atan2(e,t)}function qi(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function Ki(e,t,n,s,i,r,o,a,l,c){const d=Gi(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function Ji(e,t,n,s,i,r,o){if(!e.has(t,di)||!e.has(t,re))return null;const a=e.get(t,di),l=e.get(t,re),c=Si(a,t)*l.worldScale.x,d=Pi(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),w=Gi(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-m*v,u+g*v+m*x],[h+y*x-m*v,u+y*v+m*x],[h+y*x-_*v,u+y*v+_*x],[h+g*x-_*v,u+g*v+_*x]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=qi(e,t,n,s,i,r,o);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function Qi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Xi]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Xi);n.enabled&&(h.add(e),n.mode===Hi?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;Ti(t,e,e=>{if(i.has(e)){if(t.get(e,Xi).mode===Oi)return n=!1,!0}return!1}),n&&d.push(e)}function h(s,d){const u=e.getChildEntities(n,s);for(const n of u){let s=d;if(i.has(n)){if(t.get(n,Xi).mode===Oi){const e=Ji(t,n,r,o,a,l,c);e&&(s=ji(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Ji(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Ti(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Zi{build(e){if(Z("UIMask",Xi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Qi(e.wasmModule,e.world))}}const er=new Zi,tr=te("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),nr=te("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),sr={Normal:0,Hovered:1,Pressed:2,Disabled:3},ir=Y("Button",{state:sr.Normal,transition:null});class rr{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}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 or=Me(new rr,"UIEvents");class ar{build(e){Z("UIRect",di);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){hi=e,ui=t}(n,s);e.addSystemToSchedule(ut.PreUpdate,gt([Te(Mt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(ut.PostUpdate,gt([Te(Mt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(ut.PostUpdate,gt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const lr=new ar;let cr=!1,dr=!1;function hr(e){cr=e}function ur(){return cr}function fr(){return!cr}function pr(e){dr=e}function gr(){return dr}const yr=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Yi(t,e),n=!1),e)}}();function mr(e,t,n,s){t.emit(n,s,n),Ti(e,n,i=>{if(!e.has(i,tr))return!1;const r=e.get(i,tr);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class _r{build(e){Z("Interactable",tr),Z("Button",ir);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new rr;e.insertResource(or,i);let r=null,o=null;e.addSystemToSchedule(ut.PreUpdate,gt([Te(bt),Te(Mt)],(e,a)=>{if(i.drain(),ur()&&!gr())return;const l=t.getEntitiesWithComponents([nr]);for(const e of l){const n=t.get(e,nr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,nr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;yr.update(a.viewProjection);const u=Ni(d,h,yr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const m=n.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,nr)){const e=t.get(r,nr);e.hovered=!1,t.insert(r,nr,e),i.emit(r,"hover_exit")}if(null!==_){Ei(t,_,nr);const e=t.get(_,nr);e.hovered=!0,t.insert(_,nr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,nr);e.pressed=!0,e.justPressed=!0,t.insert(_,nr,e),o=_,mr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,nr)){const e=t.get(o,nr);e.pressed=!1,e.justReleased=!0,t.insert(o,nr,e),mr(t,i,o,"release"),o===r&&mr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ut.Update,gt([],()=>{const e=t.getEntitiesWithComponents([ir]);for(const n of e){if(Ei(t,n,tr,{enabled:!0}),!t.has(n,nr))continue;const e=t.get(n,nr),s=t.get(n,ir),i=t.get(n,tr),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=sr.Pressed:e.hovered?s.state=sr.Hovered:s.state=sr.Normal:s.state=sr.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,le)){const r=t.get(n,le);r.color=_i(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,le,r)}}},{name:"ButtonSystem"}))}}const wr=new _r,xr=Y("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}),vr=Y("Focusable",{tabIndex:0,isFocused:!1});class br{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Sr=Me(new br,"FocusManager");class Pr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Z("TextInput",xr),ur()&&!gr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(R.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=0;const f=function(){if("undefined"==typeof document||!document.body)return null;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}();if(!f)return;const p=f;function g(){const t=e.getResource(Sr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,xr)?s:null}const y=()=>{l||null===g()||v()},m=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,xr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(or).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,xr);s.focused=!1,s.dirty=!0;e.getResource(Sr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,xr);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(or).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=n.get(t,xr);e.focused=!1,e.dirty=!0}e.getResource(Sr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let P=null;function M(e,l,d,h){(i.width<d||i.height<h)&&(i.width=vi(Math.max(i.width,d)),i.height=vi(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=xi(r,p,d-2*m);let t=m;for(const n of e)r.fillText(n,m,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,m,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=xi(r,l.value,d-2*m);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=m+r.measureText(c).width,n=m+o*y,s=y}else t=m+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,d,h),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,le);S.texture=b,S.size.x=d,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,le,S)}e.addSystemToSchedule(ut.Update,gt([Te(Sr)],e=>{const t=n.getEntitiesWithComponents([xr]);for(const e of t)Ei(n,e,vr,{tabIndex:0,isFocused:!1}),Ei(n,e,tr,{enabled:!0,blockRaycast:!0});const s=g();if(s!==P){if(null!==P&&n.valid(P)&&n.has(P,xr)){const e=n.get(P,xr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,xr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),P=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(ut.PreUpdate,gt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,xr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,xr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([xr,di]);for(const e of a){const t=n.get(e,xr);if(!t.dirty)continue;const s=n.get(e,di),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(fi(n,e),M(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Mr=new Pr,Tr={Simple:0,Sliced:1,Tiled:2,Filled:3},Er={Horizontal:0,Vertical:1},Rr={Left:0,Right:1,Bottom:2,Top:3},Cr=Y("Image",{texture:F,color:{r:1,g:1,b:1,a:1},imageType:Tr.Simple,fillMethod:Er.Horizontal,fillOrigin:Rr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ar=Ci({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Si(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Pi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Ir=new class{build(e){Z("Image",Cr);const t=e.world,n=new Map;e.addSystemToSchedule(ut.PreUpdate,gt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Cr)||n.delete(e);const e=t.getEntitiesWithComponents([Cr]);for(const s of e){const e=t.get(s,Cr),i=t.has(s,di)?t.get(s,di):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Ar.changed(o,r))continue;fi(t,s);const a=t.get(s,le);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Si(i,s),a.size.y=Pi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Tr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Er.Horizontal?e.fillOrigin===Rr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Rr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Tr.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,le,a),n.set(s,Ar.take(r))}else a.color.a=0,t.insert(s,le,a),n.set(s,Ar.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},kr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Fr=Y("ToggleGroup",{allowSwitchOff:!1});const Br=new class{build(e){Z("Toggle",kr),Z("ToggleGroup",Fr);const t=e.world,n=new Set;e.addSystemToSchedule(ut.Update,gt([Te(or)],e=>{const s=t.getEntitiesWithComponents([kr]);if(!ur()||gr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,kr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,kr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,kr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Ei(t,n,tr,{enabled:!0}),!t.has(n,nr))continue;const s=t.get(n,nr),i=t.get(n,kr),o=t.get(n,tr);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Fr);if(i.isOn&&o){if(!t.get(s,Fr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,kr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,kr);i.isOn&&(i.isOn=!1,t.insert(s,kr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,le)){const e=t.get(n,le);e.color=_i(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,le,e)}}}for(const e of s){const n=t.get(e,kr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,le)){const e=t.get(n.graphicEntity,le);e.enabled=n.isOn,t.insert(n.graphicEntity,le,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},zr=li,Ur=Y("ProgressBar",{value:0,fillEntity:0,direction:li.LeftToRight});function $r(e,t,n,s){if(!e.has(t,di))return;const i=e.get(t,di),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=ci(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,le)){const n=e.get(t,le);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,le,n))}if(e.has(t,re)){const n=e.get(t,re),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,re,n))}}class Dr{build(e){Z("ProgressBar",Ur);const t=e.world;e.addSystemToSchedule(ut.PreUpdate,gt([],()=>{const e=t.getEntitiesWithComponents([Ur,di]);for(const n of e){const e=t.get(n,Ur);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,di),i=Math.max(0,Math.min(1,e.value));mi(t,e.fillEntity,e.direction,i);const r=Si(s,n),o=Pi(s,n);$r(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Lr=new Dr,Wr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Or=Y("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const Hr=new class{build(e){Z("Draggable",Wr),Z("DragState",Or);const t=e.world,n=e.getResource(or);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ut.PreUpdate,gt([Te(bt),Te(Mt)],(e,o)=>{if(ur()&&!gr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Wr,nr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Wr).enabled)continue;if(t.get(s,nr).hovered){let e=0;t.has(s,le)&&(e=t.get(s,le).layer);const i=bi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Or)||t.insert(n,Or);const e=t.get(n,Or),r=t.get(n,re);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Or)){t.get(s,Or).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(s,Wr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Or).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Or))return void(r=null);const s=t.get(r,Or),i=t.get(r,Wr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,re)){const e=function(e,t,n,s){if(!e.has(t,ue))return{x:n,y:s};const i=e.get(t,ue).entity;if(!e.valid(i)||!e.has(i,re))return{x:n,y:s};const r=e.get(i,re),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Gi(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,re);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,re,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Xr=Y("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function jr(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function Yr(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const Nr=new class{build(e){Z("ScrollView",Xr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ut.PostUpdate,gt([Te(bt),Te(Mt),Te(Ae)],(e,i,r)=>{const o=ur()&&!gr(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Xr,di]);for(const r of l){Ei(t,r,Xi,{enabled:!0,mode:Oi});const l=t.get(r,Xr),c=t.get(r,di);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=Si(c,r),u=Pi(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,fe)){const e=t.get(l.contentEntity,fe).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,re))continue;const e=t.get(o,re);let a=0,l=0,c=.5,d=.5;if(t.has(o,di)){const e=t.get(o,di);a=Si(e,o)||e.size.x,l=Pi(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,le)){const e=t.get(o,le);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){Ei(t,r,tr,{enabled:!0,blockRaycast:!0});const n=t.has(r,nr)?t.get(r,nr):null;if(n?.justPressed&&(d.isDragging=!0,d.lastWorldX=s.x,d.lastWorldY=s.y,d.velocityX=0,d.velocityY=0),d.isDragging&&e.isMouseButtonDown(0)){const e=s.x-d.lastWorldX,t=s.y-d.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=jr(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=jr(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=jr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=jr(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Yr(l.scrollX,e,d.velocityX,.1,a);l.scrollX=t.value,d.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(d.velocityX)<Ai&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ai?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Yr(l.scrollY,e,d.velocityY,.1,a);l.scrollY=t.value,d.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(d.velocityY)<Ai&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ai?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,re)){const e=t.get(l.contentEntity,re),n=e.position.x,s=e.position.y;(isNaN(d.lastAppliedX)||Math.abs(n-d.lastAppliedX)>.01)&&(d.contentBaseX=n),(isNaN(d.lastAppliedY)||Math.abs(s-d.lastAppliedY)>.01)&&(d.contentBaseY=s),e.position.x=d.contentBaseX-l.scrollX,e.position.y=d.contentBaseY+l.scrollY,d.lastAppliedX=e.position.x,d.lastAppliedY=e.position.y,t.insert(l.contentEntity,re,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Vr=li,Gr=Y("Slider",{value:0,minValue:0,maxValue:1,direction:li.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function qr(e,t,n,s,i,r){const o=Si(s,i)*n.worldScale.x,a=Pi(s,i)*n.worldScale.y,l=Gi(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case li.LeftToRight:return o>0?(f-g)/o:0;case li.RightToLeft:return o>0?1-(f-g)/o:0;case li.BottomToTop:return a>0?(p-y)/a:0;case li.TopToBottom:return a>0?1-(p-y)/a:0}}function Kr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case li.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case li.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case li.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case li.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Jr{build(e){Z("Slider",Gr);const t=e.world;let n=null;e.addSystemToSchedule(ut.PreUpdate,gt([Te(bt),Te(Mt),Te(or)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Gr,di]);for(const o of r){const r=t.get(o,Gr),a=t.get(o,di);if(!ur()||gr()){if(t.has(o,re)){Ei(t,o,tr,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ei(t,r.handleEntity,tr,{enabled:!0,blockRaycast:!1});const l=t.get(o,re),c=t.has(o,nr)?t.get(o,nr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,nr)&&(d=t.get(r.handleEntity,nr).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=qr(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,Gr,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=Si(a,o),h=Pi(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(mi(t,r.fillEntity,r.direction,c),Ri(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,di)){const e=t.get(r.handleEntity,di);Kr(e,r.direction,c),t.insert(r.handleEntity,di,e),Ri(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Qr=new Jr;const Zr=new class{build(e){Z("Focusable",vr);const t=e.world,n=new br;e.insertResource(Sr,n),e.addSystemToSchedule(ut.Update,gt([Te(bt),Te(or)],(e,s)=>{if(ur()&&!gr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([vr]);for(const e of i){if(!t.has(e,nr))continue;t.get(e,nr).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,tr)){if(!t.get(n,tr).enabled)continue}const s=t.get(n,vr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,vr)){t.get(i,vr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,vr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},eo=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function to(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const no=new class{build(e){Z("SafeArea",eo);const t=e.world;let n=to(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=to(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=to(),s=!0});e.addSystemToSchedule(ut.PreUpdate,gt([Te(Mt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([eo,di]);for(const e of d){const s=t.get(e,eo),i=t.get(e,di),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,di,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},so=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let io=null;function ro(e,t){if(!io)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=io.get(e);n?n.renderer=t:io.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const oo=new class{build(e){Z("ListView",so);const t=e.world,n=new Map;io=n,e.addSystemToSchedule(ut.PostUpdate,gt([Te(bt)],e=>{const s=ur()&&!gr();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([so,di]);for(const r of i){Ei(t,r,tr,{enabled:!0,blockRaycast:!0}),Ei(t,r,Xi,{enabled:!0,mode:Oi});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,so),a=t.get(r,di),l=Pi(a,r),c=Si(a,r);if(!s){const n=t.has(r,nr)?t.get(r,nr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,ye,{value:`ListItem_${e}`}),t.insert(n,di,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,re)){const s=t.get(n,re);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,re,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},ao=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const lo=new class{build(e){Z("Dropdown",ao);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,re))return;const n=t.get(e,re);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,re,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,le)){const n=t.get(e,le);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,le,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,le),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Ii;t.insert(i,di,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,re,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,le,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*Ii;t.insert(r,ye,{value:`Option_${e}`}),t.insert(r,di,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Ii},offsetMax:{x:0,y:0},size:{x:o,y:Ii},pivot:{x:.5,y:.5}}),t.insert(r,re,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,le,{texture:F,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Ii},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,tr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,re,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,Ui,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Fi.Left,verticalAlign:Bi.Middle,wordWrap:!1,overflow:zi.Clip,lineHeight:1.2}),t.insert(c,di,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Ii},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Ui))return;const s=t.get(n,Ui);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Ui,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,tr)&&t.insert(e,tr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,le))){const s=t.get(e,le);t.insert(e,le,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,le))continue;const i=n===e.highlightIndex?{...ki}:{r:.95,g:.95,b:.95,a:1};t.insert(s,le,{texture:F,color:i,size:{x:e.ddWidth,y:Ii},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function u(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,nr))continue;if(t.get(n,nr).hovered)return!0}return!1}e.addSystemToSchedule(ut.Update,gt([Te(bt),Te(or)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=ur()&&!gr(),p=t.getEntitiesWithComponents([ao]);for(const g of p){const p=t.get(g,ao);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Ei(t,g,tr,{enabled:!0,blockRaycast:!0});const m=t.has(g,nr)?t.get(g,nr):null;if(m?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,nr))continue;if(t.get(n,nr).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,nr))continue;if(t.get(s,nr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},co=0,ho=0,uo=2,fo=Y("LayoutGroup",{direction:co,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:ho,reverseOrder:!1});const po=new class{build(e){Z("LayoutGroup",fo);const t=e.world;e.addSystemToSchedule(ut.PreUpdate,gt([],()=>{const e=t.getEntitiesWithComponents([fo,di,fe]);for(const n of e){const e=t.get(n,fo),s=t.get(n,di),i=t.get(n,fe);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,di)&&t.has(e,re)&&r.push({entity:e,rect:t.get(e,di)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Si(s,n),a=Pi(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===co;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Si(s.rect,s.entity),f=Pi(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*o+d.left+u+p*i,m=e.childAlignment===ho?(1-c)*a-d.top-(1-g)*f:e.childAlignment===uo?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===ho?-l*o+d.left+p*i:e.childAlignment===uo?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,m=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const _=t.get(s.entity,re);_.position.x=y,_.position.y=m,t.insert(s.entity,re,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};te("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),te("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class go{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ut.PostUpdate,gt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const yo=new go;async function mo(e,t,n){const s=e.getResource(Xs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function _o(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const wo=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),xo=Me(null,"PhysicsAPI");function vo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function bo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class So{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(wo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=_o(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([de]);for(const n of t){const t=e.world.get(n,de);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(ut.PostUpdate,gt([Te(Ae)],a=>{const l=o.getEntitiesWithComponents([we,re]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,we),l=o.get(i,re);if(t.has(i)){const e=n.get(i);!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(i,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 o=vo(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Po(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Se.Kinematic){const e=vo(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,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 i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,re);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,ue)){const t=e.world.get(o,ue);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,re)){const n=e.world.get(t.entity,re),s=vo(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=bo(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,re,d)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.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=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(wo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(xo,Mo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Po(e,t,n){const s=e.world;if(s.has(n,xe)){const e=s.get(n,xe);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,ve)){const e=s.get(n,ve);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,be)){const e=s.get(n,be);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 Mo{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(Mo.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)}}const To={nearest:0,linear:1},Eo={repeat:0,clamp:1,mirror:2};function Ro(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=To[s.filterMode??"linear"]??1,a=Eo[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Co(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 Ao(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Io(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=rn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=Ro(e,await n.loadPixels(r),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${r}`,e),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 i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let d={},h=null;if(i&&(h=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"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=on(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===Sn(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=Co(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=Ro(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...M},fixedTimestep:o?.fixedTimestep??T,subStepCount:o?.subStepCount??4};new So("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=rn(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=Sn(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=Ro(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=rn(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=zt.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=zt.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=rn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(n,c,u,f);const p=un(e.world,n);if(l&&e.hasResource(Xs))for(const t of p.values())e.world.insert(t,me,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=on(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=P);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,ge)?c.get(r,ge):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,re)){const e=Ao(c.get(r,re),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,d,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,u),t._free(_),t._free(w),n._free(c),n._free(d),n._free(h),n._free(f)}u&&t._free(u)}})}(e,t,i,h,s)}if(a){const t=e.getResource(Un);t&&t.setAddressableManifest(a)}}function ko(e,t,n){return{name:e,async setup(){await Io(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Fo{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=on(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===Sn(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=rn(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=Sn(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}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(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Bo="__preview__";class zo{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(Xs);t.register({name:Bo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Bo),this.loadPromise_=t.load(Bo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Fo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Io(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Bo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ce]);for(const s of n){if(e.get(s,ce).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([de]);for(const i of s){const s=e.get(i,de);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Xs).getScene(Bo),r=i?i.spawn():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},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,re,o);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:se.ColorAndDepth};e.insert(r,ce,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Xs);await e.switchTo(Bo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Uo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Fs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Fs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Fs.releaseRenderTarget(e._handle),Uo.create({width:t,height:n,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};var $o;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}($o||($o={}));class Do{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${$o[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case $o.Debug:console.debug(t,n);break;case $o.Info:console.log(t,n);break;case $o.Warn:console.warn(t,n);break;case $o.Error:console.error(t,n)}}}class Lo{constructor(){this.handlers_=[],this.minLevel_=$o.Info,this.addHandler(new Do)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log($o.Debug,e,t,n)}info(e,t,n){this.log($o.Info,e,t,n)}warn(e,t,n){this.log($o.Warn,e,t,n)}error(e,t,n){this.log($o.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Wo=new Lo;function Oo(){return Wo}function Ho(e){Wo.setMinLevel(e)}function Xo(e,t,n){Wo.debug(e,t,n)}function jo(e,t,n){Wo.info(e,t,n)}function Yo(e,t,n){Wo.warn(e,t,n)}function No(e,t,n){Wo.error(e,t,n)}const Vo={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Go={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},qo={Running:0,Paused:1,Completed:2,Cancelled:3},Ko={None:0,Restart:1,PingPong:2};class Jo{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Qo=null,Zo=null;function ea(e,t){Qo=e,Zo=t}function ta(){Qo=null,Zo=null}function na(){if(!Qo)throw new Error("Tween API not initialized");return Qo}function sa(){if(!Zo)throw new Error("Tween API not initialized");return Zo}const ia={to(e,t,n,s,i,r){const o=na(),a=sa(),l=r?.easing??Vo.Linear,c=r?.delay??0,d=r?.loop??Ko.None,h=r?.loopCount??0,u=o._anim_createTween(a,e,t,n,s,i,l,c,d,h);return new Jo(o,a,u)},cancel(e){na()._anim_cancelTween(sa(),e.entity)},cancelAll(e){na()._anim_cancelAllTweens(sa(),e)},update(e){na()._anim_updateTweens(sa(),e)}};class ra{constructor(){this.name="AnimationPlugin"}build(e){ea(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(ut.Update,gt([Te(Ae)],e=>{ia.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(ut.Update,gt([Te(Ae)],e=>{en(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ta()}}const oa=new ra;class aa{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function la(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function ca(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:r}=e,o=t.getResource(Un);o&&(o.registerEmbeddedAssets(s),o.setEmbeddedOnly(!0)),Gs(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await la(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await la(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=ko(r,i,{app:t,module:n,provider:new aa(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(Xs);d.register(c),d.setInitial(r),await d.load(r);const h=e.canvas.width/e.canvas.height;yn(t.world,h),t.run()}const da=[Wi,er,lr,Ir,Lr,wr,Hr,Nr,Qr,Br,Mr,Zr,no,oo,lo,po,yo],ha=[...da,oa];function ua(e,t){return function(e,t){const n=Vs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ts(e),kt(e),_s(e),Ss(e),Is(e),zs(e);const i=new Ds;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=Zs(e,s,t,i));const o=n.getResource(Mt);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(Mt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Fs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(Fs.resize(t,l),Ts.isInitialized()&&Ts.getPassCount()>0&&!Ts.isBypassed()&&Ts.resize(t,l),n.hasResource(Xs)){const e=n.getResource(Xs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Zs(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:qs,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Fs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ut.First,l),n.addSystemToSchedule(ut.Last,c),n.addPlugin(Dn),n.addPlugin(qn),n.addPlugin(Pt),n.addPlugin(Ns),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ha,...t})}e=p;export{Ne as Added,ra as AnimationPlugin,Vs as App,$n as AssetPlugin,Ln as AssetRefCounter,zn as AssetServer,Un as Assets,jt as AsyncCache,pe as BitmapText,Tt as BlendMode,Se as BodyType,xe as BoxCollider,ir as Button,sr as ButtonState,ce as Camera,de as Canvas,be as CapsuleCollider,Ve as Changed,fe as Children,ve as CircleCollider,se as ClearFlags,nt as Commands,it as CommandsInstance,y as DEFAULT_DESIGN_HEIGHT,g as DEFAULT_DESIGN_WIDTH,P as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,M as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,m as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,w as DEFAULT_SPRITE_SIZE,_ as DEFAULT_TEXT_CANVAS_SIZE,fs as DataType,Or as DragState,Wr as Draggable,rs as Draw,ao as Dropdown,Vo as EasingType,st as EntityCommands,ct as EventReader,ht as EventReaderInstance,at as EventRegistry,lt as EventWriter,dt as EventWriterInstance,li as FillDirection,Er as FillMethod,Rr as FillOrigin,Sr as FocusManager,br as FocusManagerState,vr as Focusable,$s as GLDebug,vs as Geometry,ft as GetWorld,k as INVALID_ENTITY,B as INVALID_FONT,z as INVALID_MATERIAL,F as INVALID_TEXTURE,Cr as Image,Tr as ImageType,bt as Input,St as InputPlugin,vt as InputState,tr as Interactable,so as ListView,oe as LocalTransform,$o as LogLevel,Lo as Logger,Ko as LoopMode,zt as Material,Yt as MaterialLoader,je as Mut,ye as Name,ue as Parent,Mo as Physics,wo as PhysicsEvents,So as PhysicsPlugin,Ts as PostProcess,Nn as PrefabServer,Vn as Prefabs,Gn as PrefabsPlugin,zo as PreviewPlugin,Ur as ProgressBar,zr as ProgressBarDirection,Dr as ProgressBarPlugin,ne as ProjectionType,Qe as Query,Ze as QueryInstance,et as Removed,tt as RemovedQueryInstance,Ds as RenderPipeline,Rs as RenderStage,Uo as RenderTexture,Fs as Renderer,Te as Res,Ee as ResMut,we as RigidBody,R as RuntimeConfig,eo as SafeArea,ie as ScaleMode,Xs as SceneManager,Hs as SceneManagerState,me as SceneOwner,ut as Schedule,Xr as ScrollView,Xt as ShaderSources,Gr as Slider,Vr as SliderDirection,Jr as SliderPlugin,ge as SpineAnimation,le as Sprite,Zt as SpriteAnimator,xt as SystemRunner,Ui as Text,Fi as TextAlign,xr as TextInput,Pr as TextInputPlugin,zi as TextOverflow,Li as TextPlugin,$i as TextRenderer,Bi as TextVerticalAlign,Ae as Time,kr as Toggle,re as Transform,ia as Tween,Jo as TweenHandle,qo as TweenState,Go as TweenTarget,Mt as UICameraInfo,rr as UIEventQueue,or as UIEvents,nr as UIInteraction,_r as UIInteractionPlugin,ar as UILayoutPlugin,Xi as UIMask,Zi as UIMaskPlugin,di as UIRect,go as UIRenderOrderPlugin,he as Velocity,Fo as WebAssetProvider,Xe as World,ae as WorldTransform,_t as addStartupSystem,mt as addSystem,wt as addSystemToSchedule,oa as animationPlugin,I as applyBuildRuntimeConfig,mi as applyDirectionalFill,C as applyRuntimeConfig,Dn as assetPlugin,Qt as clearAnimClips,us as clearDrawCallbacks,G as clearUserComponents,L as color,pi as computeFillAnchors,yi as computeFillSize,gi as computeHandleAnchors,ci as computeUIRectLayout,Qi as createMaskProcessor,ko as createRuntimeSceneConfig,ua as createWebApp,Xo as debug,Y as defineComponent,rt as defineEvent,Me as defineResource,gt as defineSystem,N as defineTag,No as error,Nt as extractAnimClipTexturePaths,mn as findEntityByName,Gs as flushPendingSystems,Mn as getAddressableType,Tn as getAddressableTypeByEditorType,Rn as getAllAssetExtensions,Jt as getAnimClip,kn as getAssetMimeType,Sn as getAssetTypeEntry,ee as getComponent,rn as getComponentAssetFieldDescriptors,sn as getComponentAssetFields,_e as getComponentDefaults,cn as getComponentEntityFields,on as getComponentSpineFieldDescriptor,An as getCustomExtensions,Pn as getEditorType,Oo as getLogger,t as getPlatform,s as getPlatformType,V as getUserComponent,In as getWeChatPackOptions,jo as info,ts as initDrawAPI,zs as initGLDebugAPI,_s as initGeometryAPI,kt as initMaterialAPI,ca as initPlayableRuntime,Ss as initPostProcessAPI,Is as initRendererAPI,ea as initTweenAPI,Pt as inputPlugin,On as instantiatePrefab,ji as intersectRects,Yi as invertMatrix4,J as isBuiltinComponent,Fn as isCustomExtension,ur as isEditor,En as isKnownAssetExtension,n as isPlatformInitialized,gr as isPlayMode,fr as isRuntime,Et as isTextureRef,i as isWeChat,r as isWeb,gn as loadComponent,_o as loadPhysicsModule,Io as loadRuntimeScene,un as loadSceneData,fn as loadSceneWithAssets,Cn as looksLikeAssetPath,Vt as parseAnimClipData,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ki as pointInOBB,Vi as pointInWorldRect,qn as prefabsPlugin,Lr as progressBarPlugin,W as quat,qt as registerAnimClip,Z as registerComponent,nn as registerComponentAssetFields,ln as registerComponentEntityFields,ds as registerDrawCallback,Wn as registerEmbeddedAssets,Ht as registerMaterialCallback,dn as remapEntityFields,Ns as sceneManagerPlugin,Ni as screenToWorld,hr as setEditorMode,ro as setListViewRenderer,Ho as setLogLevel,pr as setPlayMode,ze as setWasmErrorHandler,ns as shutdownDrawAPI,Us as shutdownGLDebugAPI,ws as shutdownGeometryAPI,Ft as shutdownMaterialAPI,Ps as shutdownPostProcessAPI,ks as shutdownRendererAPI,ta as shutdownTweenAPI,Qr as sliderPlugin,en as spriteAnimatorSystemUpdate,Mi as syncFillSpriteSize,Mr as textInputPlugin,Wi as textPlugin,Bn as toBuildPath,mo as transitionTo,wr as uiInteractionPlugin,lr as uiLayoutPlugin,er as uiMaskPlugin,da as uiPlugins,yo as uiRenderOrderPlugin,Kt as unregisterAnimClip,q as unregisterComponent,hs as unregisterDrawCallback,yn as updateCameraAspectRatio,U as vec2,$ as vec3,D as vec4,Yo as warn,js as wrapSceneSystem};
+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 i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(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(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}const p=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 loadImagePixels(e){const t=this.createImage();await new Promise((n,s)=>{t.crossOrigin="anonymous",t.onload=()=>n(),t.onerror=()=>s(new Error(`Failed to load image: ${e}`)),t.src=e});const n=this.createCanvas(t.width,t.height).getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(s.data.buffer)}}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),i=t=>e.onKeyUp(t.code),o=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},r=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;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",o),n.addEventListener("mousedown",r),document.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",i),n.removeEventListener("mousemove",o),n.removeEventListener("mousedown",r),document.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)}},m=1920,g=1080,_=100,y=512,w={x:100,y:100},x="Arial",v=24,b=1.2,S=.5,M=1/60,P={x:0,y:-9.81},T=1/60,E="default",C={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function R(e){e.Text&&(e.Text._default.fontFamily=C.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=C.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=C.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=C.canvasMatchWidthOrHeight)}const A={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function I(e,t){if(void 0!==t.maxDeltaTime&&(C.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(C.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(C.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(C.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(C.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");C.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(C.canvasScaleMode=A[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(C.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const k=0,F=4294967295,B=4294967295,z=0,U=(e=0,t=0)=>({x:e,y:t}),$=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),D=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),L=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),O=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function W(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(W);const t={};for(const n in e)t[n]=W(e[n]);return t}let H=0;function X(e,t){const n=++H,s=function(e){for(const t in e){const n=e[t];if(null!==n&&"object"==typeof n)return!0}return!1}(t);return{_id:Symbol(`Component_${n}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>s?e?{...W(t),...e}:W(t):e?{...t,...e}:{...t}}}function j(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Y(e,t){const n=Q.get(e)??j().get(e);if(n)return n;const s=X(e,t);return j().set(e,s),Q.set(e,s),K(e,t,!1),s}function N(e){const t=Q.get(e)??j().get(e);if(t)return t;const n=X(e,{});return j().set(e,n),Q.set(e,n),K(e,{},!0),n}function V(e){return j().get(e)}function q(){const e=j();for(const t of e.keys())Q.delete(t);e.clear()}function G(e){j().delete(e),Q.delete(e)}function K(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function J(e){return!0===e._builtin}const Q=new Map;function Z(e,t){Q.set(e,t)}function ee(e){return Q.get(e)??V(e)}function te(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Q.set(e,n),n}const ne={Perspective:0,Orthographic:1},se={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ie={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},oe=te("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),re=oe,ae=oe,le=te("Sprite",{texture:F,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,enabled:!0}),ce=te("Camera",{projectionType:ne.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:se.ColorAndDepth}),ue=te("Canvas",{designResolution:{x:m,y:g},pixelsPerUnit:100,scaleMode:ie.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=te("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),de=te("Parent",{entity:0}),fe=te("Children",{entities:[]}),pe=te("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B,enabled:!0}),me=te("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,enabled:!0}),ge=Y("Name",{value:""}),_e=Y("SceneOwner",{scene:"",persistent:!1});function ye(e){const t=ee(e);return t?W(t._default):null}const we=te("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),xe=te("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=te("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be=te("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Se={Static:0,Kinematic:1,Dynamic:2};let Me=0;function Pe(e,t){const n=++Me;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Te(e){return{_type:"res",_resource:e}}function Ee(e){return{_type:"res_mut",_resource:e}}class Ce{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_)}updateValue(e){this.value_=e}}class Re{constructor(){this.resources_=new Map,this.resMutPool_=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),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new Ce(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ae=Pe({delta:0,elapsed:0,frameCount:0},"Time");function Ie(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=ke(t[e]),o=ke(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Fe(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Be=null;function ze(e){Be=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Be&&Be(e,t)}function $e(e){let t=!1;for(const n of Object.keys(e)){const s=e[n];if(null!=s&&"object"==typeof s&&!Array.isArray(s)){if("r"in s&&"g"in s&&"b"in s&&"a"in s&&!("x"in s)){t=!0;break}}}if(!t)return e;const n={};for(const t of Object.keys(e)){const s=e[t];if(null==s||"object"!=typeof s||Array.isArray(s))n[t]=s;else{const e=s;n[t]="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}:s}}return n}let De=1;const Le=new WeakMap;function Oe(e){let t=Le.get(e);return void 0===t&&(t=De++,Le.set(e,t)),t}const We=[];function He(e,t=[],n=[]){We.length=0;for(const t of e)We.push(Oe(t));We.sort((e,t)=>e-t);let s=We.join(",");if(t.length>0){We.length=0;for(const e of t)We.push(Oe(e));We.sort((e,t)=>e-t),s+="|+"+We.join(",")}if(n.length>0){We.length=0;for(const e of n)We.push(Oe(e));We.sort((e,t)=>e-t),s+="|-"+We.join(",")}return s}class Xe{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ue(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ue(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Ue(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ue(t,`removeParent(entity=${e})`)}}insert(e,t,n){return J(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(J(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,$e(n))}catch(n){Ue(n,`set(${t._name}, entity=${e})`)}this.recordChangedTick_(t,e)}else this.getStorage(t).set(e,n),this.recordChangedTick_(t,e)}get(e,t){return J(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return J(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(J(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Ue(n,`tryGet(${t._name}, entity=${e})`),null}}return this.hasScript(e,t)?this.getScript(e,t):null}remove(e,t){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");J(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),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 e=Ie(t._name,t._default,s);if(e.length>0)throw new Error(Fe(t._name,e))}const i={...t._default,...s};let o=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);o=!n.has(e),n.add(e,$e(i))}catch(n){Ue(n,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return Ue(n,`getBuiltin(${t._name}, entity=${e})`),{...t._default}}}hasBuiltin(e,t){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(t._cppName).has(e)}catch(n){return Ue(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ue(n,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,n){let s;if(null!=n&&"object"==typeof n){const e={};for(const[t,s]of Object.entries(n))void 0!==s&&(e[t]=s);const i=Ie(t._name,t._default,e);if(i.length>0)throw new Error(Fe(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}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),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Q)if(J(s)&&!t.has(n))try{this.getBuiltinMethods(s._cppName).has(e)&&t.add(n)}catch{}const n=this.entityComponents_.get(e);if(n){const e=j();for(const s of n)for(const[n,i]of e)if(i._id===s){t.add(n);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],n=[],s){if(0===e.length&&0===t.length&&0===n.length)return this.getAllEntities();const i=s??He(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!J(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function je(e){return{_type:"mut",_component:e}}function Ye(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ne(e){return{_filterType:"added",_component:e}}function Ve(e){return{_filterType:"changed",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ge(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ke(e){return Ye(e)||qe(e)||Ge(e)?e._component:e}function Je(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),qe(e)?i.push({index:t,component:e._component}):Ge(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Je(e,[...t,...s],n),without:(...s)=>Je(e,t,[...n,...s])}}function Qe(...e){return Je(e)}class Ze{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Ke),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=He(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of n)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,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(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function et(e){return{_type:"removed",_component:e}}class tt{constructor(e,t,n){this.world_=e,this.component_=t,this.lastRunTick_=n}*[Symbol.iterator](){yield*this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}isEmpty(){return 0===this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_).length}toArray(){return this.world_.getRemovedEntitiesSince(this.component_,this.lastRunTick_)}}function nt(){return{_type:"commands"}}class st{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=J(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 it{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new st(this,null);return this.spawned_.push(e),e}entity(e){return new st(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_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function ot(e){return{_id:Symbol(`Event_${e}`),_name:e}}class rt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class at{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new rt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new rt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function lt(e){return{_type:"event_writer",_event:e}}function ct(e){return{_type:"event_reader",_event:e}}class ut{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class ht{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var dt;function ft(){return{_type:"get_world"}}!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"}(dt||(dt={}));let pt=0;function mt(e,t,n){const s=++pt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function gt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function _t(e){gt().push({schedule:dt.Update,system:e})}function yt(e){gt().push({schedule:dt.Startup,system:e})}function wt(e,t){gt().push({schedule:e,system:t})}class xt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof it&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ze(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new it(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new ut(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new ht(n)}case"removed":{const t=e;return new tt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class vt{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 bt=Pe(new vt,"Input");class St{constructor(e){this.target_=e??null}build(e){const n=new vt;e.insertResource(bt,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(dt.Last,mt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Mt=new St,Pt=Pe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Tt;function Et(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"}(Tt||(Tt={}));let Ct=null,Rt=null,At=1;const It=new Map;function kt(e){Ct=e,Rt=e.getResourceManager(),Ht()}function Ft(){0!==$t&&Ct&&(Ct._free($t),$t=0),It.clear(),At=1,Ut=!1,Lt.clear(),Ot=null,Rt=null,Ct=null}function Bt(){if(!Rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Rt}const zt={createShader:(e,t)=>Bt().createShader(e,t),releaseShader(e){e>0&&Bt().releaseShader(e)},create(e){const t=At++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Tt.Normal,depthTest:e.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};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),s.dirty_=!0,Ct?.invalidateMaterialCache(e))},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,Ct?.invalidateMaterialCache(e))},getBlendMode(e){const t=It.get(e);return t?.blendMode??Tt.Normal},setDepthTest(e,t){const n=It.get(e);n&&(n.depthTest=t,Ct?.invalidateMaterialCache(e))},getShader(e){const t=It.get(e);return t?.shader??0},release(e){It.delete(e),Ct?.invalidateMaterialCache(e)},isValid:e=>It.has(e),releaseAll(){It.clear(),Ct?.clearMaterialCache()},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??Tt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=It.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=At++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};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 Ut=!1,$t=0;const Dt=16384,Lt=new Map;let Ot=null;function Wt(e){const t=(0===$t&&Ct&&($t=Ct._malloc(Dt)),$t);if(0===t||!Ct)return{ptr:0,count:0};let n=0,s=0;const i=Ct.HEAPU8,o=Ct.HEAPU32,r=Ct.HEAPF32;for(const[a,l]of e){if(Et(l))continue;let e=Lt.get(a);e||(Ot||(Ot=new TextEncoder),e=Ot.encode(a),Lt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Dt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Dt} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.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++)r[t+n>>2]=d[e],n+=4;s++}return{ptr:t,count:s}}function Ht(){if(!Ct||Ut)return;Ct.materialDataProvider=(e,t,n,s,i)=>{const o=It.get(e);if(!o)return Ct.HEAPU32[t>>2]=0,Ct.HEAPU32[n>>2]=0,Ct.HEAPU32[s>>2]=0,void(Ct.HEAPU32[i>>2]=0);Ct.HEAPU32[t>>2]=o.shader,Ct.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Wt(o.uniforms);Ct.HEAPU32[s>>2]=r,Ct.HEAPU32[i>>2]=a},Ut=!0}const Xt={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 jt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return o.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}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()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Yt{constructor(e,t=""){this.cache_=new jt,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(zt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())zt.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 i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:zt.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 Nt(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Vt(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>({texture:n.get(e.texture)??0}))}}const qt=new Map;function Gt(e){qt.set(e.name,e)}function Kt(e){qt.delete(e)}function Jt(e){return qt.get(e)}function Qt(){qt.clear()}const Zt=Y("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function en(e,t){const n=e.getEntitiesWithComponents([Zt]);for(const s of n){const n=e.get(s,Zt);if(!n.enabled||!n.playing||!n.clip)continue;const i=qt.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,le)){const t=i.frames[n.currentFrame],o=e.get(s,le);o.texture=t.texture,e.insert(s,le,o)}a&&e.insert(s,Zt,n)}}class tn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static playSFX(e,t){const n=this.bufferCache_.get(e);return n?this.backend_.play(n,{bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0}):(this.preload(e).then(()=>{const n=this.bufferCache_.get(e);n&&this.backend_.play(n,{bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0})}),this.createPendingHandle())}static playBGM(e,t){const n=e=>{this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade):this.bgmHandle_&&this.bgmHandle_.stop(),this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:t?.fadeIn?0:t?.volume??1,loop:!0}),t?.fadeIn&&this.fadeIn(this.bgmHandle_,t.fadeIn,t?.volume??1)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&n(t)})}static stopBGM(e){this.bgmHandle_&&(e&&e>0?this.fadeOut(this.bgmHandle_,e):this.bgmHandle_.stop(),this.bgmHandle_=null)}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying&&requestAnimationFrame(i)};requestAnimationFrame(i)}static fadeOut(e,t){const n=performance.now(),s=()=>{const i=(performance.now()-n)/1e3,o=Math.min(i/t,1);e.setVolume(1-o),o<1&&e.isPlaying?requestAnimationFrame(s):e.stop()};requestAnimationFrame(s)}static createPendingHandle(){return{id:-1,stop(){},pause(){},resume(){},setVolume(){},setPan(){},setLoop(){},setPlaybackRate(){},isPlaying:!1,currentTime:0,duration:0}}}tn.mixer_=null,tn.bufferCache_=new Map,tn.bgmHandle_=null;const nn=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}]]);function sn(e,t){nn.set(e,t)}function on(e){const t=nn.get(e);if(!t)return[];const n=[];if(t.fields)for(const{field:e}of t.fields)n.push(e);return t.spine&&(n.push(t.spine.skeletonField),n.push(t.spine.atlasField)),n}function rn(e){return nn.get(e)?.fields??[]}function an(e){return nn.get(e)?.spine??null}const ln=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function cn(e,t){ln.set(e,t)}function un(e){return ln.get(e)}function hn(e,t){const n=ln.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function dn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,ge,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)hn(i,n),gn(e,t,i,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),i=n.get(s.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return n}function fn(e,t){return dn(e,t)}async function pn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of mn.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=nn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...mn.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=nn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=dn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const mn=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Nt(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Gt(Vt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await tn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function gn(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=ee(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function _n(e,t){const n=e.getEntitiesWithComponents([ce]);for(const s of n){const n=e.get(s,ce);n&&(n.aspectRatio=t,e.insert(s,ce,n))}}function yn(e,t){const n=e.getEntitiesWithComponents([ge]);for(const s of n){const n=e.get(s,ge);if(n&&n.value===t)return s}return null}const wn=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0}],xn={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},vn=new Map,bn=new Set;for(const e of wn)for(const t of e.extensions)vn.set(t,e),bn.add(t);function Sn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Mn(e){return vn.get(Sn(e))}function Pn(e){return Mn(e)?.editorType??"unknown"}function Tn(e){return Mn(e)?.addressableType??null}function En(e){for(const t of wn)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Cn(e){return bn.has(e.toLowerCase())}function Rn(){return bn}function An(e){return"string"==typeof e&&(!!e.includes("/")&&Cn(Sn(e)))}function In(){const e=[];for(const t of wn)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function kn(){return In().map(e=>({type:"suffix",value:e}))}function Fn(e){return xn[e.toLowerCase()]}function Bn(e){const t=Mn(e);return t?.wechatPackInclude??!1}function zn(e){const t=Mn(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}class Un{constructor(e){this.textureCache_=new jt,this.shaderCache_=new jt,this.jsonCache_=new jt,this.textCache_=new jt,this.binaryCache_=new jt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new jt,this.prefabCache_=new jt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(C.textCanvasSize,C.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Yt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}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))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}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);if(this.materialLoader_.releaseAll(),zt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.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)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===Mn(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=Mn(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?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 i=n?`${n}/${s}`:s;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of on(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=an(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}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 pn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(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)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(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"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?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 r=this.module_.GL,a=r.getNewId(r.textures);r.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 i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.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.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return zt.createShader(s,i)}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:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return zt.createShader(i,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://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(zn(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(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 r(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.getEmbedded(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 r(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.getEmbedded(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 r(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 i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}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 $n=Pe(null,"Assets");class Dn{build(e){const t=e.wasmModule;t?e.insertResource($n,new Un(t)):console.warn("AssetPlugin: No WASM module available")}}const Ln=new Dn;class On{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Wn(e,t){const n=e.getResource($n);n&&n.registerEmbeddedAssets(t)}async function Hn(e,t,n){const{entities:s,rootId:i}=await jn(t,n?.overrides??[],n,void 0,new Set),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,visible:e.visible}))},r=await pn(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const Xn=10;async function jn(e,t,n,s,i,o=0){if(o>Xn)throw new Error(`Prefab nesting depth exceeded ${Xn}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await jn(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?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};Yn(h.components,r),Nn(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Yn(e,t){for(const n of e){const e=un(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}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 Vn{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const n=this.assetServer_.resolveAddress(e),s=n?n.path:e,i=await this.assetServer_.loadPrefab(s,t?.baseUrl);return Hn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const qn=Pe(null,"Prefabs");class Gn{constructor(){this.name="PrefabsPlugin",this.dependencies=[$n]}build(e){const t=e.getResource($n);e.insertResource(qn,new Vn(e.world,t))}}const Kn=new Gn;let Jn=null,Qn=0,Zn=0,es=0;const ts=new Float32Array(256);function ns(e){Jn=e,Qn=Jn._malloc(64),Zn=Jn._malloc(64),es=Jn._malloc(1024)}function ss(){Jn&&(Qn&&(Jn._free(Qn),Qn=0),Zn&&(Jn._free(Zn),Zn=0),es&&(Jn._free(es),es=0)),Jn=null}function is(){if(!Jn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Jn}const os={r:1,g:1,b:1,a:1},rs={begin(e){const t=is();try{t.HEAPF32.set(e,Qn/4),t.draw_begin(Qn)}catch(e){Ue(e,"Draw.begin")}},end(){try{is().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,n,s=1){try{is().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ue(e,"Draw.line")}},rect(e,t,n,s=!0){try{is().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{is().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{is().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{is().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,n,s=os){try{is().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,n,s,i=os){try{is().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){is().draw_setLayer(e)},setDepth(e){is().draw_setDepth(e)},getDrawCallCount:()=>Jn?Jn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Jn?Jn.draw_getPrimitiveCount():0,setBlendMode(e){is().draw_setBlendMode(e)},setDepthTest(e){is().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=is();s.HEAPF32.set(n,Zn/4),s.draw_mesh(e,t,Zn)}catch(n){Ue(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=is(),i=zt.get(t);if(!i)return;if(rs.setBlendMode(i.blendMode),rs.setDepthTest(i.depthTest),0===i.uniforms.size)return void rs.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Zn/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=cs(t);if(!(s<0)){if(Et(n))ts[o++]=10,ts[o++]=s,ts[o++]=n.slot??e++,ts[o++]=n.textureId;else if("number"==typeof n)ts[o++]=1,ts[o++]=s,ts[o++]=n;else if(Array.isArray(n)){ts[o++]=n.length,ts[o++]=s;for(let e=0;e<n.length;e++)ts[o++]=n[e]}else"w"in n?(ts[o++]=4,ts[o++]=s,ts[o++]=n.x,ts[o++]=n.y,ts[o++]=n.z,ts[o++]=n.w):"z"in n?(ts[o++]=3,ts[o++]=s,ts[o++]=n.x,ts[o++]=n.y,ts[o++]=n.z):(ts[o++]=2,ts[o++]=s,ts[o++]=n.x,ts[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(ts.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Zn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),es/4),s.draw_meshWithUniforms(e,i.shader,Zn,es,o)}catch(n){Ue(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},as={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},ls=new Set;function cs(e){const t=as[e];return void 0!==t?t:(ls.has(e)||(ls.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(as).join(", ")}`)),-1)}const us=new Map;function hs(e,t,n){us.set(e,{fn:t,scene:n??""})}function ds(e){us.delete(e)}function fs(){us.clear()}var ps;!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"}(ps||(ps={}));let ms=null,gs=0,_s=0,ys=0;function ws(e){ms=e,gs=ms._malloc(262144),_s=ms._malloc(65536),ys=ms._malloc(256)}function xs(){ms&&(gs&&ms._free(gs),_s&&ms._free(_s),ys&&ms._free(ys),gs=0,_s=0,ys=0),ms=null}function vs(){if(!ms)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ms}const bs={create(e){const t=vs(),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,gs/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ys,i).set(o),t.geometry_init(n,gs,s,ys,i,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,_s,s).set(e.indices),t.geometry_setIndices16(n,_s,s)}else{new Uint32Array(t.HEAPU8.buffer,_s,s).set(e.indices),t.geometry_setIndices32(n,_s,s)}}return n},updateVertices(e,t,n=0){const s=vs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,gs/4),s.geometry_updateVertices(e,gs,i,n)},release(e){e>0&&vs().geometry_release(e)},isValid:e=>!(!ms||e<=0)&&ms.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return bs.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:ps.Float2},{name:"a_texCoord",type:ps.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 i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return bs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return bs.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:ps.Float2},{name:"a_texCoord",type:ps.Float2}],indices:new Uint16Array(r)})}};let Ss=null;function Ms(e){Ss=e}function Ps(){Ss&&Es.isInitialized()&&Es.shutdown(),Ss=null}function Ts(){if(!Ss)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ss}const Es={init(e,t){try{return Ts().postprocess_init(e,t)}catch(n){return Ue(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ts().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{Ts().postprocess_resize(e,t)}catch(n){Ue(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ts().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ts().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ts().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ts().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ts().postprocess_setUniformFloat(e,t,n)}catch(n){Ue(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ts().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){Ue(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ts().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{Ts().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return Ts().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ss)return!1;try{return Ss.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ts().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!Ss)return!0;try{return Ss.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>zt.createShader(Cs,"#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:()=>zt.createShader(Cs,"#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:()=>zt.createShader(Cs,"#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:()=>zt.createShader(Cs,"#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")},Cs="#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 Rs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Rs||(Rs={}));let As=null,Is=0;function ks(e){As=e,Is=As._malloc(64)}function Fs(){As&&Is&&(As._free(Is),Is=0),As=null}const Bs={init(e,t){As?.renderer_init(e,t)},resize(e,t){As?.renderer_resize(e,t)},begin(e,t){if(As&&Is)try{As.HEAPF32.set(e,Is/4),As.renderer_begin(Is,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{As?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{As?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(As)try{As.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(As)try{As.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(As)try{As.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){As?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>As?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){As?.renderer_releaseTarget(e)},getTargetTexture:e=>As?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>As?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){As?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){As?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){As?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){As?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>As?As.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>As?{drawCalls:As.renderer_getDrawCalls(),triangles:As.renderer_getTriangles(),sprites:As.renderer_getSprites(),text:As.renderer_getText(),spine:As.renderer_getSpine?.()??0,meshes:As.renderer_getMeshes(),culled:As.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let zs=null;function Us(e){zs=e}function $s(){zs=null}const Ds={enable(){zs?.gl_enableErrorCheck(!0)},disable(){zs?.gl_enableErrorCheck(!1)},check:e=>zs?.gl_checkErrors(e)??0,diagnose(){zs?.renderer_diagnose()}};class Ls{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Bs.resize(s,i),Es.isInitialized()&&Es.getPassCount()>0&&Es.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Bs.setViewport(0,0,s,i),Bs.clearBuffers(3),Bs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Bs.submitSprites(t),Bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bs.submitSpine(t),Bs.flush(),this.executeDrawCallbacks(n,o),Bs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o}=e;Bs.setViewport(s.x,s.y,s.w,s.h),Bs.setScissor(s.x,s.y,s.w,s.h,!0),Bs.clearBuffers(i),Bs.setScissor(0,0,0,0,!1),Bs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Bs.submitSprites(t),Bs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Bs.submitSpine(t),Bs.flush(),this.executeDrawCallbacks(n,o),Bs.end()}executeDrawCallbacks(e,t){const n=us;if(n.size>0){rs.begin(e);const s=[];for(const[e,i]of n.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),s.push(e)}rs.end();for(const e of s)ds(e)}}}const Os="__scene_transition_overlay__";class Ws{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class Hs{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,_e,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),hs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Es.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Es.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,_e)){const n=this.app_.world.get(e,_e);n.persistent=t,this.app_.world.insert(e,_e,n)}}}class Xs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??C.sceneTransitionDuration,i=t.color??{...C.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},hs(Os,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:n})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,n=this.activeScene_;(async()=>{try{n&&n!==e&&await this.unload(n,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,ds(Os),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ds(Os),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ws(t);this.scenes_.set(e,n);const s=new Hs(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource($n)?this.app_.getResource($n):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Ws(t);this.scenes_.set(e,n);const s=new Hs(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource($n)?this.app_.getResource($n):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(n,e,t,i),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),s})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const n=this.scenes_.get(e);if(!n)return;const s=this.contexts_.get(e);n.status="unloading",n.config.cleanup&&n.config.cleanup(s);const i=t?.keepPersistent??!0;for(const e of n.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,_e)){if(this.app_.world.get(e,_e).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ds(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Es.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource($n)&&(i.assetServer=this.app_.getResource($n));const o=await pn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,_e,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Ys(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const i=this.contexts_.get(t);n.setup&&await n.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource($n)?this.app_.getResource($n):null;if(n){for(const e of t.textureUrls)n.releaseTexture(e);for(const e of t.fontPaths)n.releaseFont(e);for(const e of t.spineKeys)n.releaseSpine(e)}for(const e of t.materialHandles)zt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,le)){const t=n.get(e,le);s.sprite=t.color.a,t.color.a=0,n.insert(e,le,t),i=!0}if(n.has(e,me)){const t=n.get(e,me);s.spine=t.color.a,t.color.a=0,n.insert(e,me,t),i=!0}if(n.has(e,pe)){const t=n.get(e,pe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,pe,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,le)){const t=n.get(e,le);t.color.a=s.sprite,n.insert(e,le,t)}if(void 0!==s.spine&&n.has(e,me)){const t=n.get(e,me);t.color.a=s.spine,n.insert(e,me,t)}if(void 0!==s.bitmapText&&n.has(e,pe)){const t=n.get(e,pe);t.color.a=s.bitmapText,n.insert(e,pe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Es.setEnabled(n,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,n]of this.scenes_)"running"===n.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const js=Pe(null,"SceneManager");function Ys(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(js).getSceneStatus(t)&&n._fn(...s)}}}const Ns=mt([Ee(js),Te(Ae)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vs={name:"SceneManager",build(e){const t=new Xs(e);e.insertResource(js,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(js),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(dt.Startup,n),e.addSystemToSchedule(dt.Last,Ns)}};class qs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new at,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(dt.Last);else{this.runSchedule(dt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(dt.FixedPreUpdate),this.runSchedule(dt.FixedUpdate),this.runSchedule(dt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(dt.PreUpdate),this.runSchedule(dt.Update),this.runSchedule(dt.PostUpdate),this.runSchedule(dt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Xe,this.resources_=new Re;for(const e of Object.values(dt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qs}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(dt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(dt.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return ze(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(js).register(e),this}setInitialScene(e){return this.getResource(js).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new xt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ae)||this.resources_.insert(Ae,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(dt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(dt.Last);else{this.runSchedule(dt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(dt.FixedPreUpdate),this.runSchedule(dt.FixedUpdate),this.runSchedule(dt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(dt.PreUpdate),this.runSchedule(dt.Update),this.runSchedule(dt.PostUpdate),this.runSchedule(dt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new xt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ae,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(dt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,fs();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[$s,Fs,Ps,xs,Ft,ss];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ae);t.delta=e,t.elapsed+=e,t.frameCount++}}function Gs(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Ks=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Js(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case ie.FixedWidth:return o;case ie.FixedHeight:return r;case ie.Expand:return Math.max(o,r);case ie.Shrink:return Math.min(o,r);case ie.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const Qs=[];function Zs(e){if(e<Qs.length)return Qs[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return Qs.push(t),t}function ei(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,_e);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,h=0;if(i.projectionType===ne.Orthographic){if(h=i.orthoSize,l){h=Js(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=ni(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=ii(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=ri(o.position.x,o.position.y,o.position.z),f=Zs(c.length);f.entity=e,f.viewProjection.set(li(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ti=new Float32Array(16);function ni(e,t,n,s,i,o){const r=ti;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const si=new Float32Array(16);function ii(e,t,n,s){const i=si;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const oi=new Float32Array(16);function ri(e,t,n){const s=oi;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}const ai=new Float32Array(16);function li(e,t){const n=ai;for(let s=0;s<4;s++)for(let i=0;i<4;i++)n[4*i+s]=e[0+s]*t[4*i+0]+e[4+s]*t[4*i+1]+e[8+s]*t[4*i+2]+e[12+s]*t[4*i+3];return n}const ci={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ui(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=d+s.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}const hi=te("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}});let di=null,fi=null;function pi(e,t){e.has(t,le)||e.insert(t,le,{texture:F,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})}function mi(e,t){switch(e){case ci.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ci.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case ci.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function gi(e,t){switch(e){case ci.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case ci.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case ci.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1-t}};default:return{anchorMin:{x:t,y:0},anchorMax:{x:t,y:1}}}}function _i(e,t,n,s){switch(e){case ci.BottomToTop:case ci.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function yi(e,t,n,s){if(!e.has(t,hi))return;const i=e.get(t,hi),o=mi(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,hi,i)}function wi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function xi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function vi(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(xi(r.charCodeAt(0))&&s.length>0&&xi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!xi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function bi(e){let t=1;for(;t<e;)t*=2;return t}function Si(e,t){let n=0,s=t;for(;e.has(s,de);){const t=e.get(s,de).entity;if(!e.valid(t))break;n++,s=t}return n}function Mi(e,t){if(di&&fi){const e=di.getUIRectComputedWidth(fi,t);if(e>0)return e}return e.size.x}function Pi(e,t){if(di&&fi){const e=di.getUIRectComputedHeight(fi,t);if(e>0)return e}return e.size.y}function Ti(e,t,n,s,i,o){if(!e.has(t,le))return;const r=e.get(t,le);let a,l;switch(n){case ci.BottomToTop:case ci.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,le,r))}function Ei(e,t,n){let s=t;for(;e.has(s,de);){const t=e.get(s,de).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ci(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ri(e,t,n,s,i){if(!e.has(t,hi))return;const o=e.get(t,hi),r=ui(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,le)){const n=e.get(t,le);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,le,n))}if(e.has(t,oe)){const n=e.get(t,oe);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,oe,n)}}function Ai(e){const t=Object.keys(e),n=t.map(t=>e[t]);return{take(e){const s={};for(let i=0;i<t.length;i++)s[t[i]]=n[i](e);return s},changed(e,s){for(let i=0;i<t.length;i++)if(e[t[i]]!==n[i](s))return!0;return!1},update(e,s){for(let i=0;i<t.length;i++)e[t[i]]=n[i](s)}}}const Ii=.1,ki=30,Fi={r:.3,g:.5,b:.8,a:1},Bi={Left:0,Center:1,Right:2},zi={Top:0,Middle:1,Bottom:2},Ui={Visible:0,Clip:1,Ellipsis:2},$i=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Bi.Left,verticalAlign:zi.Top,wordWrap:!0,overflow:Ui.Visible,lineHeight:1.2});class Di{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(C.textCanvasSize,C.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,bi(this.frameMaxW_)),e.height=Math.max(e.height,bi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=bi(this.frameMaxW_),e.height=bi(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=vi(n,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=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===Ui.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,bi(f)),s.height=Math.max(s.height,bi(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.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})`,i&&e.overflow===Ui.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case zi.Top:x=u;break;case zi.Middle:x=u+(p-2*u-w)/2;break;case zi.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let s;switch(e.align){case Bi.Left:s=u;break;case Bi.Center:s=f/2;break;case Bi.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===Ui.Clip&&n.restore();const b=n.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,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 i=this.renderText(t,n);return this.cache.set(e,i),i}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()}measureWidth(e){let t=0;for(const n of e)t=Math.max(t,this.ctx.measureText(n).width);return t}mapAlign(e){switch(e){case Bi.Left:return"left";case Bi.Center:return"center";case Bi.Right:return"right"}}}const Li=Ai({content:e=>e.text.content,fontFamily:e=>e.text.fontFamily,fontSize:e=>e.text.fontSize,colorR:e=>e.text.color.r,colorG:e=>e.text.color.g,colorB:e=>e.text.color.b,colorA:e=>e.text.color.a,align:e=>e.text.align,verticalAlign:e=>e.text.verticalAlign,wordWrap:e=>e.text.wordWrap,overflow:e=>e.text.overflow,lineHeight:e=>e.text.lineHeight,containerWidth:e=>e.uiRect?Mi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Pi(e.uiRect,e.entity):0});class Oi{build(e){Z("Text",$i);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Di(t),s=e.world,i=new Map;e.addSystemToSchedule(dt.PreUpdate,mt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,$i));for(const e of i.keys())if(!s.valid(e)||!s.has(e,$i)){if(s.valid(e)&&s.has(e,le)){const t=s.get(e,le);s.insert(e,le,{texture:F,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=s.getEntitiesWithComponents([$i]);for(const t of e){const e=s.get(t,$i),o=s.has(t,hi)?s.get(t,hi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Li.changed(a,r)){if(s.has(t,le)&&s.get(t,le).texture!==F)continue}pi(s,t);const l=o?{size:{x:Mi(o,t),y:Pi(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,le);s.insert(t,le,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,Li.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Wi=new Oi,Hi=0,Xi=1,ji=te("UIMask",{enabled:!0,mode:Hi});function Yi(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=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,i-n),h:Math.max(0,o-s)}}function Ni(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=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],_=e[14],y=e[15],w=s*l-i*a,x=s*c-o*a,v=s*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,R=d*y-p*g,A=f*y-p*_;let I=w*A-x*R+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*A-c*R+u*C)*I,n[1]=(o*R-i*A-r*C)*I,n[2]=(g*M-_*S+y*b)*I,n[3]=(f*S-d*M-p*b)*I,n[4]=(c*E-a*A-u*T)*I,n[5]=(s*A-o*E+r*T)*I,n[6]=(_*v-m*M-y*x)*I,n[7]=(h*M-f*v+p*x)*I,n[8]=(a*R-l*E+u*P)*I,n[9]=(i*E-s*R-r*P)*I,n[10]=(m*S-g*v+y*w)*I,n[11]=(d*v-h*S-p*w)*I,n[12]=(l*T-a*C-c*P)*I,n[13]=(s*C-i*T+o*P)*I,n[14]=(g*x-m*b-_*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function Vi(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*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 qi(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function Gi(e,t){return 2*Math.atan2(e,t)}function Ki(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function Ji(e,t,n,s,i,o,r,a,l,c){const u=Gi(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,g=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function Qi(e,t,n,s,i,o,r){if(!e.has(t,hi)||!e.has(t,oe))return null;const a=e.get(t,hi),l=e.get(t,oe),c=Mi(a,t)*l.worldScale.x,u=Pi(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-u*p,y=u*(1-p),w=Gi(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-_*v,d+m*v+_*x],[h+g*x-_*v,d+g*v+_*x],[h+g*x-y*v,d+g*v+y*x],[h+m*x-y*v,d+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Ki(e,t,n,s,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function Zi(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ji]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,ji);n.enabled&&(h.add(e),n.mode===Xi?(u.push(e),d.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;Ei(t,e,e=>{if(i.has(e)){if(t.get(e,ji).mode===Hi)return n=!1,!0}return!1}),n&&u.push(e)}function h(s,u){const d=e.getChildEntities(n,s);for(const n of d){let s=u;if(i.has(n)){if(t.get(n,ji).mode===Hi){const e=Qi(t,n,o,r,a,l,c);e&&(s=Yi(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=Qi(t,e,o,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Ei(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class eo{build(e){if(Z("UIMask",ji),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Zi(e.wasmModule,e.world))}}const to=new eo,no=te("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),so=te("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),io={Normal:0,Hovered:1,Pressed:2,Disabled:3},oo=Y("Button",{state:io.Normal,transition:null});class ro{constructor(){this.events_=[]}emit(e,t,n){const s=n??e;this.events_.push({entity:e,type:t,target:s,currentTarget:e})}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 ao=Pe(new ro,"UIEvents");class lo{build(e){Z("UIRect",hi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){di=e,fi=t}(n,s);e.addSystemToSchedule(dt.PreUpdate,mt([Te(Pt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(dt.PostUpdate,mt([Te(Pt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(dt.PostUpdate,mt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const co=new lo;let uo=!1,ho=!1;function fo(e){uo=e}function po(){return uo}function mo(){return!uo}function go(e){ho=e}function _o(){return ho}const yo=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Ni(t,e),n=!1),e)}}();function wo(e,t,n,s){t.emit(n,s,n),Ei(e,n,i=>{if(!e.has(i,no))return!1;const o=e.get(i,no);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class xo{build(e){Z("Interactable",no),Z("Button",oo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new ro;e.insertResource(ao,i);let o=null,r=null;e.addSystemToSchedule(dt.PreUpdate,mt([Te(bt),Te(Pt)],(e,a)=>{if(i.drain(),po()&&!_o())return;const l=t.getEntitiesWithComponents([so]);for(const e of l){const n=t.get(e,so);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,so,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;yo.update(a.viewProjection);const d=Vi(u,h,yo.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,d.x,d.y,p,m,g);const _=n.uiHitTest_getHitEntity(),y=4294967295===_?null:_;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,so)){const e=t.get(o,so);e.hovered=!1,t.insert(o,so,e),i.emit(o,"hover_exit")}if(null!==y){Ci(t,y,so);const e=t.get(y,so);e.hovered=!0,t.insert(y,so,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,so);e.pressed=!0,e.justPressed=!0,t.insert(y,so,e),r=y,wo(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,so)){const e=t.get(r,so);e.pressed=!1,e.justReleased=!0,t.insert(r,so,e),wo(t,i,r,"release"),r===o&&wo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(dt.Update,mt([],()=>{const e=t.getEntitiesWithComponents([oo]);for(const n of e){if(Ci(t,n,no,{enabled:!0}),!t.has(n,so))continue;const e=t.get(n,so),s=t.get(n,oo),i=t.get(n,no),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=io.Pressed:e.hovered?s.state=io.Hovered:s.state=io.Normal:s.state=io.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,le)){const o=t.get(n,le);o.color=wi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,le,o)}}},{name:"ButtonSystem"}))}}const vo=new xo,bo=Y("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}),So=Y("Focusable",{tabIndex:0,isFocused:!1});class Mo{constructor(){this.focusedEntity=null}focus(e){const t=this.focusedEntity;return this.focusedEntity=e,t}blur(){const e=this.focusedEntity;return this.focusedEntity=null,e}}const Po=Pe(new Mo,"FocusManager");class To{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Z("TextInput",bo),po()&&!_o())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(C.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=0;const f=function(){if("undefined"==typeof document||!document.body)return null;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}();if(!f)return;const p=f;function m(){const t=e.getResource(Po);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,bo)?s:null}const g=()=>{l||null===m()||v()},_=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,bo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(ao).emit(s,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const s=n.get(t,bo);s.focused=!1,s.dirty=!0;e.getResource(Po).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,bo);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(ao).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=n.get(t,bo);e.focused=!1,e.dirty=!0}e.getResource(Po).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,h){(i.width<u||i.height<h)&&(i.width=bi(Math.max(i.width,u)),i.height=bi(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=vi(o,p,u-2*_);let t=_;for(const n of e)o.fillText(n,_,t),t+=g}else{const e=(h-l.fontSize)/2;o.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=vi(o,l.value,u-2*_);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=_+o.measureText(c).width,n=_+r*g,s=g}else t=_+o.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,n,2,s)}o.restore();const y=o.getImageData(0,0,u,h),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,h,r,w.length,1,!0);s.set(e,b);const S=n.get(e,le);S.texture=b,S.size.x=u,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,le,S)}e.addSystemToSchedule(dt.Update,mt([Te(Po)],e=>{const t=n.getEntitiesWithComponents([bo]);for(const e of t)Ci(n,e,So,{tabIndex:0,isFocused:!1}),Ci(n,e,no,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,bo)){const e=n.get(M,bo);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,bo);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(dt.PreUpdate,mt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,bo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,bo)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([bo,hi]);for(const e of a){const t=n.get(e,bo);if(!t.dirty)continue;const s=n.get(e,hi),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(pi(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Eo=new To,Co={Simple:0,Sliced:1,Tiled:2,Filled:3},Ro={Horizontal:0,Vertical:1},Ao={Left:0,Right:1,Bottom:2,Top:3},Io=Y("Image",{texture:F,color:{r:1,g:1,b:1,a:1},imageType:Co.Simple,fillMethod:Ro.Horizontal,fillOrigin:Ao.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),ko=Ai({texture:e=>e.image.texture,colorR:e=>e.image.color.r,colorG:e=>e.image.color.g,colorB:e=>e.image.color.b,colorA:e=>e.image.color.a,layer:e=>e.image.layer,material:e=>e.image.material,imageType:e=>e.image.imageType,fillMethod:e=>e.image.fillMethod,fillOrigin:e=>e.image.fillOrigin,fillAmount:e=>e.image.fillAmount,tileSizeX:e=>e.image.tileSize.x,tileSizeY:e=>e.image.tileSize.y,rectWidth:e=>e.uiRect?Mi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Pi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Fo=new class{build(e){Z("Image",Io);const t=e.world,n=new Map;e.addSystemToSchedule(dt.PreUpdate,mt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Io)||n.delete(e);const e=t.getEntitiesWithComponents([Io]);for(const s of e){const e=t.get(s,Io),i=t.has(s,hi)?t.get(s,hi):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!ko.changed(r,o))continue;pi(t,s);const a=t.get(s,le);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Mi(i,s),a.size.y=Pi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Co.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Ro.Horizontal?e.fillOrigin===Ao.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Ao.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===Co.Tiled&&e.tileSize.x>0&&e.tileSize.y>0&&(a.uvScale.x=a.size.x/e.tileSize.x,a.uvScale.y=a.size.y/e.tileSize.y);t.insert(s,le,a),n.set(s,ko.take(o))}else a.color.a=0,t.insert(s,le,a),n.set(s,ko.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Bo=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),zo=Y("ToggleGroup",{allowSwitchOff:!1});const Uo=new class{build(e){Z("Toggle",Bo),Z("ToggleGroup",zo);const t=e.world,n=new Set;e.addSystemToSchedule(dt.Update,mt([Te(ao)],e=>{const s=t.getEntitiesWithComponents([Bo]);if(!po()||_o()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Bo);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Bo,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Bo);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ci(t,n,no,{enabled:!0}),!t.has(n,so))continue;const s=t.get(n,so),i=t.get(n,Bo),r=t.get(n,no);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,zo);if(i.isOn&&r){if(!t.get(s,zo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Bo,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Bo);i.isOn&&(i.isOn=!1,t.insert(s,Bo,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,le)){const e=t.get(n,le);e.color=wi(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,le,e)}}}for(const e of s){const n=t.get(e,Bo);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,le)){const e=t.get(n.graphicEntity,le);e.enabled=n.isOn,t.insert(n.graphicEntity,le,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},$o=ci,Do=Y("ProgressBar",{value:0,fillEntity:0,direction:ci.LeftToRight});function Lo(e,t,n,s){if(!e.has(t,hi))return;const i=e.get(t,hi),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=ui(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,le)){const n=e.get(t,le);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,le,n))}if(e.has(t,oe)){const n=e.get(t,oe),s=n.position;s.x===l.originX&&s.y===l.originY||(n.position={x:l.originX,y:l.originY,z:s.z},e.insert(t,oe,n))}}class Oo{build(e){Z("ProgressBar",Do);const t=e.world;e.addSystemToSchedule(dt.PreUpdate,mt([],()=>{const e=t.getEntitiesWithComponents([Do,hi]);for(const n of e){const e=t.get(n,Do);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,hi),i=Math.max(0,Math.min(1,e.value));yi(t,e.fillEntity,e.direction,i);const o=Mi(s,n),r=Pi(s,n);Lo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Wo=new Oo,Ho=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Xo=Y("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});const jo=new class{build(e){Z("Draggable",Ho),Z("DragState",Xo);const t=e.world,n=e.getResource(ao);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(dt.PreUpdate,mt([Te(bt),Te(Pt)],(e,r)=>{if(po()&&!_o())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ho,so]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,Ho).enabled)continue;if(t.get(s,so).hovered){let e=0;t.has(s,le)&&(e=t.get(s,le).layer);const i=Si(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Xo)||t.insert(n,Xo);const e=t.get(n,Xo),o=t.get(n,oe);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Xo)){t.get(s,Xo).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,Ho);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,Xo).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Xo))return void(o=null);const s=t.get(o,Xo),i=t.get(o,Ho),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=h.x,u=h.y;const d=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-d,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,oe)){const e=function(e,t,n,s){if(!e.has(t,de))return{x:n,y:s};const i=e.get(t,de).entity;if(!e.valid(i)||!e.has(i,oe))return{x:n,y:s};const o=e.get(i,oe),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Gi(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,oe);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,oe,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Yo=Y("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function No(e,t,n,s){return s<=0?1:e<t?Math.max(0,1-(t-e)/s):e>n?Math.max(0,1-(e-n)/s):1}function Vo(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}const qo=new class{build(e){Z("ScrollView",Yo);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(dt.PostUpdate,mt([Te(bt),Te(Pt),Te(Ae)],(e,i,o)=>{const r=po()&&!_o(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Yo,hi]);for(const o of l){Ci(t,o,ji,{enabled:!0,mode:Hi});const l=t.get(o,Yo),c=t.get(o,hi);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const h=Mi(c,o),d=Pi(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,fe)){const e=t.get(l.contentEntity,fe).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,oe))continue;const e=t.get(r,oe);let a=0,l=0,c=.5,u=.5;if(t.has(r,hi)){const e=t.get(r,hi);a=Mi(e,r)||e.size.x,l=Pi(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,le)){const e=t.get(r,le);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<n&&(n=h),d>s&&(s=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Ci(t,o,no,{enabled:!0,blockRaycast:!0});const n=t.has(o,so)?t.get(o,so):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=No(l.scrollX,0,m,h);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=No(l.scrollY,0,g,d);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=No(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=No(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=Vo(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Ii&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ii?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=Vo(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Ii&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ii?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,oe)){const e=t.get(l.contentEntity,oe),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,oe,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Go=ci,Ko=Y("Slider",{value:0,minValue:0,maxValue:1,direction:ci.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Jo(e,t,n,s,i,o){const r=Mi(s,i)*n.worldScale.x,a=Pi(s,i)*n.worldScale.y,l=Gi(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-n.worldPosition.x,d=t-n.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case ci.LeftToRight:return r>0?(f-m)/r:0;case ci.RightToLeft:return r>0?1-(f-m)/r:0;case ci.BottomToTop:return a>0?(p-g)/a:0;case ci.TopToBottom:return a>0?1-(p-g)/a:0}}function Qo(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case ci.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case ci.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case ci.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case ci.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Zo{build(e){Z("Slider",Ko);const t=e.world;let n=null;e.addSystemToSchedule(dt.PreUpdate,mt([Te(bt),Te(Pt),Te(ao)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([Ko,hi]);for(const r of o){const o=t.get(r,Ko),a=t.get(r,hi);if(!po()||_o()){if(t.has(r,oe)){Ci(t,r,no,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ci(t,o.handleEntity,no,{enabled:!0,blockRaycast:!1});const l=t.get(r,oe),c=t.has(r,so)?t.get(r,so):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,so)&&(u=t.get(o.handleEntity,so).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=Jo(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,Ko,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Mi(a,r),h=Pi(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(yi(t,o.fillEntity,o.direction,c),Ri(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,hi)){const e=t.get(o.handleEntity,hi);Qo(e,o.direction,c),t.insert(o.handleEntity,hi,e),Ri(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const er=new Zo;const tr=new class{build(e){Z("Focusable",So);const t=e.world,n=new Mo;e.insertResource(Po,n),e.addSystemToSchedule(dt.Update,mt([Te(bt),Te(ao)],(e,s)=>{if(po()&&!_o())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([So]);for(const e of i){if(!t.has(e,so))continue;t.get(e,so).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,no)){if(!t.get(n,no).enabled)continue}const s=t.get(n,So);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,So)){t.get(i,So).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,So).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},nr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function sr(){return i()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:n,screenWidth:s,screenHeight:i}=t;return{top:n.top,bottom:i-n.bottom,left:n.left,right:s-n.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const ir=new class{build(e){Z("SafeArea",nr);const t=e.world;let n=sr(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=sr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=sr(),s=!0});e.addSystemToSchedule(dt.PreUpdate,mt([Te(Pt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([nr,hi]);for(const e of u){const s=t.get(e,nr),i=t.get(e,hi),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,hi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},or=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let rr=null;function ar(e,t){if(!rr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=rr.get(e);n?n.renderer=t:rr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const lr=new class{build(e){Z("ListView",or);const t=e.world,n=new Map;rr=n,e.addSystemToSchedule(dt.PostUpdate,mt([Te(bt)],e=>{const s=po()&&!_o();for(const[e,s]of n)if(!t.valid(e)){for(const e of s.itemEntities.values())t.valid(e)&&t.despawn(e);n.delete(e)}const i=t.getEntitiesWithComponents([or,hi]);for(const o of i){Ci(t,o,no,{enabled:!0,blockRaycast:!0}),Ci(t,o,ji,{enabled:!0,mode:Hi});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,or),a=t.get(o,hi),l=Pi(a,o),c=Mi(a,o);if(!s){const n=t.has(o,so)?t.get(o,so):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=d)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<d;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,ge,{value:`ListItem_${e}`}),t.insert(n,hi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,oe)){const s=t.get(n,oe);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,oe,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},cr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const ur=new class{build(e){Z("Dropdown",cr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,oe))return;const n=t.get(e,oe);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,oe,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,le)){const n=t.get(e,le);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,le,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,le),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*ki;t.insert(i,hi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,oe,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,le,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*ki;t.insert(o,ge,{value:`Option_${e}`}),t.insert(o,hi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*ki},offsetMax:{x:0,y:0},size:{x:r,y:ki},pivot:{x:.5,y:.5}}),t.insert(o,oe,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,le,{texture:F,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:ki},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,no,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,oe,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,$i,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Bi.Left,verticalAlign:zi.Middle,wordWrap:!1,overflow:Ui.Clip,lineHeight:1.2}),t.insert(c,hi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:ki},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}h(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,$i))return;const s=t.get(n,$i);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,$i,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,no)&&t.insert(e,no,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,le))){const s=t.get(e,le);t.insert(e,le,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function h(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,le))continue;const i=n===e.highlightIndex?{...Fi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,le,{texture:F,color:i,size:{x:e.ddWidth,y:ki},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,so))continue;if(t.get(n,so).hovered)return!0}return!1}e.addSystemToSchedule(dt.Update,mt([Te(bt),Te(ao)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=po()&&!_o(),p=t.getEntitiesWithComponents([cr]);for(const m of p){const p=t.get(m,cr);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Ci(t,m,no,{enabled:!0,blockRaycast:!0});const _=t.has(m,so)?t.get(m,so):null;if(_?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,so))continue;if(t.get(n,so).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,so))continue;if(t.get(s,so).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(_?.hovered||d(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},hr=0,dr=0,fr=2,pr=Y("LayoutGroup",{direction:hr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:dr,reverseOrder:!1});const mr=new class{build(e){Z("LayoutGroup",pr);const t=e.world;e.addSystemToSchedule(dt.PreUpdate,mt([],()=>{const e=t.getEntitiesWithComponents([pr,hi,fe]);for(const n of e){const e=t.get(n,pr),s=t.get(n,hi),i=t.get(n,fe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,hi)&&t.has(e,oe)&&o.push({entity:e,rect:t.get(e,hi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Mi(s,n),a=Pi(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===hr;let d=0;for(let n=0;n<o.length;n++){const s=o[n],i=Mi(s.rect,s.entity),f=Pi(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,_;h?(g=-l*r+u.left+d+p*i,_=e.childAlignment===dr?(1-c)*a-u.top-(1-m)*f:e.childAlignment===fr?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,n<o.length-1&&(d+=e.spacing)):(g=e.childAlignment===dr?-l*r+u.left+p*i:e.childAlignment===fr?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,_=(1-c)*a-u.top-d-(1-m)*f,d+=f,n<o.length-1&&(d+=e.spacing));const y=t.get(s.entity,oe);y.position.x=g,y.position.y=_,t.insert(s.entity,oe,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};te("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),te("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class gr{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(dt.PostUpdate,mt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const _r=new gr;async function yr(e,t,n){const s=e.getResource(js);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function wr(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const xr=Pe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),vr=Pe(null,"PhysicsAPI");function br(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Sr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Mr{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(xr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=wr(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([ue]);for(const n of t){const t=e.world.get(n,ue);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(dt.PostUpdate,mt([Te(Ae)],a=>{const l=r.getEntitiesWithComponents([we,oe]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,we),l=r.get(i,oe);if(t.has(i)){const e=n.get(i);!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(i,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 r=br(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Pr(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Se.Kinematic){const e=br(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,oe);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,de)){const t=e.world.get(r,de);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,oe)){const n=e.world.get(t.entity,oe),s=br(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);h=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),d=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=h,u.position.y=d;const p=Sr(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,oe,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;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(xr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(vr,Tr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Pr(e,t,n){const s=e.world;if(s.has(n,xe)){const e=s.get(n,xe);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,ve)){const e=s.get(n,ve);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,be)){const e=s.get(n,be);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 Tr{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(Tr.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)}}const Er={nearest:0,linear:1},Cr={repeat:0,clamp:1,mirror:2};function Rr(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Er[s.filterMode??"linear"]??1,a=Cr[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Ar(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 Ir(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(_+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*r,(y-x)*r,(1-(p+_))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function kr(e,t,n,s,i,o,r,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=rn(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=Rr(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=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 i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let u={},h=null;if(i&&(h=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"])}}(i),u=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=an(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===Mn(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),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,r);if(t._free(h),f<0)continue;o[a]=f;const p=Ar(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=Rr(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,h,n,s)),o){const t={gravity:r?.gravity??{...P},fixedTimestep:r?.fixedTimestep??T,subStepCount:r?.subStepCount??4};new Mr("",t,()=>Promise.resolve(o)).build(e)}const d=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=rn(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=Mn(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=Rr(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=rn(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=zt.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=zt.createFromAsset(e,r)}catch{n[o]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=rn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(n,c,d,f);const p=fn(e.world,n);if(l&&e.hasResource(js))for(const t of p.values())e.world.insert(t,_e,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=an(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,u,p);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=M);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,me)?c.get(o,me):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(o,oe)){const e=Ir(c.get(o,oe),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,h,f);const p=n.HEAPU32[h>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),_=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,i,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,i,h,s)}if(a){const t=e.getResource($n);t&&t.setAddressableManifest(a)}}function Fr(e,t,n){return{name:e,async setup(){await kr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Br{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=an(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===Mn(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=rn(e.type);for(const n of o){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=Mn(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.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(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}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(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const zr="__preview__";class Ur{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(js);t.register({name:zr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(zr),this.loadPromise_=t.load(zr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Br(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await kr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,zr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([ce]);for(const s of n){if(e.get(s,ce).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([ue]);for(const i of s){const s=e.get(i,ue);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(js).getScene(zr),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,oe,r);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:se.ColorAndDepth};e.insert(o,ce,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(js);await e.switchTo(zr),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const $r={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Bs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Bs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Bs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Bs.releaseRenderTarget(e._handle),$r.create({width:t,height:n,depth:!0})),begin(e,t){Bs.begin(t,e._handle)},end(){Bs.end()},getDepthTexture:e=>Bs.getTargetDepthTexture(e._handle)};var Dr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Dr||(Dr={}));class Lr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Dr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Dr.Debug:console.debug(t,n);break;case Dr.Info:console.log(t,n);break;case Dr.Warn:console.warn(t,n);break;case Dr.Error:console.error(t,n)}}}class Or{constructor(){this.handlers_=[],this.minLevel_=Dr.Info,this.addHandler(new Lr)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,n){this.log(Dr.Debug,e,t,n)}info(e,t,n){this.log(Dr.Info,e,t,n)}warn(e,t,n){this.log(Dr.Warn,e,t,n)}error(e,t,n){this.log(Dr.Error,e,t,n)}log(e,t,n,s){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:n,data:s};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Wr=new Or;function Hr(){return Wr}function Xr(e){Wr.setMinLevel(e)}function jr(e,t,n){Wr.debug(e,t,n)}function Yr(e,t,n){Wr.info(e,t,n)}function Nr(e,t,n){Wr.warn(e,t,n)}function Vr(e,t,n){Wr.error(e,t,n)}const qr={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},Gr={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},Kr={Running:0,Paused:1,Completed:2,Cancelled:3},Jr={None:0,Restart:1,PingPong:2};class Qr{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Zr=null,ea=null;function ta(e,t){Zr=e,ea=t}function na(){Zr=null,ea=null}function sa(){if(!Zr)throw new Error("Tween API not initialized");return Zr}function ia(){if(!ea)throw new Error("Tween API not initialized");return ea}const oa={to(e,t,n,s,i,o){const r=sa(),a=ia(),l=o?.easing??qr.Linear,c=o?.delay??0,u=o?.loop??Jr.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new Qr(r,a,d)},cancel(e){sa()._anim_cancelTween(ia(),e.entity)},cancelAll(e){sa()._anim_cancelAllTweens(ia(),e)},update(e){sa()._anim_updateTweens(ia(),e)}};class ra{constructor(){this.name="AnimationPlugin"}build(e){ta(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(dt.Update,mt([Te(Ae)],e=>{oa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(dt.Update,mt([Te(Ae)],e=>{en(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){na()}}const aa=new ra;class la{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=t.volume??1,this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof la?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class ca{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new la(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new la(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new la(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new la(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new la(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new la(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class ua{constructor(e,t=16){this.pool_=[],this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,priority:0,startTime:0}}acquire(e=0){let t=this.pool_.find(e=>!e.inUse);return t||(t=this.createNode(),this.pool_.push(t)),t.inUse=!0,t.priority=e,t.startTime=this.context_.currentTime,t.gain.gain.value=1,t.panner.pan.value=0,t}release(e){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0}get activeCount(){return this.pool_.filter(e=>e.inUse).length}get capacity(){return this.pool_.length}}var ha;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(ha||(ha={}));const da={model:ha.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function fa(e,t=da){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);switch(n){case ha.Linear:return 1-(Math.min(Math.max(r,s),i)-s)/(i-s);case ha.Inverse:return s/Math.max(r,s);case ha.Exponential:return Math.pow(Math.max(r,s)/s,-o);default:return 1}}function pa(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const ma=Y("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:ha.Inverse,rolloff:1,priority:0,enabled:!0}),ga=Y("AudioListener",{enabled:!0});class _a{constructor(e,t,n,s,i){this.playing_=!0,this.id=e,this.source_=t,this.poolNode_=n,this.pool_=s,this.context_=i}stop(){this.playing_=!1,this.pool_.release(this.poolNode_)}pause(){this.playing_&&(this.playing_=!1,this.source_.playbackRate.value=0)}resume(){this.playing_||(this.playing_=!0,this.source_.playbackRate.value=1)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.source_.loop=e}setPlaybackRate(e){this.source_.playbackRate.value=e}get isPlaying(){return this.playing_}get currentTime(){return this.playing_?this.context_.currentTime-this.poolNode_.startTime:0}get duration(){return this.source_.buffer?.duration??0}markEnded(){this.playing_=!1}}class ya{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.nextBufferId_=0,this.nextHandleId_=0}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new ca(this.context_,e.mixerConfig),this.pool_=new ua(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e)};document.addEventListener("touchstart",e,{once:!0}),document.addEventListener("mousedown",e,{once:!0}),document.addEventListener("keydown",e,{once:!0})}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=await fetch(e),n=await t.arrayBuffer(),s=await this.context_.decodeAudioData(n),i=++this.nextBufferId_;return this.buffers_.set(i,s),{id:i,duration:s.duration}}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const n=this.buffers_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=this.pool_.acquire(t.priority??0),i=this.context_.createBufferSource();i.buffer=n,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(s.gain),s.source=i,s.gain.gain.value=t.volume??1,s.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;s.panner.connect(r.node),i.start(0,t.startOffset??0);const a=++this.nextHandleId_,l=new _a(a,i,s,this.pool_,this.context_);return i.onended=()=>{i.loop||(l.markEnded(),this.pool_.release(s),l.onEnd?.())},l}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.context_?.close(),this.context_=null}}class wa{constructor(e,t,n){this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class xa{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}async initialize(){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.src=n,s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.autoplay=!0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new wa(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function va(){return i()?new xa:new ya}class ba{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const t=va();t.initialize();let n=null;t instanceof ya&&(n=t.mixer),tn.init(t,n);const s=new Map;e.addSystemToSchedule(dt.PreUpdate,mt([Te(Ae)],n=>{const i=e.world;let o=0,r=0;const a=i.getEntitiesWithComponents([ga,ae]);for(const e of a){if(i.get(e,ga).enabled){const t=i.get(e,ae);o=t.position.x,r=t.position.y;break}}const l=i.getEntitiesWithComponents([ma,ae]);for(const e of l){const n=i.get(e,ma);if(!n.enabled||!n.clip)continue;const a=i.get(e,ae);if(n.playOnAwake&&!s.has(e)){const i=tn.getBufferHandle(n.clip);if(i){const o=t.play(i,{bus:n.bus,volume:n.volume,loop:n.loop,playbackRate:n.pitch,priority:n.priority});s.set(e,o)}}if(n.spatial&&s.has(e)){const t=s.get(e),i=a.position.x-o,l=a.position.y-r,c=fa(Math.sqrt(i*i+l*l),{model:n.attenuationModel,refDistance:n.minDistance,maxDistance:n.maxDistance,rolloff:n.rolloff}),u=pa(a.position.x,a.position.y,o,0,n.maxDistance);t.setVolume(n.volume*c),t.setPan(u)}}},{name:"AudioUpdateSystem"}))}cleanup(){}}const Sa=new ba;class Ma{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(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}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Pa(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function Ta(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:o}=e,r=t.getResource($n);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0)),Gs(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Pa(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Pa(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Fr(o,i,{app:t,module:n,provider:new Ma(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),u=t.getResource(js);u.register(c),u.setInitial(o),await u.load(o);const h=e.canvas.width/e.canvas.height;_n(t.world,h),t.run()}const Ea=[Wi,to,co,Fo,Wo,vo,jo,qo,er,Uo,Eo,tr,ir,lr,ur,mr,_r],Ca=[...Ea,aa];function Ra(e,t){return function(e,t){const n=qs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ns(e),kt(e),ws(e),Ms(e),ks(e),Us(e);const i=new Ls;n.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=ei(e,s,t,i));const r=n.getResource(Pt);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(Pt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Bs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Bs.resize(t,l),Es.isInitialized()&&Es.getPassCount()>0&&!Es.isBypassed()&&Es.resize(t,l),n.hasResource(js)){const e=n.getResource(js).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ei(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Ks,width:t,height:l,elapsed:u});else{for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Bs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(dt.First,l),n.addSystemToSchedule(dt.Last,c),n.addPlugin(Ln),n.addPlugin(Kn),n.addPlugin(Mt),n.addPlugin(Vs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ca,...t})}e=p;export{Ne as Added,ra as AnimationPlugin,qs as App,Dn as AssetPlugin,On as AssetRefCounter,Un as AssetServer,$n as Assets,jt as AsyncCache,ha as AttenuationModel,tn as Audio,la as AudioBus,ga as AudioListener,ca as AudioMixer,ba as AudioPlugin,ua as AudioPool,ma as AudioSource,pe as BitmapText,Tt as BlendMode,Se as BodyType,xe as BoxCollider,oo as Button,io as ButtonState,ce as Camera,ue as Canvas,be as CapsuleCollider,Ve as Changed,fe as Children,ve as CircleCollider,se as ClearFlags,nt as Commands,it as CommandsInstance,g as DEFAULT_DESIGN_HEIGHT,m as DEFAULT_DESIGN_WIDTH,M as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,P as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,_ as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,w as DEFAULT_SPRITE_SIZE,y as DEFAULT_TEXT_CANVAS_SIZE,ps as DataType,Xo as DragState,Ho as Draggable,rs as Draw,cr as Dropdown,qr as EasingType,st as EntityCommands,ct as EventReader,ht as EventReaderInstance,at as EventRegistry,lt as EventWriter,ut as EventWriterInstance,ci as FillDirection,Ro as FillMethod,Ao as FillOrigin,Po as FocusManager,Mo as FocusManagerState,So as Focusable,Ds as GLDebug,bs as Geometry,ft as GetWorld,k as INVALID_ENTITY,B as INVALID_FONT,z as INVALID_MATERIAL,F as INVALID_TEXTURE,Io as Image,Co as ImageType,bt as Input,St as InputPlugin,vt as InputState,no as Interactable,or as ListView,re as LocalTransform,Dr as LogLevel,Or as Logger,Jr as LoopMode,zt as Material,Yt as MaterialLoader,je as Mut,ge as Name,de as Parent,Tr as Physics,xr as PhysicsEvents,Mr as PhysicsPlugin,Es as PostProcess,Vn as PrefabServer,qn as Prefabs,Gn as PrefabsPlugin,Ur as PreviewPlugin,Do as ProgressBar,$o as ProgressBarDirection,Oo as ProgressBarPlugin,ne as ProjectionType,Qe as Query,Ze as QueryInstance,et as Removed,tt as RemovedQueryInstance,Ls as RenderPipeline,Rs as RenderStage,$r as RenderTexture,Bs as Renderer,Te as Res,Ee as ResMut,we as RigidBody,C as RuntimeConfig,nr as SafeArea,ie as ScaleMode,js as SceneManager,Xs as SceneManagerState,_e as SceneOwner,dt as Schedule,Yo as ScrollView,Xt as ShaderSources,Ko as Slider,Go as SliderDirection,Zo as SliderPlugin,me as SpineAnimation,le as Sprite,Zt as SpriteAnimator,xt as SystemRunner,$i as Text,Bi as TextAlign,bo as TextInput,To as TextInputPlugin,Ui as TextOverflow,Oi as TextPlugin,Di as TextRenderer,zi as TextVerticalAlign,Ae as Time,Bo as Toggle,oe as Transform,oa as Tween,Qr as TweenHandle,Kr as TweenState,Gr as TweenTarget,Pt as UICameraInfo,ro as UIEventQueue,ao as UIEvents,so as UIInteraction,xo as UIInteractionPlugin,lo as UILayoutPlugin,ji as UIMask,eo as UIMaskPlugin,hi as UIRect,gr as UIRenderOrderPlugin,he as Velocity,Br as WebAssetProvider,Xe as World,ae as WorldTransform,yt as addStartupSystem,_t as addSystem,wt as addSystemToSchedule,aa as animationPlugin,I as applyBuildRuntimeConfig,yi as applyDirectionalFill,R as applyRuntimeConfig,Ln as assetPlugin,Sa as audioPlugin,fa as calculateAttenuation,pa as calculatePanning,Qt as clearAnimClips,fs as clearDrawCallbacks,q as clearUserComponents,L as color,mi as computeFillAnchors,_i as computeFillSize,gi as computeHandleAnchors,ui as computeUIRectLayout,va as createAudioBackend,Zi as createMaskProcessor,Fr as createRuntimeSceneConfig,Ra as createWebApp,jr as debug,Y as defineComponent,ot as defineEvent,Pe as defineResource,mt as defineSystem,N as defineTag,Vr as error,Nt as extractAnimClipTexturePaths,yn as findEntityByName,Gs as flushPendingSystems,Tn as getAddressableType,En as getAddressableTypeByEditorType,Rn as getAllAssetExtensions,Jt as getAnimClip,Fn as getAssetMimeType,Mn as getAssetTypeEntry,ee as getComponent,rn as getComponentAssetFieldDescriptors,on as getComponentAssetFields,ye as getComponentDefaults,un as getComponentEntityFields,an as getComponentSpineFieldDescriptor,In as getCustomExtensions,Pn as getEditorType,Hr as getLogger,t as getPlatform,s as getPlatformType,V as getUserComponent,kn as getWeChatPackOptions,Yr as info,ns as initDrawAPI,Us as initGLDebugAPI,ws as initGeometryAPI,kt as initMaterialAPI,Ta as initPlayableRuntime,Ms as initPostProcessAPI,ks as initRendererAPI,ta as initTweenAPI,Mt as inputPlugin,Hn as instantiatePrefab,Yi as intersectRects,Ni as invertMatrix4,J as isBuiltinComponent,Bn as isCustomExtension,po as isEditor,Cn as isKnownAssetExtension,n as isPlatformInitialized,_o as isPlayMode,mo as isRuntime,Et as isTextureRef,i as isWeChat,o as isWeb,gn as loadComponent,wr as loadPhysicsModule,kr as loadRuntimeScene,fn as loadSceneData,pn as loadSceneWithAssets,An as looksLikeAssetPath,Vt as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ji as pointInOBB,qi as pointInWorldRect,Kn as prefabsPlugin,Wo as progressBarPlugin,O as quat,Gt as registerAnimClip,Z as registerComponent,sn as registerComponentAssetFields,cn as registerComponentEntityFields,hs as registerDrawCallback,Wn as registerEmbeddedAssets,Ht as registerMaterialCallback,hn as remapEntityFields,Vs as sceneManagerPlugin,Vi as screenToWorld,fo as setEditorMode,ar as setListViewRenderer,Xr as setLogLevel,go as setPlayMode,ze as setWasmErrorHandler,ss as shutdownDrawAPI,$s as shutdownGLDebugAPI,xs as shutdownGeometryAPI,Ft as shutdownMaterialAPI,Ps as shutdownPostProcessAPI,Fs as shutdownRendererAPI,na as shutdownTweenAPI,er as sliderPlugin,en as spriteAnimatorSystemUpdate,Ti as syncFillSpriteSize,Eo as textInputPlugin,Wi as textPlugin,zn as toBuildPath,yr as transitionTo,vo as uiInteractionPlugin,co as uiLayoutPlugin,to as uiMaskPlugin,Ea as uiPlugins,_r as uiRenderOrderPlugin,Kt as unregisterAnimClip,G as unregisterComponent,ds as unregisterDrawCallback,_n as updateCameraAspectRatio,U as vec2,$ as vec3,D as vec4,Nr as warn,Ys as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/editor/package.json b/editor/package.json
index c61ca5d30..11ab80b16 100644
--- a/editor/package.json
+++ b/editor/package.json
@@ -30,10 +30,11 @@
"lucide": "^0.563.0"
},
"devDependencies": {
- "@tauri-apps/api": "^2.0.0",
"@rollup/plugin-alias": "^6.0.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-typescript": "^11.1.5",
+ "@tauri-apps/api": "^2.0.0",
+ "@vitest/coverage-v8": "^2.1.9",
"@vitest/ui": "^2.1.8",
"happy-dom": "^20.6.1",
"jsdom": "^25.0.1",
diff --git a/editor/src/panels/hierarchy/HierarchyContextMenu.ts b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
index dac19cffc..fd6643964 100644
--- a/editor/src/panels/hierarchy/HierarchyContextMenu.ts
+++ b/editor/src/panels/hierarchy/HierarchyContextMenu.ts
@@ -23,30 +23,38 @@ export function showEntityContextMenu(state: HierarchyState, x: number, y: numbe
const newEntity = state.store.createEntity(undefined, entity);
state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
} },
- { label: 'Sprite', icon: icons.image(14), onClick: () => createEntityWithComponent(state, 'Sprite', entity) },
- { label: 'Text', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'Text', entity) },
- { label: 'BitmapText', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'BitmapText', entity) },
- { label: 'Spine', icon: icons.bone(14), onClick: () => createEntityWithComponent(state, 'SpineAnimation', entity) },
- { label: 'Camera', icon: icons.camera(14), onClick: () => createEntityWithComponent(state, 'Camera', entity) },
- { label: 'Canvas', icon: icons.template(14), onClick: () => createEntityWithComponent(state, 'Canvas', entity) },
{ label: '', separator: true },
+ { label: '2D', icon: icons.image(14), children: [
+ { label: 'Sprite', icon: icons.image(14), onClick: () => createEntityWithComponent(state, 'Sprite', entity) },
+ { label: 'Text', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'Text', entity) },
+ { label: 'BitmapText', icon: icons.type(14), onClick: () => createEntityWithComponent(state, 'BitmapText', entity) },
+ { label: 'Spine', icon: icons.bone(14), onClick: () => createEntityWithComponent(state, 'SpineAnimation', entity) },
+ ] },
{ label: 'UI', icon: icons.pointer(14), children: [
- { label: 'Button', onClick: () => createButtonEntity(state, entity) },
- { label: 'TextInput', onClick: () => createTextInputEntity(state, entity) },
- { label: 'Image', onClick: () => createImageEntity(state, entity) },
- { label: 'Panel', onClick: () => createPanelEntity(state, entity) },
+ { label: 'Canvas', icon: icons.template(14), onClick: () => createEntityWithComponent(state, 'Canvas', entity) },
+ { label: '', separator: true },
+ { label: 'Button', icon: icons.pointer(14), onClick: () => createButtonEntity(state, entity) },
+ { label: 'TextInput', icon: icons.type(14), onClick: () => createTextInputEntity(state, entity) },
+ { label: 'Image', icon: icons.image(14), onClick: () => createImageEntity(state, entity) },
+ { label: 'Panel', icon: icons.layers(14), onClick: () => createPanelEntity(state, entity) },
{ label: '', separator: true },
- { label: 'Toggle', onClick: () => createToggleEntity(state, entity) },
- { label: 'Slider', onClick: () => createSliderEntity(state, entity) },
- { label: 'ProgressBar', onClick: () => createProgressBarEntity(state, entity) },
- { label: 'ScrollView', onClick: () => createScrollViewEntity(state, entity) },
- { label: 'Dropdown', onClick: () => createDropdownEntity(state, entity) },
+ { label: 'Toggle', icon: icons.toggle(14), onClick: () => createToggleEntity(state, entity) },
+ { label: 'Slider', icon: icons.sliders(14), onClick: () => createSliderEntity(state, entity) },
+ { label: 'ProgressBar', icon: icons.gauge(14), onClick: () => createProgressBarEntity(state, entity) },
+ { label: 'ScrollView', icon: icons.list(14), onClick: () => createScrollViewEntity(state, entity) },
+ { label: 'Dropdown', icon: icons.chevronDown(14), onClick: () => createDropdownEntity(state, entity) },
+ ] },
+ { label: 'Audio', icon: icons.volume(14), children: [
+ { label: 'AudioSource', icon: icons.volume(14), onClick: () => createAudioEntity(state, 'AudioSource', entity) },
+ { label: 'AudioListener', icon: icons.headphones(14), onClick: () => createAudioEntity(state, 'AudioListener', entity) },
] },
{ label: 'Physics', icon: icons.circle(14), children: [
- { label: 'Box Collider', onClick: () => createPhysicsEntity(state, 'BoxCollider', entity) },
- { label: 'Circle Collider', onClick: () => createPhysicsEntity(state, 'CircleCollider', entity) },
- { label: 'Capsule Collider', onClick: () => createPhysicsEntity(state, 'CapsuleCollider', entity) },
+ { label: 'Box Collider', icon: icons.box(14), onClick: () => createPhysicsEntity(state, 'BoxCollider', entity) },
+ { label: 'Circle Collider', icon: icons.circle(14), onClick: () => createPhysicsEntity(state, 'CircleCollider', entity) },
+ { label: 'Capsule Collider', icon: icons.shield(14), onClick: () => createPhysicsEntity(state, 'CapsuleCollider', entity) },
] },
+ { label: '', separator: true },
+ { label: 'Camera', icon: icons.camera(14), onClick: () => createEntityWithComponent(state, 'Camera', entity) },
];
const items: ContextMenuItem[] = [];
@@ -98,25 +106,28 @@ export function showEntityContextMenu(state: HierarchyState, x: number, y: numbe
const addComp = (type: string) => state.store.addComponent(entity, type, getInitialComponentData(type));
items.push({
label: 'Add Component', children: [
- { label: 'Interactable', disabled: has('Interactable'), onClick: () => addComp('Interactable') },
- { label: 'Button', disabled: has('Button'), onClick: () => addComp('Button') },
- { label: 'Image', disabled: has('Image'), onClick: () => addComp('Image') },
- { label: 'UIMask', disabled: has('UIMask'), onClick: () => addComp('UIMask') },
+ { label: 'Interactable', icon: icons.pointer(14), disabled: has('Interactable'), onClick: () => addComp('Interactable') },
+ { label: 'Button', icon: icons.pointer(14), disabled: has('Button'), onClick: () => addComp('Button') },
+ { label: 'Image', icon: icons.image(14), disabled: has('Image'), onClick: () => addComp('Image') },
+ { label: 'UIMask', icon: icons.scan(14), disabled: has('UIMask'), onClick: () => addComp('UIMask') },
{ label: '', separator: true },
- { label: 'Toggle', disabled: has('Toggle'), onClick: () => addComp('Toggle') },
- { label: 'Slider', disabled: has('Slider'), onClick: () => addComp('Slider') },
- { label: 'ProgressBar', disabled: has('ProgressBar'), onClick: () => addComp('ProgressBar') },
- { label: 'Draggable', disabled: has('Draggable'), onClick: () => addComp('Draggable') },
- { label: 'ScrollView', disabled: has('ScrollView'), onClick: () => addComp('ScrollView') },
- { label: 'Dropdown', disabled: has('Dropdown'), onClick: () => addComp('Dropdown') },
- { label: 'ListView', disabled: has('ListView'), onClick: () => addComp('ListView') },
- { label: 'Focusable', disabled: has('Focusable'), onClick: () => addComp('Focusable') },
- { label: 'SafeArea', disabled: has('SafeArea'), onClick: () => addComp('SafeArea') },
+ { label: 'Toggle', icon: icons.toggle(14), disabled: has('Toggle'), onClick: () => addComp('Toggle') },
+ { label: 'Slider', icon: icons.sliders(14), disabled: has('Slider'), onClick: () => addComp('Slider') },
+ { label: 'ProgressBar', icon: icons.gauge(14), disabled: has('ProgressBar'), onClick: () => addComp('ProgressBar') },
+ { label: 'Draggable', icon: icons.move(14), disabled: has('Draggable'), onClick: () => addComp('Draggable') },
+ { label: 'ScrollView', icon: icons.list(14), disabled: has('ScrollView'), onClick: () => addComp('ScrollView') },
+ { label: 'Dropdown', icon: icons.chevronDown(14), disabled: has('Dropdown'), onClick: () => addComp('Dropdown') },
+ { label: 'ListView', icon: icons.list(14), disabled: has('ListView'), onClick: () => addComp('ListView') },
+ { label: 'Focusable', icon: icons.eye(14), disabled: has('Focusable'), onClick: () => addComp('Focusable') },
+ { label: 'SafeArea', icon: icons.shield(14), disabled: has('SafeArea'), onClick: () => addComp('SafeArea') },
{ label: '', separator: true },
- { label: 'RigidBody', disabled: has('RigidBody'), onClick: () => addComp('RigidBody') },
- { label: 'BoxCollider', disabled: has('BoxCollider'), onClick: () => addComp('BoxCollider') },
- { label: 'CircleCollider', disabled: has('CircleCollider'), onClick: () => addComp('CircleCollider') },
- { label: 'CapsuleCollider', disabled: has('CapsuleCollider'), onClick: () => addComp('CapsuleCollider') },
+ { label: 'AudioSource', icon: icons.volume(14), disabled: has('AudioSource'), onClick: () => addComp('AudioSource') },
+ { label: 'AudioListener', icon: icons.headphones(14), disabled: has('AudioListener'), onClick: () => addComp('AudioListener') },
+ { label: '', separator: true },
+ { label: 'RigidBody', icon: icons.box(14), disabled: has('RigidBody'), onClick: () => addComp('RigidBody') },
+ { label: 'BoxCollider', icon: icons.box(14), disabled: has('BoxCollider'), onClick: () => addComp('BoxCollider') },
+ { label: 'CircleCollider', icon: icons.circle(14), disabled: has('CircleCollider'), onClick: () => addComp('CircleCollider') },
+ { label: 'CapsuleCollider', icon: icons.shield(14), disabled: has('CapsuleCollider'), onClick: () => addComp('CapsuleCollider') },
],
});
@@ -198,6 +209,12 @@ function createEntityWithComponent(state: HierarchyState, componentType: string,
state.store.addComponent(newEntity, componentType, getInitialComponentData(componentType));
}
+function createAudioEntity(state: HierarchyState, componentType: string, parent: Entity | null): void {
+ const newEntity = state.store.createEntity(componentType, parent);
+ state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
+ state.store.addComponent(newEntity, componentType, getInitialComponentData(componentType));
+}
+
function createPhysicsEntity(state: HierarchyState, colliderType: string, parent: Entity | null): void {
const newEntity = state.store.createEntity(colliderType, parent);
state.store.addComponent(newEntity, 'Transform', getInitialComponentData('Transform'));
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 05d04d7c5..af25e543c 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -1921,6 +1921,133 @@ function createAnimFileEditor(
};
}
+// =============================================================================
+// Audio File Editor
+// =============================================================================
+
+function createAudioFileEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-file-editor';
+
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.className = 'es-input es-input-file es-asset-link';
+ input.value = resolveDisplayName(String(value ?? ''));
+ input.placeholder = 'None';
+ input.readOnly = true;
+ checkAssetMissing(String(value ?? ''), input);
+
+ const browseBtn = document.createElement('button');
+ browseBtn.className = 'es-btn es-btn-icon es-btn-browse';
+ browseBtn.title = 'Browse';
+ browseBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-6l-2-2H5a2 2 0 0 0-2 2z"></path></svg>`;
+
+ const clearBtn = document.createElement('button');
+ clearBtn.className = 'es-btn es-btn-icon es-btn-clear';
+ clearBtn.title = 'Clear';
+ clearBtn.innerHTML = `<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
+
+ input.addEventListener('click', () => {
+ if (input.value) {
+ navigateToAsset(input.value);
+ }
+ });
+
+ wrapper.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ const data = e.dataTransfer?.types.includes('application/esengine-asset');
+ if (data) {
+ wrapper.classList.add('es-drag-over');
+ e.dataTransfer!.dropEffect = 'copy';
+ } else {
+ e.dataTransfer!.dropEffect = 'none';
+ }
+ });
+
+ wrapper.addEventListener('dragleave', () => {
+ wrapper.classList.remove('es-drag-over');
+ });
+
+ wrapper.addEventListener('drop', (e) => {
+ e.preventDefault();
+ wrapper.classList.remove('es-drag-over');
+
+ const jsonData = e.dataTransfer?.getData('application/esengine-asset');
+ if (!jsonData) return;
+
+ try {
+ const assetData = JSON.parse(jsonData);
+ if (assetData.type === 'audio') {
+ const projectDir = getProjectDir();
+ if (projectDir && assetData.path.startsWith(projectDir)) {
+ const relativePath = assetData.path.substring(projectDir.length + 1);
+ const uuid = getAssetLibrary().getUuid(relativePath);
+ const ref = uuid ?? relativePath;
+ input.value = relativePath;
+ onChange(ref);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to parse drop data:', err);
+ }
+ });
+
+ browseBtn.addEventListener('click', async () => {
+ const projectDir = getProjectDir();
+ if (!projectDir) return;
+
+ const assetsDir = `${projectDir}/assets`;
+
+ try {
+ const platform = getPlatformAdapter();
+ const result = await platform.openFileDialog({
+ title: 'Select Audio File',
+ defaultPath: assetsDir,
+ filters: [{ name: 'Audio', extensions: ['mp3', 'wav', 'ogg'] }],
+ });
+ if (result) {
+ const normalizedPath = result.replace(/\\/g, '/');
+ const assetsIndex = normalizedPath.indexOf('/assets/');
+ if (assetsIndex !== -1) {
+ const relativePath = normalizedPath.substring(assetsIndex + 1);
+ const uuid = getAssetLibrary().getUuid(relativePath);
+ const ref = uuid ?? relativePath;
+ input.value = relativePath;
+ onChange(ref);
+ }
+ }
+ } catch (err) {
+ console.error('Failed to open file dialog:', err);
+ }
+ });
+
+ clearBtn.addEventListener('click', () => {
+ input.value = '';
+ onChange('');
+ });
+
+ wrapper.appendChild(input);
+ wrapper.appendChild(browseBtn);
+ wrapper.appendChild(clearBtn);
+ container.appendChild(wrapper);
+
+ return {
+ update(v: unknown) {
+ const ref = String(v ?? '');
+ input.value = resolveDisplayName(ref);
+ checkAssetMissing(ref, input);
+ },
+ dispose() {
+ wrapper.remove();
+ },
+ };
+}
+
// =============================================================================
// Register All Editors
// =============================================================================
@@ -1948,4 +2075,5 @@ export function registerBuiltinEditors(): void {
registerPropertyEditor('entity', createEntityEditor);
registerPropertyEditor('string-array', createStringArrayEditor);
registerPropertyEditor('anim-file', createAnimFileEditor);
+ registerPropertyEditor('audio-file', createAudioFileEditor);
}
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index ee3d8f1bb..40ce2843c 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -351,6 +351,43 @@ export const SpriteAnimatorSchema: ComponentSchema = {
],
};
+export const AudioSourceSchema: ComponentSchema = {
+ name: 'AudioSource',
+ category: 'builtin',
+ properties: [
+ { name: 'clip', type: 'audio-file' },
+ { name: 'bus', type: 'enum', options: [
+ { label: 'SFX', value: 'sfx' },
+ { label: 'Music', value: 'music' },
+ { label: 'UI', value: 'ui' },
+ { label: 'Voice', value: 'voice' },
+ ]},
+ { name: 'volume', type: 'number', min: 0, max: 1, step: 0.05 },
+ { name: 'pitch', type: 'number', min: 0.1, max: 3, step: 0.1 },
+ { name: 'loop', type: 'boolean' },
+ { name: 'playOnAwake', type: 'boolean' },
+ { name: 'spatial', type: 'boolean' },
+ { name: 'minDistance', type: 'number', min: 0, step: 10 },
+ { name: 'maxDistance', type: 'number', min: 0, step: 10 },
+ { name: 'attenuationModel', type: 'enum', options: [
+ { label: 'Linear', value: 0 },
+ { label: 'Inverse', value: 1 },
+ { label: 'Exponential', value: 2 },
+ ]},
+ { name: 'rolloff', type: 'number', min: 0, max: 5, step: 0.1 },
+ { name: 'priority', type: 'number', min: 0, step: 1 },
+ { name: 'enabled', type: 'boolean' },
+ ],
+};
+
+export const AudioListenerSchema: ComponentSchema = {
+ name: 'AudioListener',
+ category: 'builtin',
+ properties: [
+ { name: 'enabled', type: 'boolean' },
+ ],
+};
+
export const RigidBodySchema: ComponentSchema = {
name: 'RigidBody',
category: 'physics',
@@ -810,6 +847,8 @@ export function registerBuiltinSchemas(options?: BuiltinSchemaOptions): void {
registerComponentSchema(FlexItemSchema);
registerComponentSchema(LayoutGroupSchema);
registerComponentSchema(SpriteAnimatorSchema);
+ registerComponentSchema(AudioSourceSchema);
+ registerComponentSchema(AudioListenerSchema);
registerComponentSchema(RigidBodySchema);
registerComponentSchema(BoxColliderSchema);
registerComponentSchema(CircleColliderSchema);
diff --git a/editor/src/utils/icons.ts b/editor/src/utils/icons.ts
index 7e728f97d..2a84ac95d 100644
--- a/editor/src/utils/icons.ts
+++ b/editor/src/utils/icons.ts
@@ -64,6 +64,9 @@ import {
Clipboard,
Pause,
StepForward,
+ Headphones,
+ SlidersHorizontal,
+ Gauge,
} from 'lucide';
// =============================================================================
@@ -184,6 +187,9 @@ export const icons = {
clipboard: (size?: number) => renderIcon(Clipboard as IconNode, size),
pause: (size?: number) => renderIcon(Pause as IconNode, size),
stepForward: (size?: number) => renderIcon(StepForward as IconNode, size),
+ headphones: (size?: number) => renderIcon(Headphones as IconNode, size),
+ sliders: (size?: number) => renderIcon(SlidersHorizontal as IconNode, size),
+ gauge: (size?: number) => renderIcon(Gauge as IconNode, size),
};
export type IconName = keyof typeof icons;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e5854b007..88c749dba 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -88,6 +88,9 @@ importers:
'@tauri-apps/api':
specifier: ^2.0.0
version: 2.10.1
+ '@vitest/coverage-v8':
+ specifier: ^2.1.9
+ version: 2.1.9([email protected])
'@vitest/ui':
specifier: ^2.1.8
version: 2.1.9([email protected])
@@ -124,6 +127,9 @@ importers:
'@rollup/plugin-typescript':
specifier: ^11.1.5
+ '@vitest/coverage-v8':
+ specifier: ^2.1.9
+ version: 2.1.9([email protected])
'@vitest/ui':
specifier: ^2.1.0
version: 2.1.9([email protected])
@@ -154,6 +160,10 @@ importers:
packages:
+ '@ampproject/[email protected]':
+ resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}
+ engines: {node: '>=6.0.0'}
+
'@asamuzakjp/[email protected]':
resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
@@ -161,10 +171,26 @@ packages:
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
engines: {node: '>=6.9.0'}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}
+ engines: {node: '>=6.9.0'}
+
resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}
engines: {node: '>=6.9.0'}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
+ engines: {node: '>=6.9.0'}
+
+ resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==}
+
'@csstools/[email protected]':
resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==}
engines: {node: '>=18'}
@@ -491,6 +517,10 @@ packages:
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
+ '@istanbuljs/[email protected]':
+ resolution: {integrity: sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==}
+ engines: {node: '>=8'}
+
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -810,6 +840,15 @@ packages:
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-Z2cOr0ksM00MpEfyVE8KXIYPEcBFxdbLSs56L8PO0QQMxt/6bDj45uQfxoc96v05KW3clk7vvgP0qfDit9DmfQ==}
+ peerDependencies:
+ '@vitest/browser': 2.1.9
+ vitest: 2.1.9
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
'@vitest/[email protected]':
resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
@@ -883,6 +922,10 @@ packages:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
+ resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
engines: {node: '>=8'}
@@ -890,6 +933,10 @@ packages:
resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==}
+ resolution: {integrity: sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'}
@@ -1122,6 +1169,10 @@ packages:
resolution: {integrity: sha512-+0vhESXXhFwkdjZnJ5DlmJIfUYGgIEEjzIjB+aKJbFuqlvvKyOi+XkI1fYbgYR9QCxG5T08koxsQ6HrQfa5gCQ==}
engines: {node: '>=20.0.0'}
+ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
engines: {node: '>= 0.4'}
@@ -1138,6 +1189,9 @@ packages:
resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
+
resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}
engines: {node: '>= 14'}
@@ -1195,6 +1249,22 @@ packages:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
@@ -1226,6 +1296,13 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}
+
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
@@ -1245,6 +1322,10 @@ packages:
resolution: {integrity: sha512-xSxV1onUDkwBRRqxAQgu+Xct1Ose74Ol2ESefE/hUpxH+7oY/eAFUvEaQB8hKL/2TZNx4RMIduEZv4Z5cAuvYg==}
+ resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}
engines: {node: '>=16 || 14 >=14.17'}
@@ -1371,6 +1452,11 @@ packages:
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
engines: {node: '>=v12.22.7'}
+ resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
+ engines: {node: '>=10'}
+ hasBin: true
+
resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==}
@@ -1437,6 +1523,10 @@ packages:
resolution: {integrity: sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
@@ -1449,6 +1539,10 @@ packages:
engines: {node: '>=10'}
hasBin: true
+ resolution: {integrity: sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
@@ -1670,6 +1764,11 @@ packages:
snapshots:
+ '@ampproject/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
'@asamuzakjp/[email protected]':
dependencies:
'@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])
@@ -1685,8 +1784,20 @@ snapshots:
picocolors: 1.1.1
optional: true
- '@babel/[email protected]':
- optional: true
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/types': 7.29.0
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/helper-string-parser': 7.27.1
+ '@babel/helper-validator-identifier': 7.28.5
+
+ '@bcoe/[email protected]': {}
'@csstools/[email protected]': {}
@@ -1864,6 +1975,8 @@ snapshots:
wrap-ansi: 8.1.0
wrap-ansi-cjs: [email protected]
+ '@istanbuljs/[email protected]': {}
+
'@jridgewell/[email protected]':
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -2085,6 +2198,24 @@ snapshots:
dependencies:
'@types/node': 25.2.3
+ dependencies:
+ '@ampproject/remapping': 2.3.0
+ '@bcoe/v8-coverage': 0.2.3
+ debug: 4.4.3
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-lib-source-maps: 5.0.6
+ istanbul-reports: 3.2.0
+ magic-string: 0.30.21
+ magicast: 0.3.5
+ std-env: 3.10.0
+ test-exclude: 7.0.2
+ tinyrainbow: 1.2.0
+ transitivePeerDependencies:
+ - supports-color
+
'@vitest/[email protected]':
dependencies:
'@vitest/spy': 2.1.9
@@ -2161,12 +2292,18 @@ snapshots:
+
dependencies:
balanced-match: 1.0.2
+ dependencies:
+ balanced-match: 4.0.4
+
dependencies:
fill-range: 7.1.1
@@ -2437,6 +2574,8 @@ snapshots:
- bufferutil
- utf-8-validate
+
@@ -2451,6 +2590,8 @@ snapshots:
dependencies:
whatwg-encoding: 3.1.1
+
dependencies:
agent-base: 7.1.4
@@ -2499,6 +2640,27 @@ snapshots:
+
+ dependencies:
+ istanbul-lib-coverage: 3.2.2
+ make-dir: 4.0.0
+ supports-color: 7.2.0
+
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ debug: 4.4.3
+ istanbul-lib-coverage: 3.2.2
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ html-escaper: 2.0.2
+ istanbul-lib-report: 3.0.1
+
dependencies:
'@isaacs/cliui': 8.0.2
@@ -2551,6 +2713,16 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+ dependencies:
+ '@babel/parser': 7.29.0
+ '@babel/types': 7.29.0
+ source-map-js: 1.2.1
+
+ dependencies:
+ semver: 7.7.4
+
@@ -2563,6 +2735,10 @@ snapshots:
+ dependencies:
+ brace-expansion: 5.0.4
+
dependencies:
brace-expansion: 2.0.2
@@ -2702,6 +2878,8 @@ snapshots:
dependencies:
xmlchars: 2.2.0
+
dependencies:
randombytes: 2.1.0
@@ -2765,6 +2943,10 @@ snapshots:
dependencies:
ansi-regex: 6.2.2
+ dependencies:
+ has-flag: 4.0.0
+
@@ -2776,6 +2958,12 @@ snapshots:
commander: 2.20.3
source-map-support: 0.5.21
+ dependencies:
+ '@istanbuljs/schema': 0.1.3
+ glob: 10.5.0
+ minimatch: 10.2.4
+
diff --git a/sdk/package.json b/sdk/package.json
index ed1d56670..d780a79a4 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -61,6 +61,7 @@
"devDependencies": {
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
+ "@vitest/coverage-v8": "^2.1.9",
"@vitest/ui": "^2.1.0",
"happy-dom": "^15.11.0",
"minigame-api-typings": "^3.8.16",
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
new file mode 100644
index 000000000..75453a850
--- /dev/null
+++ b/sdk/src/audio/Audio.ts
@@ -0,0 +1,183 @@
+import type { PlatformAudioBackend, AudioBufferHandle, AudioHandle } from './PlatformAudioBackend';
+import type { AudioMixer } from './AudioMixer';
+
+export class Audio {
+ private static backend_: PlatformAudioBackend;
+ private static mixer_: AudioMixer | null = null;
+ private static bufferCache_ = new Map<string, AudioBufferHandle>();
+ private static bgmHandle_: AudioHandle | null = null;
+
+ static init(backend: PlatformAudioBackend, mixer: AudioMixer | null = null): void {
+ this.backend_ = backend;
+ this.mixer_ = mixer;
+ this.bufferCache_.clear();
+ this.bgmHandle_ = null;
+ }
+
+ static async preload(url: string): Promise<void> {
+ if (this.bufferCache_.has(url)) return;
+ const buffer = await this.backend_.loadBuffer(url);
+ this.bufferCache_.set(url, buffer);
+ }
+
+ static async preloadAll(urls: string[]): Promise<void> {
+ await Promise.all(urls.map(url => this.preload(url)));
+ }
+
+ static playSFX(url: string, config?: {
+ volume?: number;
+ pitch?: number;
+ pan?: number;
+ priority?: number;
+ }): AudioHandle {
+ const buffer = this.bufferCache_.get(url);
+ if (!buffer) {
+ this.preload(url).then(() => {
+ const buf = this.bufferCache_.get(url);
+ if (buf) {
+ this.backend_.play(buf, {
+ bus: 'sfx',
+ volume: config?.volume,
+ playbackRate: config?.pitch,
+ pan: config?.pan,
+ priority: config?.priority ?? 0,
+ });
+ }
+ });
+ return this.createPendingHandle();
+ }
+ return this.backend_.play(buffer, {
+ bus: 'sfx',
+ volume: config?.volume,
+ playbackRate: config?.pitch,
+ pan: config?.pan,
+ priority: config?.priority ?? 0,
+ });
+ }
+
+ static playBGM(url: string, config?: {
+ volume?: number;
+ fadeIn?: number;
+ crossFade?: number;
+ }): void {
+ const play = (buffer: AudioBufferHandle) => {
+ if (this.bgmHandle_ && config?.crossFade) {
+ this.fadeOut(this.bgmHandle_, config.crossFade);
+ } else if (this.bgmHandle_) {
+ this.bgmHandle_.stop();
+ }
+
+ this.bgmHandle_ = this.backend_.play(buffer, {
+ bus: 'music',
+ volume: config?.fadeIn ? 0 : (config?.volume ?? 1.0),
+ loop: true,
+ });
+
+ if (config?.fadeIn) {
+ this.fadeIn(this.bgmHandle_, config.fadeIn, config?.volume ?? 1.0);
+ }
+ };
+
+ const buffer = this.bufferCache_.get(url);
+ if (buffer) {
+ play(buffer);
+ } else {
+ this.preload(url).then(() => {
+ const buf = this.bufferCache_.get(url);
+ if (buf) {
+ play(buf);
+ }
+ });
+ }
+ }
+
+ static stopBGM(fadeOut?: number): void {
+ if (!this.bgmHandle_) return;
+ if (fadeOut && fadeOut > 0) {
+ this.fadeOut(this.bgmHandle_, fadeOut);
+ } else {
+ this.bgmHandle_.stop();
+ }
+ this.bgmHandle_ = null;
+ }
+
+ static setMasterVolume(volume: number): void {
+ if (this.mixer_) {
+ this.mixer_.master.volume = volume;
+ }
+ }
+
+ static setMusicVolume(volume: number): void {
+ if (this.mixer_) {
+ this.mixer_.music.volume = volume;
+ }
+ }
+
+ static setSFXVolume(volume: number): void {
+ if (this.mixer_) {
+ this.mixer_.sfx.volume = volume;
+ }
+ }
+
+ static setUIVolume(volume: number): void {
+ if (this.mixer_) {
+ this.mixer_.ui.volume = volume;
+ }
+ }
+
+ static muteBus(busName: string, muted: boolean): void {
+ const bus = this.mixer_?.getBus(busName);
+ if (bus) {
+ bus.muted = muted;
+ }
+ }
+
+ static getBufferHandle(url: string): AudioBufferHandle | undefined {
+ return this.bufferCache_.get(url);
+ }
+
+ private static fadeIn(handle: AudioHandle, duration: number, targetVolume: number): void {
+ handle.setVolume(0);
+ const startTime = performance.now();
+ const tick = () => {
+ const elapsed = (performance.now() - startTime) / 1000;
+ const t = Math.min(elapsed / duration, 1);
+ handle.setVolume(t * targetVolume);
+ if (t < 1 && handle.isPlaying) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ }
+
+ private static fadeOut(handle: AudioHandle, duration: number): void {
+ const startTime = performance.now();
+ const tick = () => {
+ const elapsed = (performance.now() - startTime) / 1000;
+ const t = Math.min(elapsed / duration, 1);
+ handle.setVolume(1 - t);
+ if (t < 1 && handle.isPlaying) {
+ requestAnimationFrame(tick);
+ } else {
+ handle.stop();
+ }
+ };
+ requestAnimationFrame(tick);
+ }
+
+ private static createPendingHandle(): AudioHandle {
+ return {
+ id: -1,
+ stop() {},
+ pause() {},
+ resume() {},
+ setVolume() {},
+ setPan() {},
+ setLoop() {},
+ setPlaybackRate() {},
+ isPlaying: false,
+ currentTime: 0,
+ duration: 0,
+ };
+ }
+}
diff --git a/sdk/src/audio/AudioBackendFactory.ts b/sdk/src/audio/AudioBackendFactory.ts
new file mode 100644
index 000000000..e9268457d
--- /dev/null
+++ b/sdk/src/audio/AudioBackendFactory.ts
@@ -0,0 +1,11 @@
+import { WebAudioBackend } from './WebAudioBackend';
+import { WeChatAudioBackend } from './WeChatAudioBackend';
+import type { PlatformAudioBackend } from './PlatformAudioBackend';
+import { isWeChat } from '../platform/base';
+
+export function createAudioBackend(): PlatformAudioBackend {
+ if (isWeChat()) {
+ return new WeChatAudioBackend();
+ }
+ return new WebAudioBackend();
+}
diff --git a/sdk/src/audio/AudioBus.ts b/sdk/src/audio/AudioBus.ts
new file mode 100644
index 000000000..1760a6008
--- /dev/null
+++ b/sdk/src/audio/AudioBus.ts
@@ -0,0 +1,62 @@
+export interface AudioBusConfig {
+ name: string;
+ volume?: number;
+ muted?: boolean;
+ parent?: string;
+}
+
+const SMOOTHING_TIME_CONSTANT = 0.015;
+
+export class AudioBus {
+ private readonly name_: string;
+ private readonly gainNode_: GainNode;
+ private muted_: boolean = false;
+ private volume_: number = 1.0;
+ private children_: AudioBus[] = [];
+
+ constructor(context: AudioContext, config: AudioBusConfig) {
+ this.name_ = config.name;
+ this.gainNode_ = context.createGain();
+ this.volume_ = config.volume ?? 1.0;
+ this.muted_ = config.muted ?? false;
+ this.gainNode_.gain.value = this.muted_ ? 0 : this.volume_;
+ }
+
+ get name(): string { return this.name_; }
+ get node(): GainNode { return this.gainNode_; }
+
+ get volume(): number { return this.volume_; }
+ set volume(v: number) {
+ this.volume_ = Math.max(0, Math.min(1, v));
+ if (!this.muted_) {
+ this.gainNode_.gain.setTargetAtTime(
+ this.volume_,
+ this.gainNode_.context.currentTime,
+ SMOOTHING_TIME_CONSTANT
+ );
+ }
+ }
+
+ get muted(): boolean { return this.muted_; }
+ set muted(m: boolean) {
+ this.muted_ = m;
+ this.gainNode_.gain.setTargetAtTime(
+ m ? 0 : this.volume_,
+ this.gainNode_.context.currentTime,
+ SMOOTHING_TIME_CONSTANT
+ );
+ }
+
+ connect(destination: AudioBus | AudioNode): void {
+ if (destination instanceof AudioBus) {
+ this.gainNode_.connect(destination.node);
+ } else {
+ this.gainNode_.connect(destination);
+ }
+ }
+
+ addChild(child: AudioBus): void {
+ child.connect(this);
+ this.children_.push(child);
+ }
+}
diff --git a/sdk/src/audio/AudioComponents.ts b/sdk/src/audio/AudioComponents.ts
new file mode 100644
index 000000000..77e11a475
--- /dev/null
+++ b/sdk/src/audio/AudioComponents.ts
@@ -0,0 +1,42 @@
+import { defineComponent } from '../component';
+import { AttenuationModel } from './SpatialAudio';
+
+export interface AudioSourceData {
+ clip: string;
+ bus: string;
+ volume: number;
+ pitch: number;
+ loop: boolean;
+ playOnAwake: boolean;
+ spatial: boolean;
+ minDistance: number;
+ maxDistance: number;
+ attenuationModel: number;
+ rolloff: number;
+ priority: number;
+ enabled: boolean;
+}
+
+export const AudioSource = defineComponent<AudioSourceData>('AudioSource', {
+ clip: '',
+ bus: 'sfx',
+ volume: 1.0,
+ pitch: 1.0,
+ loop: false,
+ playOnAwake: false,
+ spatial: false,
+ minDistance: 100,
+ maxDistance: 1000,
+ attenuationModel: AttenuationModel.Inverse,
+ rolloff: 1.0,
+ priority: 0,
+ enabled: true,
+});
+
+export interface AudioListenerData {
+ enabled: boolean;
+}
+
+export const AudioListener = defineComponent<AudioListenerData>('AudioListener', {
+ enabled: true,
+});
diff --git a/sdk/src/audio/AudioMixer.ts b/sdk/src/audio/AudioMixer.ts
new file mode 100644
index 000000000..ef90a04ab
--- /dev/null
+++ b/sdk/src/audio/AudioMixer.ts
@@ -0,0 +1,61 @@
+import { AudioBus, type AudioBusConfig } from './AudioBus';
+
+export interface AudioMixerConfig {
+ masterVolume?: number;
+ musicVolume?: number;
+ sfxVolume?: number;
+ uiVolume?: number;
+ voiceVolume?: number;
+}
+
+const DEFAULT_MUSIC_VOLUME = 0.8;
+
+export class AudioMixer {
+ readonly master: AudioBus;
+ readonly music: AudioBus;
+ readonly sfx: AudioBus;
+ readonly ui: AudioBus;
+ readonly voice: AudioBus;
+
+ private readonly context_: AudioContext;
+ private readonly buses_ = new Map<string, AudioBus>();
+
+ constructor(context: AudioContext, config: AudioMixerConfig = {}) {
+ this.context_ = context;
+
+ this.master = new AudioBus(context, { name: 'master', volume: config.masterVolume ?? 1.0 });
+ this.master.connect(context.destination);
+
+ this.music = new AudioBus(context, { name: 'music', volume: config.musicVolume ?? DEFAULT_MUSIC_VOLUME });
+ this.master.addChild(this.music);
+
+ this.sfx = new AudioBus(context, { name: 'sfx', volume: config.sfxVolume ?? 1.0 });
+ this.master.addChild(this.sfx);
+
+ this.ui = new AudioBus(context, { name: 'ui', volume: config.uiVolume ?? 1.0 });
+ this.master.addChild(this.ui);
+
+ this.voice = new AudioBus(context, { name: 'voice', volume: config.voiceVolume ?? 1.0 });
+ this.master.addChild(this.voice);
+
+ this.buses_.set('master', this.master);
+ this.buses_.set('music', this.music);
+ this.buses_.set('sfx', this.sfx);
+ this.buses_.set('ui', this.ui);
+ this.buses_.set('voice', this.voice);
+ }
+
+ getBus(name: string): AudioBus | undefined {
+ return this.buses_.get(name);
+ }
+
+ createBus(config: AudioBusConfig): AudioBus {
+ const bus = new AudioBus(this.context_, config);
+ const parent = config.parent ? this.buses_.get(config.parent) : this.master;
+ if (parent) {
+ parent.addChild(bus);
+ }
+ this.buses_.set(config.name, bus);
+ return bus;
+ }
+}
diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.ts
new file mode 100644
index 000000000..e082874df
--- /dev/null
+++ b/sdk/src/audio/AudioPlugin.ts
@@ -0,0 +1,115 @@
+import type { App, Plugin } from '../app';
+import { defineSystem, Schedule } from '../system';
+import { Res, Time, type TimeData } from '../resource';
+import { Audio } from './Audio';
+import { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';
+import { WorldTransform, type WorldTransformData } from '../component';
+import { createAudioBackend } from './AudioBackendFactory';
+import { WebAudioBackend } from './WebAudioBackend';
+import { calculateAttenuation, calculatePanning, type SpatialAudioConfig, AttenuationModel } from './SpatialAudio';
+import type { AudioHandle } from './PlatformAudioBackend';
+
+export interface AudioPluginConfig {
+ maxPoolSize?: number;
+ masterVolume?: number;
+ musicVolume?: number;
+ sfxVolume?: number;
+}
+
+export class AudioPlugin implements Plugin {
+ name = 'AudioPlugin';
+ private config_: AudioPluginConfig;
+
+ constructor(config: AudioPluginConfig = {}) {
+ this.config_ = config;
+ }
+
+ build(app: App): void {
+ const backend = createAudioBackend();
+ backend.initialize();
+
+ let mixer = null;
+ if (backend instanceof WebAudioBackend) {
+ mixer = backend.mixer;
+ }
+ Audio.init(backend, mixer);
+
+ const activeSourceHandles = new Map<number, AudioHandle>();
+
+ app.addSystemToSchedule(
+ Schedule.PreUpdate,
+ defineSystem(
+ [Res(Time)],
+ (_time: TimeData) => {
+ const world = app.world;
+
+ let listenerX = 0;
+ let listenerY = 0;
+ const listeners = world.getEntitiesWithComponents([AudioListener, WorldTransform]);
+ for (const entity of listeners) {
+ const listener = world.get(entity, AudioListener) as AudioListenerData;
+ if (listener.enabled) {
+ const wt = world.get(entity, WorldTransform) as WorldTransformData;
+ listenerX = wt.position.x;
+ listenerY = wt.position.y;
+ break;
+ }
+ }
+
+ const sources = world.getEntitiesWithComponents([AudioSource, WorldTransform]);
+ for (const entity of sources) {
+ const source = world.get(entity, AudioSource) as AudioSourceData;
+ if (!source.enabled || !source.clip) continue;
+
+ const wt = world.get(entity, WorldTransform) as WorldTransformData;
+
+ if (source.playOnAwake && !activeSourceHandles.has(entity)) {
+ const buffer = Audio.getBufferHandle(source.clip);
+ if (buffer) {
+ const handle = backend.play(buffer, {
+ bus: source.bus,
+ volume: source.volume,
+ loop: source.loop,
+ playbackRate: source.pitch,
+ priority: source.priority,
+ });
+ activeSourceHandles.set(entity, handle);
+ }
+ }
+
+ if (source.spatial && activeSourceHandles.has(entity)) {
+ const handle = activeSourceHandles.get(entity)!;
+ const dx = wt.position.x - listenerX;
+ const dy = wt.position.y - listenerY;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+
+ const spatialConfig: SpatialAudioConfig = {
+ model: source.attenuationModel as AttenuationModel,
+ refDistance: source.minDistance,
+ maxDistance: source.maxDistance,
+ rolloff: source.rolloff,
+ };
+
+ const attenuation = calculateAttenuation(distance, spatialConfig);
+ const pan = calculatePanning(
+ wt.position.x, wt.position.y,
+ listenerX, listenerY,
+ source.maxDistance
+ );
+
+ handle.setVolume(source.volume * attenuation);
+ handle.setPan(pan);
+ }
+ }
+ },
+ { name: 'AudioUpdateSystem' }
+ )
+ );
+ }
+
+ cleanup(): void {
+ // Backend disposal handled by app shutdown
+ }
+}
+
+export const audioPlugin = new AudioPlugin();
diff --git a/sdk/src/audio/AudioPool.ts b/sdk/src/audio/AudioPool.ts
new file mode 100644
index 000000000..6e5f7d5ce
--- /dev/null
+++ b/sdk/src/audio/AudioPool.ts
@@ -0,0 +1,70 @@
+export interface PooledAudioNode {
+ gain: GainNode;
+ panner: StereoPannerNode;
+ source: AudioBufferSourceNode | null;
+ inUse: boolean;
+ priority: number;
+ startTime: number;
+}
+
+const DEFAULT_INITIAL_SIZE = 16;
+
+export class AudioPool {
+ private readonly context_: AudioContext;
+ private readonly pool_: PooledAudioNode[] = [];
+
+ constructor(context: AudioContext, initialSize: number = DEFAULT_INITIAL_SIZE) {
+ this.context_ = context;
+ for (let i = 0; i < initialSize; i++) {
+ this.pool_.push(this.createNode());
+ }
+ }
+
+ private createNode(): PooledAudioNode {
+ const gain = this.context_.createGain();
+ const panner = this.context_.createStereoPanner();
+ gain.connect(panner);
+ return {
+ gain,
+ panner,
+ source: null,
+ inUse: false,
+ priority: 0,
+ startTime: 0,
+ };
+ }
+
+ acquire(priority: number = 0): PooledAudioNode {
+ let freeNode = this.pool_.find(n => !n.inUse);
+
+ if (!freeNode) {
+ freeNode = this.createNode();
+ this.pool_.push(freeNode);
+ }
+
+ freeNode.inUse = true;
+ freeNode.priority = priority;
+ freeNode.startTime = this.context_.currentTime;
+ freeNode.gain.gain.value = 1.0;
+ freeNode.panner.pan.value = 0;
+ return freeNode;
+ }
+
+ release(node: PooledAudioNode): void {
+ if (node.source) {
+ try { node.source.stop(); } catch (_) { /* already stopped */ }
+ node.source.disconnect();
+ node.source = null;
+ }
+ node.inUse = false;
+ node.priority = 0;
+ }
+
+ get activeCount(): number {
+ return this.pool_.filter(n => n.inUse).length;
+ }
+
+ get capacity(): number {
+ return this.pool_.length;
+ }
+}
diff --git a/sdk/src/audio/PlatformAudioBackend.ts b/sdk/src/audio/PlatformAudioBackend.ts
new file mode 100644
index 000000000..b919f115a
--- /dev/null
+++ b/sdk/src/audio/PlatformAudioBackend.ts
@@ -0,0 +1,41 @@
+export interface AudioHandle {
+ readonly id: number;
+ stop(): void;
+ pause(): void;
+ resume(): void;
+ setVolume(volume: number): void;
+ setPan(pan: number): void;
+ setLoop(loop: boolean): void;
+ setPlaybackRate(rate: number): void;
+ readonly isPlaying: boolean;
+ readonly currentTime: number;
+ readonly duration: number;
+ onEnd?: () => void;
+}
+
+export interface AudioBufferHandle {
+ readonly id: number;
+ readonly duration: number;
+}
+
+export interface PlayConfig {
+ volume?: number;
+ pan?: number;
+ loop?: boolean;
+ playbackRate?: number;
+ bus?: string;
+ priority?: number;
+ startOffset?: number;
+}
+
+export interface PlatformAudioBackend {
+ readonly name: string;
+ initialize(): Promise<void>;
+ ensureResumed(): Promise<void>;
+ loadBuffer(url: string): Promise<AudioBufferHandle>;
+ unloadBuffer(handle: AudioBufferHandle): void;
+ play(buffer: AudioBufferHandle, config: PlayConfig): AudioHandle;
+ suspend(): void;
+ resume(): void;
+ dispose(): void;
+}
diff --git a/sdk/src/audio/SpatialAudio.ts b/sdk/src/audio/SpatialAudio.ts
new file mode 100644
index 000000000..05af9f5da
--- /dev/null
+++ b/sdk/src/audio/SpatialAudio.ts
@@ -0,0 +1,51 @@
+export enum AttenuationModel {
+ Linear = 0,
+ Inverse,
+ Exponential,
+}
+
+export interface SpatialAudioConfig {
+ model: AttenuationModel;
+ refDistance: number;
+ maxDistance: number;
+ rolloff: number;
+}
+
+const DEFAULT_SPATIAL_CONFIG: SpatialAudioConfig = {
+ model: AttenuationModel.Inverse,
+ refDistance: 100,
+ maxDistance: 1000,
+ rolloff: 1.0,
+};
+
+export function calculateAttenuation(
+ distance: number,
+ config: SpatialAudioConfig = DEFAULT_SPATIAL_CONFIG
+): number {
+ const { model, refDistance, maxDistance, rolloff } = config;
+ const d = Math.max(distance, 0.001);
+
+ switch (model) {
+ case AttenuationModel.Linear: {
+ const clamped = Math.min(Math.max(d, refDistance), maxDistance);
+ return 1 - (clamped - refDistance) / (maxDistance - refDistance);
+ }
+ case AttenuationModel.Inverse: {
+ return refDistance / Math.max(d, refDistance);
+ }
+ case AttenuationModel.Exponential: {
+ return Math.pow(Math.max(d, refDistance) / refDistance, -rolloff);
+ }
+ default:
+ return 1;
+ }
+}
+
+export function calculatePanning(
+ sourceX: number, sourceY: number,
+ listenerX: number, listenerY: number,
+ maxDistance: number
+): number {
+ const dx = sourceX - listenerX;
+ return Math.max(-1, Math.min(1, dx / maxDistance));
+}
diff --git a/sdk/src/audio/WeChatAudioBackend.ts b/sdk/src/audio/WeChatAudioBackend.ts
new file mode 100644
index 000000000..c65f6531f
--- /dev/null
+++ b/sdk/src/audio/WeChatAudioBackend.ts
@@ -0,0 +1,156 @@
+import type { AudioHandle, AudioBufferHandle, PlayConfig, PlatformAudioBackend } from './PlatformAudioBackend';
+
+interface WxInnerAudioContext {
+ src: string;
+ startTime: number;
+ autoplay: boolean;
+ loop: boolean;
+ obeyMuteSwitch: boolean;
+ volume: number;
+ playbackRate: number;
+ duration: number;
+ currentTime: number;
+ paused: boolean;
+ play(): void;
+ pause(): void;
+ stop(): void;
+ seek(position: number): void;
+ destroy(): void;
+ onEnded(callback: () => void): void;
+ offEnded(callback: () => void): void;
+ onError(callback: (res: { errMsg: string }) => void): void;
+}
+
+class WeChatAudioHandle implements AudioHandle {
+ readonly id: number;
+ onEnd?: () => void;
+
+ private ctx_: WxInnerAudioContext;
+ private contexts_: Map<number, WxInnerAudioContext>;
+
+ constructor(id: number, ctx: WxInnerAudioContext, contexts: Map<number, WxInnerAudioContext>) {
+ this.id = id;
+ this.ctx_ = ctx;
+ this.contexts_ = contexts;
+ }
+
+ stop(): void {
+ this.ctx_.stop();
+ this.ctx_.destroy();
+ this.contexts_.delete(this.id);
+ }
+
+ pause(): void {
+ this.ctx_.pause();
+ }
+
+ resume(): void {
+ this.ctx_.play();
+ }
+
+ setVolume(volume: number): void {
+ this.ctx_.volume = volume;
+ }
+
+ setPan(_pan: number): void {
+ // InnerAudioContext does not support panning
+ }
+
+ setLoop(loop: boolean): void {
+ this.ctx_.loop = loop;
+ }
+
+ setPlaybackRate(rate: number): void {
+ this.ctx_.playbackRate = rate;
+ }
+
+ get isPlaying(): boolean {
+ return !this.ctx_.paused;
+ }
+
+ get currentTime(): number {
+ return this.ctx_.currentTime;
+ }
+
+ get duration(): number {
+ return this.ctx_.duration;
+ }
+}
+
+export class WeChatAudioBackend implements PlatformAudioBackend {
+ readonly name = 'WeChat';
+
+ private contexts_ = new Map<number, WxInnerAudioContext>();
+ private urlCache_ = new Map<number, string>();
+ private nextId_ = 0;
+
+ async initialize(): Promise<void> {
+ // wx.createInnerAudioContext does not require global initialization
+ }
+
+ async ensureResumed(): Promise<void> {
+ // WeChat does not require user interaction to resume
+ }
+
+ async loadBuffer(url: string): Promise<AudioBufferHandle> {
+ const id = ++this.nextId_;
+ this.urlCache_.set(id, url);
+ return { id, duration: 0 };
+ }
+
+ unloadBuffer(handle: AudioBufferHandle): void {
+ this.urlCache_.delete(handle.id);
+ }
+
+ play(buffer: AudioBufferHandle, config: PlayConfig): AudioHandle {
+ const url = this.urlCache_.get(buffer.id);
+ if (!url) {
+ throw new Error(`Buffer ${buffer.id} not found`);
+ }
+
+ const ctx: WxInnerAudioContext = (wx as any).createInnerAudioContext();
+ ctx.src = url;
+ ctx.loop = config.loop ?? false;
+ ctx.volume = config.volume ?? 1.0;
+ ctx.playbackRate = config.playbackRate ?? 1.0;
+ ctx.startTime = config.startOffset ?? 0;
+ ctx.autoplay = true;
+ ctx.obeyMuteSwitch = false;
+
+ const handleId = ++this.nextId_;
+ this.contexts_.set(handleId, ctx);
+
+ const handle = new WeChatAudioHandle(handleId, ctx, this.contexts_);
+ ctx.onEnded(() => {
+ handle.onEnd?.();
+ if (!ctx.loop) {
+ ctx.destroy();
+ this.contexts_.delete(handleId);
+ }
+ });
+
+ return handle;
+ }
+
+ suspend(): void {
+ for (const ctx of this.contexts_.values()) {
+ ctx.pause();
+ }
+ }
+
+ resume(): void {
+ for (const ctx of this.contexts_.values()) {
+ if (ctx.paused) {
+ ctx.play();
+ }
+ }
+ }
+
+ dispose(): void {
+ for (const ctx of this.contexts_.values()) {
+ ctx.destroy();
+ }
+ this.contexts_.clear();
+ this.urlCache_.clear();
+ }
+}
diff --git a/sdk/src/audio/WebAudioBackend.ts b/sdk/src/audio/WebAudioBackend.ts
new file mode 100644
index 000000000..5186a20fe
--- /dev/null
+++ b/sdk/src/audio/WebAudioBackend.ts
@@ -0,0 +1,202 @@
+import type { AudioHandle, AudioBufferHandle, PlayConfig, PlatformAudioBackend } from './PlatformAudioBackend';
+import { AudioMixer, type AudioMixerConfig } from './AudioMixer';
+import { AudioPool, type PooledAudioNode } from './AudioPool';
+
+class WebAudioHandle implements AudioHandle {
+ readonly id: number;
+ onEnd?: () => void;
+
+ private source_: AudioBufferSourceNode;
+ private poolNode_: PooledAudioNode;
+ private pool_: AudioPool;
+ private context_: AudioContext;
+ private playing_ = true;
+
+ constructor(
+ id: number,
+ source: AudioBufferSourceNode,
+ poolNode: PooledAudioNode,
+ pool: AudioPool,
+ context: AudioContext,
+ ) {
+ this.id = id;
+ this.source_ = source;
+ this.poolNode_ = poolNode;
+ this.pool_ = pool;
+ this.context_ = context;
+ }
+
+ stop(): void {
+ this.playing_ = false;
+ this.pool_.release(this.poolNode_);
+ }
+
+ pause(): void {
+ if (this.playing_) {
+ this.playing_ = false;
+ this.source_.playbackRate.value = 0;
+ }
+ }
+
+ resume(): void {
+ if (!this.playing_) {
+ this.playing_ = true;
+ this.source_.playbackRate.value = 1;
+ }
+ }
+
+ setVolume(volume: number): void {
+ this.poolNode_.gain.gain.value = volume;
+ }
+
+ setPan(pan: number): void {
+ this.poolNode_.panner.pan.value = pan;
+ }
+
+ setLoop(loop: boolean): void {
+ this.source_.loop = loop;
+ }
+
+ setPlaybackRate(rate: number): void {
+ this.source_.playbackRate.value = rate;
+ }
+
+ get isPlaying(): boolean {
+ return this.playing_;
+ }
+
+ get currentTime(): number {
+ if (!this.playing_) return 0;
+ return this.context_.currentTime - this.poolNode_.startTime;
+ }
+
+ get duration(): number {
+ return this.source_.buffer?.duration ?? 0;
+ }
+
+ markEnded(): void {
+ this.playing_ = false;
+ }
+}
+
+export interface WebAudioBackendOptions {
+ initialPoolSize?: number;
+ mixerConfig?: AudioMixerConfig;
+}
+
+export class WebAudioBackend implements PlatformAudioBackend {
+ readonly name = 'WebAudio';
+
+ private context_: AudioContext | null = null;
+ private mixer_: AudioMixer | null = null;
+ private pool_: AudioPool | null = null;
+ private buffers_ = new Map<number, AudioBuffer>();
+ private nextBufferId_ = 0;
+ private nextHandleId_ = 0;
+
+ get mixer(): AudioMixer | null {
+ return this.mixer_;
+ }
+
+ async initialize(options: WebAudioBackendOptions = {}): Promise<void> {
+ this.context_ = new AudioContext();
+ this.mixer_ = new AudioMixer(this.context_, options.mixerConfig);
+ this.pool_ = new AudioPool(this.context_, options.initialPoolSize);
+
+ if (this.context_.state === 'suspended') {
+ const resume = () => {
+ this.context_!.resume();
+ document.removeEventListener('touchstart', resume);
+ document.removeEventListener('mousedown', resume);
+ document.removeEventListener('keydown', resume);
+ };
+ document.addEventListener('touchstart', resume, { once: true });
+ document.addEventListener('mousedown', resume, { once: true });
+ document.addEventListener('keydown', resume, { once: true });
+ }
+ }
+
+ async ensureResumed(): Promise<void> {
+ if (this.context_ && this.context_.state === 'suspended') {
+ await this.context_.resume();
+ }
+ }
+
+ async loadBuffer(url: string): Promise<AudioBufferHandle> {
+ if (!this.context_) {
+ throw new Error('AudioContext not initialized');
+ }
+ const response = await fetch(url);
+ const arrayBuffer = await response.arrayBuffer();
+ const audioBuffer = await this.context_.decodeAudioData(arrayBuffer);
+
+ const id = ++this.nextBufferId_;
+ this.buffers_.set(id, audioBuffer);
+
+ return { id, duration: audioBuffer.duration };
+ }
+
+ unloadBuffer(handle: AudioBufferHandle): void {
+ this.buffers_.delete(handle.id);
+ }
+
+ play(buffer: AudioBufferHandle, config: PlayConfig): AudioHandle {
+ if (!this.context_ || !this.pool_ || !this.mixer_) {
+ throw new Error('Audio system not initialized');
+ }
+
+ const audioBuffer = this.buffers_.get(buffer.id);
+ if (!audioBuffer) {
+ throw new Error(`Buffer ${buffer.id} not found`);
+ }
+
+ const poolNode = this.pool_.acquire(config.priority ?? 0);
+ const source = this.context_.createBufferSource();
+ source.buffer = audioBuffer;
+ source.loop = config.loop ?? false;
+ source.playbackRate.value = config.playbackRate ?? 1.0;
+ source.connect(poolNode.gain);
+ poolNode.source = source;
+
+ poolNode.gain.gain.value = config.volume ?? 1.0;
+ poolNode.panner.pan.value = config.pan ?? 0;
+
+ const busName = config.bus ?? 'sfx';
+ const bus = this.mixer_.getBus(busName) ?? this.mixer_.sfx;
+ poolNode.panner.connect(bus.node);
+
+ source.start(0, config.startOffset ?? 0);
+
+ const handleId = ++this.nextHandleId_;
+ const handle = new WebAudioHandle(
+ handleId, source, poolNode, this.pool_, this.context_
+ );
+
+ source.onended = () => {
+ if (!source.loop) {
+ handle.markEnded();
+ this.pool_!.release(poolNode);
+ handle.onEnd?.();
+ }
+ };
+
+ return handle;
+ }
+
+ suspend(): void {
+ this.context_?.suspend();
+ }
+
+ resume(): void {
+ this.context_?.resume();
+ }
+
+ dispose(): void {
+ this.pool_ = null;
+ this.mixer_ = null;
+ this.buffers_.clear();
+ this.context_?.close();
+ this.context_ = null;
+ }
+
+}
diff --git a/sdk/src/audio/index.ts b/sdk/src/audio/index.ts
new file mode 100644
index 000000000..eb9e4d0be
--- /dev/null
+++ b/sdk/src/audio/index.ts
@@ -0,0 +1,11 @@
+export { Audio } from './Audio';
+export { AudioBus, type AudioBusConfig } from './AudioBus';
+export { AudioMixer, type AudioMixerConfig } from './AudioMixer';
+export { AudioPool, type PooledAudioNode } from './AudioPool';
+export { AudioPlugin, audioPlugin, type AudioPluginConfig } from './AudioPlugin';
+export { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';
+export { createAudioBackend } from './AudioBackendFactory';
+export { AttenuationModel, calculateAttenuation, calculatePanning, type SpatialAudioConfig } from './SpatialAudio';
+export { WebAudioBackend, type WebAudioBackendOptions } from './WebAudioBackend';
+export { WeChatAudioBackend } from './WeChatAudioBackend';
+export type { AudioHandle, AudioBufferHandle, PlayConfig, PlatformAudioBackend } from './PlatformAudioBackend';
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 4f05b4071..894303d0c 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -653,6 +653,37 @@ export {
type AnimClipAssetData,
} from './animation';
+// =============================================================================
+// Audio
+// =============================================================================
+
+export {
+ Audio,
+ AudioPlugin,
+ audioPlugin,
+ AudioSource,
+ AudioListener,
+ AudioBus,
+ AudioMixer,
+ AudioPool,
+ createAudioBackend,
+ AttenuationModel,
+ calculateAttenuation,
+ calculatePanning,
+ type AudioHandle,
+ type AudioBufferHandle,
+ type PlayConfig,
+ type PlatformAudioBackend,
+ type AudioPluginConfig,
+ type AudioBusConfig,
+ type AudioMixerConfig,
+ type SpatialAudioConfig,
+ type AudioSourceData,
+ type AudioListenerData,
+ type PooledAudioNode,
+ type WebAudioBackendOptions,
+} from './audio';
+
// =============================================================================
// Playable Runtime
// =============================================================================
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 8906b91d4..61b63a8e9 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -9,6 +9,7 @@ import { getComponent, Name, Camera } from './component';
import type { AssetServer } from './asset/AssetServer';
import { extractAnimClipTexturePaths, parseAnimClipData, type AnimClipAssetData } from './animation/AnimClipLoader';
import { registerAnimClip } from './animation/SpriteAnimator';
+import { Audio } from './audio/Audio';
// =============================================================================
// Types
@@ -65,7 +66,7 @@ export interface SceneLoadOptions {
// Component Asset Field Registry
// =============================================================================
-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip';
+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio';
interface AssetFieldDescriptor {
field: string;
@@ -111,6 +112,11 @@ const COMPONENT_ASSET_FIELDS = new Map<string, ComponentAssetFields>([
{ field: 'clip', type: 'anim-clip' },
],
}],
+ ['AudioSource', {
+ fields: [
+ { field: 'clip', type: 'audio' },
+ ],
+ }],
]);
export function registerComponentAssetFields(
@@ -350,6 +356,15 @@ const ASSET_FIELD_HANDLERS = new Map<AssetFieldType, AssetFieldHandler>([
return new Map();
},
}],
+ ['audio', {
+ async load(paths, _assetServer, baseUrl) {
+ const urls = [...paths].map(p => baseUrl ? `${baseUrl}/${p}` : `/${p}`);
+ await Audio.preloadAll(urls).catch(err => {
+ console.warn('Failed to preload audio assets:', err);
+ });
+ return new Map();
+ },
+ }],
]);
async function preloadSceneAssets(
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index ca2095b6b..4ec4d1829 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -17,6 +17,7 @@ export { sliderPlugin, SliderPlugin } from './ui/SliderPlugin';
export { PhysicsPlugin, PhysicsEvents, Physics, loadPhysicsModule } from './physics';
export { AnimationPlugin, animationPlugin } from './animation';
+export { AudioPlugin, audioPlugin } from './audio';
const defaultPlugins = [...uiPlugins, animationPlugin];
diff --git a/sdk/tests/audio-api.test.ts b/sdk/tests/audio-api.test.ts
new file mode 100644
index 000000000..b43869929
--- /dev/null
+++ b/sdk/tests/audio-api.test.ts
@@ -0,0 +1,184 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Audio } from '../src/audio/Audio';
+import type { PlatformAudioBackend, AudioHandle, AudioBufferHandle, PlayConfig } from '../src/audio/PlatformAudioBackend';
+import type { AudioMixer } from '../src/audio/AudioMixer';
+import type { AudioBus } from '../src/audio/AudioBus';
+
+function createMockHandle(overrides: Partial<AudioHandle> = {}): AudioHandle {
+ return {
+ id: 1,
+ stop: vi.fn(),
+ pause: vi.fn(),
+ resume: vi.fn(),
+ setVolume: vi.fn(),
+ setPan: vi.fn(),
+ setLoop: vi.fn(),
+ setPlaybackRate: vi.fn(),
+ isPlaying: true,
+ currentTime: 0,
+ duration: 1.0,
+ ...overrides,
+ };
+}
+
+function createMockBus(name: string): AudioBus {
+ return {
+ name,
+ volume: 1.0,
+ muted: false,
+ node: {} as GainNode,
+ connect: vi.fn(),
+ addChild: vi.fn(),
+ } as unknown as AudioBus;
+}
+
+function createMockBackend(): PlatformAudioBackend {
+ return {
+ name: 'MockBackend',
+ initialize: vi.fn().mockResolvedValue(undefined),
+ ensureResumed: vi.fn().mockResolvedValue(undefined),
+ loadBuffer: vi.fn().mockResolvedValue({ id: 1, duration: 2.0 }),
+ unloadBuffer: vi.fn(),
+ play: vi.fn().mockReturnValue(createMockHandle()),
+ suspend: vi.fn(),
+ resume: vi.fn(),
+ dispose: vi.fn(),
+ };
+}
+
+function createMockMixer(): AudioMixer {
+ const masterBus = createMockBus('master');
+ const musicBus = createMockBus('music');
+ const sfxBus = createMockBus('sfx');
+ const uiBus = createMockBus('ui');
+ const voiceBus = createMockBus('voice');
+
+ return {
+ master: masterBus,
+ music: musicBus,
+ sfx: sfxBus,
+ ui: uiBus,
+ voice: voiceBus,
+ getBus: vi.fn((name: string) => {
+ const map: Record<string, AudioBus> = { master: masterBus, music: musicBus, sfx: sfxBus, ui: uiBus, voice: voiceBus };
+ return map[name];
+ }),
+ createBus: vi.fn(),
+ } as unknown as AudioMixer;
+}
+
+describe('Audio', () => {
+ let backend: PlatformAudioBackend;
+ let mixer: AudioMixer;
+
+ beforeEach(() => {
+ backend = createMockBackend();
+ mixer = createMockMixer();
+ Audio.init(backend, mixer);
+ });
+
+ describe('preload', () => {
+ it('should load buffer via backend', async () => {
+ await Audio.preload('sfx.mp3');
+ expect(backend.loadBuffer).toHaveBeenCalledWith('sfx.mp3');
+ });
+
+ it('should not reload already cached buffer', async () => {
+ await Audio.preload('sfx.mp3');
+ await Audio.preload('sfx.mp3');
+ expect(backend.loadBuffer).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('preloadAll', () => {
+ it('should load multiple buffers in parallel', async () => {
+ await Audio.preloadAll(['a.mp3', 'b.mp3', 'c.mp3']);
+ expect(backend.loadBuffer).toHaveBeenCalledTimes(3);
+ });
+ });
+
+ describe('playSFX', () => {
+ it('should play from cached buffer', async () => {
+ await Audio.preload('click.mp3');
+ const handle = Audio.playSFX('click.mp3', { volume: 0.5 });
+ expect(backend.play).toHaveBeenCalledWith(
+ { id: 1, duration: 2.0 },
+ expect.objectContaining({ bus: 'sfx', volume: 0.5 })
+ );
+ });
+
+ it('should return pending handle for uncached buffer', () => {
+ const handle = Audio.playSFX('uncached.mp3');
+ expect(handle.id).toBe(-1);
+ expect(handle.isPlaying).toBe(false);
+ });
+ });
+
+ describe('playBGM', () => {
+ it('should play as looping music', async () => {
+ await Audio.preload('bgm.mp3');
+ Audio.playBGM('bgm.mp3');
+ expect(backend.play).toHaveBeenCalledWith(
+ { id: 1, duration: 2.0 },
+ expect.objectContaining({ bus: 'music', loop: true })
+ );
+ });
+
+ it('should stop previous BGM', async () => {
+ await Audio.preload('bgm1.mp3');
+ const firstHandle = createMockHandle();
+ (backend.play as ReturnType<typeof vi.fn>).mockReturnValue(firstHandle);
+ Audio.playBGM('bgm1.mp3');
+
+ const secondHandle = createMockHandle();
+ (backend.play as ReturnType<typeof vi.fn>).mockReturnValue(secondHandle);
+ Audio.playBGM('bgm1.mp3');
+
+ expect(firstHandle.stop).toHaveBeenCalled();
+ });
+ });
+
+ describe('stopBGM', () => {
+ it('should stop current BGM', async () => {
+ await Audio.preload('bgm.mp3');
+ const mockHandle = createMockHandle();
+ (backend.play as ReturnType<typeof vi.fn>).mockReturnValue(mockHandle);
+ Audio.playBGM('bgm.mp3');
+ Audio.stopBGM();
+ expect(mockHandle.stop).toHaveBeenCalled();
+ });
+
+ it('should do nothing if no BGM playing', () => {
+ expect(() => Audio.stopBGM()).not.toThrow();
+ });
+ });
+
+ describe('volume controls', () => {
+ it('should set master volume', () => {
+ Audio.setMasterVolume(0.5);
+ expect(mixer.master.volume).toBe(0.5);
+ });
+
+ it('should set music volume', () => {
+ Audio.setMusicVolume(0.3);
+ expect(mixer.music.volume).toBe(0.3);
+ });
+
+ it('should set sfx volume', () => {
+ Audio.setSFXVolume(0.7);
+ expect(mixer.sfx.volume).toBe(0.7);
+ });
+
+ it('should set ui volume', () => {
+ Audio.setUIVolume(0.6);
+ expect(mixer.ui.volume).toBe(0.6);
+ });
+ });
+
+ describe('muteBus', () => {
+ it('should mute specified bus', () => {
+ Audio.muteBus('sfx', true);
+ expect(mixer.getBus).toHaveBeenCalledWith('sfx');
+ });
+ });
+});
diff --git a/sdk/tests/audio-backend-factory.test.ts b/sdk/tests/audio-backend-factory.test.ts
new file mode 100644
index 000000000..893943c5e
--- /dev/null
+++ b/sdk/tests/audio-backend-factory.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { createAudioBackend } from '../src/audio/AudioBackendFactory';
+import { setPlatform } from '../src/platform/base';
+import { WebAudioBackend } from '../src/audio/WebAudioBackend';
+import { WeChatAudioBackend } from '../src/audio/WeChatAudioBackend';
+
+describe('AudioBackendFactory', () => {
+ describe('createAudioBackend', () => {
+ it('should return WebAudioBackend for web platform', () => {
+ setPlatform({ name: 'web' } as any);
+ const backend = createAudioBackend();
+ expect(backend).toBeInstanceOf(WebAudioBackend);
+ });
+
+ it('should return WeChatAudioBackend for wechat platform', () => {
+ setPlatform({ name: 'wechat' } as any);
+ const backend = createAudioBackend();
+ expect(backend).toBeInstanceOf(WeChatAudioBackend);
+ });
+ });
+});
diff --git a/sdk/tests/audio-bus.test.ts b/sdk/tests/audio-bus.test.ts
new file mode 100644
index 000000000..e9b8dd6ea
--- /dev/null
+++ b/sdk/tests/audio-bus.test.ts
@@ -0,0 +1,121 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { AudioBus, type AudioBusConfig } from '../src/audio/AudioBus';
+
+function createMockGainNode(context: AudioContext): GainNode {
+ const gain = {
+ value: 1.0,
+ setTargetAtTime: vi.fn(),
+ } as unknown as AudioParam;
+ return {
+ gain,
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ context,
+ } as unknown as GainNode;
+}
+
+function createMockAudioContext(): AudioContext {
+ const ctx = {
+ currentTime: 0,
+ createGain: vi.fn(),
+ destination: {} as AudioDestinationNode,
+ } as unknown as AudioContext;
+ (ctx.createGain as ReturnType<typeof vi.fn>).mockImplementation(() => createMockGainNode(ctx));
+ return ctx;
+}
+
+describe('AudioBus', () => {
+ let context: AudioContext;
+
+ beforeEach(() => {
+ context = createMockAudioContext();
+ });
+
+ it('should create with default volume 1.0', () => {
+ const bus = new AudioBus(context, { name: 'test' });
+ expect(bus.name).toBe('test');
+ expect(bus.volume).toBe(1.0);
+ expect(bus.muted).toBe(false);
+ });
+
+ it('should create with custom volume', () => {
+ const bus = new AudioBus(context, { name: 'music', volume: 0.8 });
+ expect(bus.volume).toBe(0.8);
+ });
+
+ it('should create muted', () => {
+ const bus = new AudioBus(context, { name: 'test', muted: true });
+ expect(bus.muted).toBe(true);
+ });
+
+ it('should expose the internal GainNode', () => {
+ const bus = new AudioBus(context, { name: 'test' });
+ expect(bus.node).toBeDefined();
+ expect(bus.node.gain).toBeDefined();
+ });
+
+ describe('volume', () => {
+ it('should set volume and update gain', () => {
+ const bus = new AudioBus(context, { name: 'test' });
+ bus.volume = 0.5;
+ expect(bus.volume).toBe(0.5);
+ expect(bus.node.gain.setTargetAtTime).toHaveBeenCalledWith(0.5, 0, 0.015);
+ });
+
+ it('should clamp volume to 0-1', () => {
+ const bus = new AudioBus(context, { name: 'test' });
+ bus.volume = -0.5;
+ expect(bus.volume).toBe(0);
+ bus.volume = 1.5;
+ expect(bus.volume).toBe(1);
+ });
+
+ it('should not update gain when muted', () => {
+ const bus = new AudioBus(context, { name: 'test', muted: true });
+ bus.volume = 0.5;
+ expect(bus.volume).toBe(0.5);
+ expect(bus.node.gain.setTargetAtTime).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('mute', () => {
+ it('should mute by setting gain to 0', () => {
+ const bus = new AudioBus(context, { name: 'test', volume: 0.8 });
+ bus.muted = true;
+ expect(bus.muted).toBe(true);
+ expect(bus.node.gain.setTargetAtTime).toHaveBeenCalledWith(0, 0, 0.015);
+ });
+
+ it('should unmute by restoring volume', () => {
+ const bus = new AudioBus(context, { name: 'test', volume: 0.8 });
+ bus.muted = true;
+ bus.muted = false;
+ expect(bus.node.gain.setTargetAtTime).toHaveBeenLastCalledWith(0.8, 0, 0.015);
+ });
+ });
+
+ describe('connect', () => {
+ it('should connect to another AudioBus', () => {
+ const busA = new AudioBus(context, { name: 'a' });
+ const busB = new AudioBus(context, { name: 'b' });
+ busA.connect(busB);
+ expect(busA.node.connect).toHaveBeenCalledWith(busB.node);
+ });
+
+ it('should connect to a raw AudioNode', () => {
+ const bus = new AudioBus(context, { name: 'test' });
+ const dest = {} as AudioNode;
+ bus.connect(dest);
+ expect(bus.node.connect).toHaveBeenCalledWith(dest);
+ });
+ });
+
+ describe('addChild', () => {
+ it('should connect child to parent', () => {
+ const parent = new AudioBus(context, { name: 'parent' });
+ const child = new AudioBus(context, { name: 'child' });
+ parent.addChild(child);
+ expect(child.node.connect).toHaveBeenCalledWith(parent.node);
+ });
+ });
+});
diff --git a/sdk/tests/audio-components.test.ts b/sdk/tests/audio-components.test.ts
new file mode 100644
index 000000000..40a1a810e
--- /dev/null
+++ b/sdk/tests/audio-components.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { AudioSource, AudioListener } from '../src/audio/AudioComponents';
+import { AttenuationModel } from '../src/audio/SpatialAudio';
+
+describe('AudioComponents', () => {
+ describe('AudioSource', () => {
+ it('should be defined with correct name', () => {
+ expect(AudioSource._name).toBe('AudioSource');
+ });
+
+ it('should have correct defaults', () => {
+ const defaults = AudioSource._default;
+ expect(defaults.clip).toBe('');
+ expect(defaults.bus).toBe('sfx');
+ expect(defaults.volume).toBe(1.0);
+ expect(defaults.pitch).toBe(1.0);
+ expect(defaults.loop).toBe(false);
+ expect(defaults.playOnAwake).toBe(false);
+ expect(defaults.spatial).toBe(false);
+ expect(defaults.minDistance).toBe(100);
+ expect(defaults.maxDistance).toBe(1000);
+ expect(defaults.attenuationModel).toBe(AttenuationModel.Inverse);
+ expect(defaults.rolloff).toBe(1.0);
+ expect(defaults.priority).toBe(0);
+ expect(defaults.enabled).toBe(true);
+ });
+
+ it('should be a user-defined component (not builtin)', () => {
+ expect(AudioSource._builtin).toBe(false);
+ });
+ });
+
+ describe('AudioListener', () => {
+ it('should be defined with correct name', () => {
+ expect(AudioListener._name).toBe('AudioListener');
+ });
+
+ it('should have correct defaults', () => {
+ const defaults = AudioListener._default;
+ expect(defaults.enabled).toBe(true);
+ });
+
+ it('should be a user-defined component (not builtin)', () => {
+ expect(AudioListener._builtin).toBe(false);
+ });
+ });
+});
diff --git a/sdk/tests/audio-mixer.test.ts b/sdk/tests/audio-mixer.test.ts
new file mode 100644
index 000000000..f014d1055
--- /dev/null
+++ b/sdk/tests/audio-mixer.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { AudioMixer } from '../src/audio/AudioMixer';
+
+function createMockGainNode(context: AudioContext): GainNode {
+ const gain = {
+ value: 1.0,
+ setTargetAtTime: vi.fn(),
+ } as unknown as AudioParam;
+ return {
+ gain,
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ context,
+ } as unknown as GainNode;
+}
+
+function createMockAudioContext(): AudioContext {
+ const ctx = {
+ currentTime: 0,
+ createGain: vi.fn(),
+ destination: {} as AudioDestinationNode,
+ } as unknown as AudioContext;
+ (ctx.createGain as ReturnType<typeof vi.fn>).mockImplementation(() => createMockGainNode(ctx));
+ return ctx;
+}
+
+describe('AudioMixer', () => {
+ let context: AudioContext;
+
+ beforeEach(() => {
+ context = createMockAudioContext();
+ });
+
+ it('should create 5 default buses', () => {
+ const mixer = new AudioMixer(context);
+ expect(mixer.master).toBeDefined();
+ expect(mixer.music).toBeDefined();
+ expect(mixer.sfx).toBeDefined();
+ expect(mixer.ui).toBeDefined();
+ expect(mixer.voice).toBeDefined();
+ });
+
+ it('should connect master to destination', () => {
+ const mixer = new AudioMixer(context);
+ expect(mixer.master.node.connect).toHaveBeenCalledWith(context.destination);
+ });
+
+ it('should connect child buses to master', () => {
+ const mixer = new AudioMixer(context);
+ expect(mixer.music.node.connect).toHaveBeenCalledWith(mixer.master.node);
+ expect(mixer.sfx.node.connect).toHaveBeenCalledWith(mixer.master.node);
+ expect(mixer.ui.node.connect).toHaveBeenCalledWith(mixer.master.node);
+ expect(mixer.voice.node.connect).toHaveBeenCalledWith(mixer.master.node);
+ });
+
+ it('should apply custom volumes', () => {
+ const mixer = new AudioMixer(context, {
+ masterVolume: 0.9,
+ musicVolume: 0.5,
+ sfxVolume: 0.7,
+ uiVolume: 0.6,
+ voiceVolume: 0.8,
+ });
+ expect(mixer.master.volume).toBe(0.9);
+ expect(mixer.music.volume).toBe(0.5);
+ expect(mixer.sfx.volume).toBe(0.7);
+ expect(mixer.ui.volume).toBe(0.6);
+ expect(mixer.voice.volume).toBe(0.8);
+ });
+
+ it('should use default volumes', () => {
+ const mixer = new AudioMixer(context);
+ expect(mixer.master.volume).toBe(1.0);
+ expect(mixer.music.volume).toBe(0.8);
+ expect(mixer.sfx.volume).toBe(1.0);
+ expect(mixer.ui.volume).toBe(1.0);
+ expect(mixer.voice.volume).toBe(1.0);
+ });
+
+ describe('getBus', () => {
+ it('should return bus by name', () => {
+ const mixer = new AudioMixer(context);
+ expect(mixer.getBus('master')).toBe(mixer.master);
+ expect(mixer.getBus('music')).toBe(mixer.music);
+ expect(mixer.getBus('sfx')).toBe(mixer.sfx);
+ expect(mixer.getBus('ui')).toBe(mixer.ui);
+ expect(mixer.getBus('voice')).toBe(mixer.voice);
+ });
+
+ it('should return undefined for unknown bus', () => {
+ const mixer = new AudioMixer(context);
+ expect(mixer.getBus('nonexistent')).toBeUndefined();
+ });
+ });
+
+ describe('createBus', () => {
+ it('should create a custom bus connected to master', () => {
+ const mixer = new AudioMixer(context);
+ const custom = mixer.createBus({ name: 'ambient', volume: 0.6 });
+ expect(custom.name).toBe('ambient');
+ expect(custom.volume).toBe(0.6);
+ expect(custom.node.connect).toHaveBeenCalledWith(mixer.master.node);
+ });
+
+ it('should create a custom bus connected to specified parent', () => {
+ const mixer = new AudioMixer(context);
+ const custom = mixer.createBus({ name: 'ambient', parent: 'sfx' });
+ expect(custom.node.connect).toHaveBeenCalledWith(mixer.sfx.node);
+ });
+
+ it('should be retrievable via getBus', () => {
+ const mixer = new AudioMixer(context);
+ const custom = mixer.createBus({ name: 'ambient' });
+ expect(mixer.getBus('ambient')).toBe(custom);
+ });
+ });
+});
diff --git a/sdk/tests/audio-plugin.test.ts b/sdk/tests/audio-plugin.test.ts
new file mode 100644
index 000000000..8de4506db
--- /dev/null
+++ b/sdk/tests/audio-plugin.test.ts
@@ -0,0 +1,20 @@
+import { describe, it, expect, vi } from 'vitest';
+import { AudioPlugin, audioPlugin } from '../src/audio/AudioPlugin';
+
+describe('AudioPlugin', () => {
+ it('should be exported as singleton', () => {
+ expect(audioPlugin).toBeInstanceOf(AudioPlugin);
+ });
+
+ it('should have name "AudioPlugin"', () => {
+ expect(audioPlugin.name).toBe('AudioPlugin');
+ });
+
+ it('should have a build method', () => {
+ expect(typeof audioPlugin.build).toBe('function');
+ });
+
+ it('should have a cleanup method', () => {
+ expect(typeof audioPlugin.cleanup).toBe('function');
+ });
+});
diff --git a/sdk/tests/audio-pool.test.ts b/sdk/tests/audio-pool.test.ts
new file mode 100644
index 000000000..85c31a50d
--- /dev/null
+++ b/sdk/tests/audio-pool.test.ts
@@ -0,0 +1,158 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { AudioPool, type PooledAudioNode } from '../src/audio/AudioPool';
+
+function createMockAudioContext(): AudioContext {
+ const ctx = {
+ currentTime: 0,
+ createGain: vi.fn(),
+ createStereoPanner: vi.fn(),
+ } as unknown as AudioContext;
+
+ (ctx.createGain as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ gain: { value: 1.0 },
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ context: ctx,
+ }));
+
+ (ctx.createStereoPanner as ReturnType<typeof vi.fn>).mockImplementation(() => ({
+ pan: { value: 0 },
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ }));
+
+ return ctx;
+}
+
+describe('AudioPool', () => {
+ let context: AudioContext;
+
+ beforeEach(() => {
+ context = createMockAudioContext();
+ });
+
+ it('should pre-allocate initialSize nodes', () => {
+ const pool = new AudioPool(context, 8);
+ expect(pool.capacity).toBe(8);
+ expect(pool.activeCount).toBe(0);
+ });
+
+ it('should default to 16 pre-allocated slots', () => {
+ const pool = new AudioPool(context);
+ expect(pool.capacity).toBe(16);
+ });
+
+ describe('acquire', () => {
+ it('should acquire a free node', () => {
+ const pool = new AudioPool(context, 4);
+ const node = pool.acquire();
+ expect(node).not.toBeNull();
+ expect(node!.inUse).toBe(true);
+ expect(pool.activeCount).toBe(1);
+ });
+
+ it('should reset gain and pan on acquire', () => {
+ const pool = new AudioPool(context, 4);
+ const node = pool.acquire()!;
+ expect(node.gain.gain.value).toBe(1.0);
+ expect(node.panner.pan.value).toBe(0);
+ });
+
+ it('should set priority and startTime', () => {
+ const pool = new AudioPool(context, 4);
+ const node = pool.acquire(5)!;
+ expect(node.priority).toBe(5);
+ expect(node.startTime).toBe(0);
+ });
+
+ it('should expand pool when all nodes are in use', () => {
+ const pool = new AudioPool(context, 2);
+ pool.acquire();
+ pool.acquire();
+ expect(pool.capacity).toBe(2);
+
+ const node = pool.acquire();
+ expect(node).not.toBeNull();
+ expect(node!.inUse).toBe(true);
+ expect(pool.activeCount).toBe(3);
+ expect(pool.capacity).toBe(3);
+ });
+
+ it('should expand to accommodate many concurrent sounds', () => {
+ const pool = new AudioPool(context, 2);
+ const nodes: PooledAudioNode[] = [];
+ for (let i = 0; i < 100; i++) {
+ const n = pool.acquire();
+ expect(n).not.toBeNull();
+ nodes.push(n!);
+ }
+ expect(pool.activeCount).toBe(100);
+ expect(pool.capacity).toBe(100);
+ });
+
+ it('should reuse released nodes before expanding', () => {
+ const pool = new AudioPool(context, 2);
+ const n1 = pool.acquire()!;
+ const n2 = pool.acquire()!;
+ pool.release(n1);
+
+ const n3 = pool.acquire()!;
+ expect(pool.capacity).toBe(2);
+ expect(pool.activeCount).toBe(2);
+ });
+ });
+
+ describe('release', () => {
+ it('should mark node as free', () => {
+ const pool = new AudioPool(context, 4);
+ const node = pool.acquire()!;
+ expect(pool.activeCount).toBe(1);
+ pool.release(node);
+ expect(pool.activeCount).toBe(0);
+ expect(node.inUse).toBe(false);
+ });
+
+ it('should stop and disconnect source', () => {
+ const pool = new AudioPool(context, 4);
+ const node = pool.acquire()!;
+ const mockSource = {
+ stop: vi.fn(),
+ disconnect: vi.fn(),
+ } as unknown as AudioBufferSourceNode;
+ node.source = mockSource;
+
+ pool.release(node);
+ expect(mockSource.stop).toHaveBeenCalled();
+ expect(mockSource.disconnect).toHaveBeenCalled();
+ expect(node.source).toBeNull();
+ });
+
+ it('should handle already stopped source gracefully', () => {
+ const pool = new AudioPool(context, 4);
+ const node = pool.acquire()!;
+ node.source = {
+ stop: vi.fn().mockImplementation(() => { throw new Error('already stopped'); }),
+ disconnect: vi.fn(),
+ } as unknown as AudioBufferSourceNode;
+
+ expect(() => pool.release(node)).not.toThrow();
+ });
+ });
+
+ describe('activeCount', () => {
+ it('should track acquire/release accurately', () => {
+ const pool = new AudioPool(context, 4);
+ expect(pool.activeCount).toBe(0);
+
+ const n1 = pool.acquire()!;
+ const n2 = pool.acquire()!;
+ expect(pool.activeCount).toBe(2);
+
+ pool.release(n1);
+ expect(pool.activeCount).toBe(1);
+
+ pool.release(n2);
+ expect(pool.activeCount).toBe(0);
+ });
+ });
+});
diff --git a/sdk/tests/spatial-audio.test.ts b/sdk/tests/spatial-audio.test.ts
new file mode 100644
index 000000000..df0b7590a
--- /dev/null
+++ b/sdk/tests/spatial-audio.test.ts
@@ -0,0 +1,119 @@
+import { describe, it, expect } from 'vitest';
+import {
+ AttenuationModel,
+ calculateAttenuation,
+ calculatePanning,
+ type SpatialAudioConfig,
+} from '../src/audio/SpatialAudio';
+
+describe('SpatialAudio', () => {
+ describe('calculateAttenuation', () => {
+ const defaultConfig: SpatialAudioConfig = {
+ model: AttenuationModel.Inverse,
+ refDistance: 100,
+ maxDistance: 1000,
+ rolloff: 1.0,
+ };
+
+ describe('Linear model', () => {
+ const config: SpatialAudioConfig = {
+ ...defaultConfig,
+ model: AttenuationModel.Linear,
+ };
+
+ it('should return 1 at ref distance', () => {
+ expect(calculateAttenuation(100, config)).toBeCloseTo(1.0);
+ });
+
+ it('should return 0 at max distance', () => {
+ expect(calculateAttenuation(1000, config)).toBeCloseTo(0.0);
+ });
+
+ it('should return 0.5 at midpoint', () => {
+ const mid = (100 + 1000) / 2;
+ expect(calculateAttenuation(mid, config)).toBeCloseTo(0.5);
+ });
+
+ it('should clamp below ref distance', () => {
+ expect(calculateAttenuation(50, config)).toBeCloseTo(1.0);
+ });
+
+ it('should clamp above max distance', () => {
+ expect(calculateAttenuation(2000, config)).toBeCloseTo(0.0);
+ });
+ });
+
+ describe('Inverse model', () => {
+ it('should return 1 at ref distance', () => {
+ expect(calculateAttenuation(100, defaultConfig)).toBeCloseTo(1.0);
+ });
+
+ it('should return ref/distance for distances > ref', () => {
+ expect(calculateAttenuation(200, defaultConfig)).toBeCloseTo(0.5);
+ expect(calculateAttenuation(400, defaultConfig)).toBeCloseTo(0.25);
+ });
+
+ it('should clamp below ref distance to 1', () => {
+ expect(calculateAttenuation(50, defaultConfig)).toBeCloseTo(1.0);
+ });
+ });
+
+ describe('Exponential model', () => {
+ const config: SpatialAudioConfig = {
+ ...defaultConfig,
+ model: AttenuationModel.Exponential,
+ rolloff: 1.0,
+ };
+
+ it('should return 1 at ref distance', () => {
+ expect(calculateAttenuation(100, config)).toBeCloseTo(1.0);
+ });
+
+ it('should follow power curve', () => {
+ expect(calculateAttenuation(200, config)).toBeCloseTo(0.5);
+ });
+
+ it('should clamp below ref distance to 1', () => {
+ expect(calculateAttenuation(50, config)).toBeCloseTo(1.0);
+ });
+ });
+
+ it('should handle zero distance safely', () => {
+ expect(calculateAttenuation(0, defaultConfig)).toBeCloseTo(1.0);
+ });
+
+ it('should use default config when not provided', () => {
+ expect(calculateAttenuation(100)).toBeCloseTo(1.0);
+ });
+ });
+
+ describe('calculatePanning', () => {
+ it('should return 0 when source is directly above/below listener', () => {
+ expect(calculatePanning(100, 200, 100, 0, 1000)).toBeCloseTo(0);
+ });
+
+ it('should return positive for source to the right', () => {
+ const pan = calculatePanning(600, 0, 100, 0, 1000);
+ expect(pan).toBeGreaterThan(0);
+ expect(pan).toBeCloseTo(0.5);
+ });
+
+ it('should return negative for source to the left', () => {
+ const pan = calculatePanning(-400, 0, 100, 0, 1000);
+ expect(pan).toBeLessThan(0);
+ expect(pan).toBeCloseTo(-0.5);
+ });
+
+ it('should clamp to -1', () => {
+ expect(calculatePanning(-2000, 0, 0, 0, 1000)).toBe(-1);
+ });
+
+ it('should clamp to 1', () => {
+ expect(calculatePanning(2000, 0, 0, 0, 1000)).toBe(1);
+ });
+
+ it('should return 0 when source equals listener', () => {
+ expect(calculatePanning(100, 100, 100, 100, 1000)).toBe(0);
+ });
+ });
+});
diff --git a/sdk/tests/web-audio-backend.test.ts b/sdk/tests/web-audio-backend.test.ts
new file mode 100644
index 000000000..50531806d
--- /dev/null
+++ b/sdk/tests/web-audio-backend.test.ts
@@ -0,0 +1,194 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { WebAudioBackend } from '../src/audio/WebAudioBackend';
+
+function createMockGainNode(context: any): any {
+ return {
+ gain: { value: 1.0, setTargetAtTime: vi.fn() },
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ context,
+ };
+}
+
+function createMockPannerNode(): any {
+ return {
+ pan: { value: 0 },
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ };
+}
+
+function createMockBufferSource(): any {
+ const source: any = {
+ buffer: null,
+ loop: false,
+ playbackRate: { value: 1.0 },
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ start: vi.fn(),
+ stop: vi.fn(),
+ onended: null,
+ };
+ return source;
+}
+
+function setupMockAudioContext(): void {
+ const mockCtx: any = {
+ state: 'running',
+ currentTime: 0,
+ destination: {},
+ createGain: vi.fn(),
+ createStereoPanner: vi.fn(),
+ createBufferSource: vi.fn(),
+ decodeAudioData: vi.fn(),
+ resume: vi.fn().mockResolvedValue(undefined),
+ suspend: vi.fn(),
+ close: vi.fn(),
+ };
+
+ mockCtx.createGain.mockImplementation(() => createMockGainNode(mockCtx));
+ mockCtx.createStereoPanner.mockImplementation(() => createMockPannerNode());
+ mockCtx.createBufferSource.mockImplementation(() => createMockBufferSource());
+
+ (globalThis as any).AudioContext = vi.fn().mockImplementation(() => mockCtx);
+ (globalThis as any).__mockAudioContext = mockCtx;
+}
+
+describe('WebAudioBackend', () => {
+ let backend: WebAudioBackend;
+
+ beforeEach(() => {
+ setupMockAudioContext();
+ backend = new WebAudioBackend();
+ });
+
+ it('should have name "WebAudio"', () => {
+ expect(backend.name).toBe('WebAudio');
+ });
+
+ describe('initialize', () => {
+ it('should create AudioContext', async () => {
+ await backend.initialize();
+ expect(globalThis.AudioContext).toHaveBeenCalled();
+ });
+
+ it('should set up auto-resume listeners when suspended', async () => {
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ mockCtx.state = 'suspended';
+
+ const addEventSpy = vi.spyOn(document, 'addEventListener');
+ await backend.initialize();
+
+ expect(addEventSpy).toHaveBeenCalledWith('touchstart', expect.any(Function), { once: true });
+ expect(addEventSpy).toHaveBeenCalledWith('mousedown', expect.any(Function), { once: true });
+ expect(addEventSpy).toHaveBeenCalledWith('keydown', expect.any(Function), { once: true });
+ addEventSpy.mockRestore();
+ });
+ });
+
+ describe('ensureResumed', () => {
+ it('should resume if suspended', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ mockCtx.state = 'suspended';
+ await backend.ensureResumed();
+ expect(mockCtx.resume).toHaveBeenCalled();
+ });
+
+ it('should not resume if already running', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ mockCtx.state = 'running';
+ mockCtx.resume.mockClear();
+ await backend.ensureResumed();
+ expect(mockCtx.resume).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('loadBuffer', () => {
+ it('should fetch and decode audio data', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+
+ const mockArrayBuffer = new ArrayBuffer(8);
+ const mockAudioBuffer = { duration: 2.5, length: 44100 };
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ arrayBuffer: vi.fn().mockResolvedValue(mockArrayBuffer),
+ }));
+ mockCtx.decodeAudioData.mockResolvedValue(mockAudioBuffer);
+
+ const handle = await backend.loadBuffer('test.mp3');
+ expect(handle.id).toBeGreaterThan(0);
+ expect(handle.duration).toBe(2.5);
+ expect(fetch).toHaveBeenCalledWith('test.mp3');
+ });
+
+ it('should throw if not initialized', async () => {
+ await expect(backend.loadBuffer('test.mp3')).rejects.toThrow('AudioContext not initialized');
+ });
+ });
+
+ describe('play', () => {
+ it('should create source, connect to bus, and start', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+
+ const mockAudioBuffer = { duration: 1.0 };
+ mockCtx.decodeAudioData.mockResolvedValue(mockAudioBuffer);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
+ }));
+
+ const bufferHandle = await backend.loadBuffer('sfx.mp3');
+ const audioHandle = backend.play(bufferHandle, { volume: 0.8, bus: 'sfx' });
+
+ expect(audioHandle.id).toBeGreaterThan(0);
+ expect(mockCtx.createBufferSource).toHaveBeenCalled();
+ });
+
+ it('should throw for unknown buffer', async () => {
+ await backend.initialize();
+ expect(() => backend.play({ id: 999, duration: 0 }, {})).toThrow('Buffer 999 not found');
+ });
+ });
+
+ describe('unloadBuffer', () => {
+ it('should remove buffer from cache', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ mockCtx.decodeAudioData.mockResolvedValue({ duration: 1.0 });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ arrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
+ }));
+
+ const handle = await backend.loadBuffer('test.mp3');
+ backend.unloadBuffer(handle);
+ expect(() => backend.play(handle, {})).toThrow();
+ });
+ });
+
+ describe('suspend/resume', () => {
+ it('should suspend AudioContext', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ backend.suspend();
+ expect(mockCtx.suspend).toHaveBeenCalled();
+ });
+
+ it('should resume AudioContext', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ backend.resume();
+ expect(mockCtx.resume).toHaveBeenCalled();
+ });
+ });
+
+ describe('dispose', () => {
+ it('should close AudioContext and clear state', async () => {
+ await backend.initialize();
+ const mockCtx = (globalThis as any).__mockAudioContext;
+ backend.dispose();
+ expect(mockCtx.close).toHaveBeenCalled();
+ });
+ });
+});
diff --git a/sdk/tests/wechat-audio-backend.test.ts b/sdk/tests/wechat-audio-backend.test.ts
new file mode 100644
index 000000000..4f339dab1
--- /dev/null
+++ b/sdk/tests/wechat-audio-backend.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { WeChatAudioBackend } from '../src/audio/WeChatAudioBackend';
+
+function createMockInnerAudioContext() {
+ return {
+ src: '',
+ startTime: 0,
+ autoplay: false,
+ loop: false,
+ obeyMuteSwitch: true,
+ volume: 1.0,
+ playbackRate: 1.0,
+ duration: 0,
+ currentTime: 0,
+ paused: false,
+ play: vi.fn(),
+ pause: vi.fn(),
+ stop: vi.fn(),
+ seek: vi.fn(),
+ destroy: vi.fn(),
+ onEnded: vi.fn(),
+ offEnded: vi.fn(),
+ onError: vi.fn(),
+ };
+}
+
+describe('WeChatAudioBackend', () => {
+ let backend: WeChatAudioBackend;
+
+ beforeEach(() => {
+ (globalThis as any).wx = {
+ createInnerAudioContext: vi.fn().mockImplementation(createMockInnerAudioContext),
+ };
+ backend = new WeChatAudioBackend();
+ });
+
+ it('should have name "WeChat"', () => {
+ expect(backend.name).toBe('WeChat');
+ });
+
+ describe('initialize', () => {
+ it('should resolve without error', async () => {
+ await expect(backend.initialize()).resolves.toBeUndefined();
+ });
+ });
+
+ describe('loadBuffer', () => {
+ it('should store URL and return handle', async () => {
+ const handle = await backend.loadBuffer('audio/bgm.mp3');
+ expect(handle.id).toBeGreaterThan(0);
+ expect(handle.duration).toBe(0);
+ });
+ });
+
+ describe('unloadBuffer', () => {
+ it('should remove URL from cache', async () => {
+ const handle = await backend.loadBuffer('audio/bgm.mp3');
+ backend.unloadBuffer(handle);
+ expect(() => backend.play(handle, {})).toThrow();
+ });
+ });
+
+ describe('play', () => {
+ it('should create InnerAudioContext and configure it', async () => {
+ const handle = await backend.loadBuffer('audio/sfx.mp3');
+ const audioHandle = backend.play(handle, {
+ volume: 0.7,
+ loop: true,
+ playbackRate: 1.5,
+ startOffset: 2.0,
+ });
+
+ const wx = (globalThis as any).wx;
+ expect(wx.createInnerAudioContext).toHaveBeenCalled();
+ expect(audioHandle.id).toBeGreaterThan(0);
+ });
+
+ it('should throw for unknown buffer', () => {
+ expect(() => backend.play({ id: 999, duration: 0 }, {})).toThrow('Buffer 999 not found');
+ });
+ });
+
+ describe('suspend/resume', () => {
+ it('should pause all active contexts on suspend', async () => {
+ const h1 = await backend.loadBuffer('a.mp3');
+ const h2 = await backend.loadBuffer('b.mp3');
+ backend.play(h1, {});
+ backend.play(h2, {});
+
+ backend.suspend();
+ const wx = (globalThis as any).wx;
+ const calls = wx.createInnerAudioContext.mock.results;
+ for (const call of calls) {
+ expect(call.value.pause).toHaveBeenCalled();
+ }
+ });
+ });
+
+ describe('dispose', () => {
+ it('should destroy all contexts', async () => {
+ const h = await backend.loadBuffer('a.mp3');
+ backend.play(h, {});
+ backend.dispose();
+
+ const wx = (globalThis as any).wx;
+ const calls = wx.createInnerAudioContext.mock.results;
+ for (const call of calls) {
+ expect(call.value.destroy).toHaveBeenCalled();
+ }
+ });
+ });
+});