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 stats panel with StatsPlugin, overlay and editor integration

esengine0d353abc945e
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index bf3f0407b..a26723644 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 i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(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 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,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"},m=new Map,g=new Set;for(const e of p)for(const t of e.extensions)m.set(t,e),g.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function _(e){return m.get(y(e))}function x(e){return g.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 A(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 i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function C(e){return A(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 C(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),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=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(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),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 V(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 Y(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)??Y(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}}),ie=ne,oe=ne,re=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=V("Name",{value:""}),me=V("SceneOwner",{scene:"",persistent:!1});const ge=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 Ae(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=Ce(t[e]),o=Ce(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Ce(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}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"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:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.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=Ae(t._name,t._default,n);if(e.length>0)throw new Error(Re(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Be(i))}catch(s){ke(s,`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 s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){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 i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,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}:i}}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 i=Ae(t._name,t._default,e);if(i.length>0)throw new Error(Re(t._name,i));n=e}const i=t.create(n),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 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,i]of e)if(i._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 i=n??We(e,t,s),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(!q(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,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 n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{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 i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>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=[],i=[],o=[];return e.forEach((e,t)=>{Oe(e)&&n.push(t),He(e)?i.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:i,_changedFilters:o,with:(...n)=>Ne(e,[...t,...n],s),without:(...n)=>Ne(e,t,[...s,...n])}}class Ve{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,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 s)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<n;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,...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 Ye{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 it{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 Ve(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 Ye(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 rt=be(new ot,"Input");class at{constructor(e){this.target_=e??null}build(e){const s=new ot;e.insertResource(rt,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 mt=new Map;function gt(e){ht=e,pt=e.getResourceManager(),Tt()}function yt(){0!==vt&&ht&&(ht._free(vt),vt=0),mt.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 mt.set(t,s),t},get:e=>mt.get(e),setUniform(e,t,s){const n=mt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,ht?.invalidateMaterialCache(e))},getUniform(e,t){const s=mt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=mt.get(e);s&&(s.blendMode=t,ht?.invalidateMaterialCache(e))},getBlendMode(e){const t=mt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=mt.get(e);s&&(s.depthTest=t,ht?.invalidateMaterialCache(e))},getShader(e){const t=mt.get(e);return t?.shader??0},release(e){mt.delete(e),ht?.invalidateMaterialCache(e)},isValid:e=>mt.has(e),releaseAll(){mt.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=mt.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 mt.set(s,n),s},toAssetData(e,t){const s=mt.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=mt.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 i=ht.HEAPU8,o=ht.HEAPU32,r=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,i.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++)r[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,i)=>{const o=mt.get(e);if(!o)return ht.HEAPU32[t>>2]=0,ht.HEAPU32[s>>2]=0,ht.HEAPU32[n>>2]=0,void(ht.HEAPU32[i>>2]=0);ht.HEAPU32[t>>2]=o.shader,ht.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Mt(o.uniforms);ht.HEAPU32[n>>2]=r,ht.HEAPU32[i>>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 At{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 i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,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 Ct{constructor(e,t=""){this.cache_=new At,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 r(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 i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);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=V("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 i=Ft.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,re)){const t=i.frames[s.currentFrame],o=e.get(n,re);o.texture=t.texture,e.insert(n,re,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,this.bgmVolume_=1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}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})}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),this.createPendingHandle())}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,this.bgmVolume_):this.bgmHandle_&&this.bgmHandle_.stop();const s=t?.volume??1;this.bgmVolume_=s;const n=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:n?0:s,loop:!0}),n&&this.fadeIn(this.bgmHandle_,n,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else 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 dispose(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}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,Ut.bgmVolume_=1,Ut.fadeAnimId_=0;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 i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=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 i of n.components)Xt(i,s),Gt(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function Nt(e,t){return jt(e,t)}async function Vt(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Yt.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=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),r.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=[...Yt.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.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]),i){for(const e of n.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=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 i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=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 r}const Yt=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.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,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Rt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);kt(It(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,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 i=Q(s.type);if(i)e.insert(t,i,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 At,this.shaderCache_=new At,this.jsonCache_=new At,this.textCache_=new At,this.binaryCache_=new At,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new At,this.prefabCache_=new At,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 Ct(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),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.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 i=this.resolveUrl(t,s),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,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),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,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 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 i=t(n);i&&(e.data[s]=i)}}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 i=t(s);i&&(e.data[n]=i)}}}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 Vt(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).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 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 s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,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,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 i=this.ctx_.getImageData(0,0,t,s),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,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:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(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:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return xt.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!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 i(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 i="";for(const e of n){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 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:i}=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}))},r=await Vt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const ts=10;async function ss(e,t,s,n,i,o=0){if(o>ts)throw new Error(`Prefab nesting depth exceeded ${ts}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){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=n;for(const t of e.entities)t.nestedPrefab||r.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(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ss(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};ns(d.components,r),is(d,t),l.push(d)}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 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 i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function is(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,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return es(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const rs=be(null,"Prefabs");class as{constructor(){this.name="PrefabsPlugin",this.dependencies=[Jt]}build(e){const t=e.getResource(Jt);e.insertResource(rs,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 ms(){cs&&(us&&(cs._free(us),us=0),ds&&(cs._free(ds),ds=0),hs&&(cs._free(hs),hs=0)),cs=null}function gs(){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=gs();try{t.HEAPF32.set(e,us/4),t.draw_begin(us)}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,i=32){try{gs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){ke(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{gs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}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,i=ys){try{gs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){ke(e,"Draw.textureRotated")}},setLayer(e){gs().draw_setLayer(e)},setDepth(e){gs().draw_setDepth(e)},getDrawCallCount:()=>cs?cs.draw_getDrawCallCount():0,getPrimitiveCount:()=>cs?cs.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(),i=xt.get(t);if(!i)return;if(_s.setBlendMode(i.blendMode),_s.setDepthTest(i.depthTest),0===i.uniforms.size)return void _s.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,ds/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.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}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(ps.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,ds);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),hs/4),n.draw_meshWithUniforms(e,i.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,As=0,Cs=0,Rs=0;function Is(e){Es=e,As=Es._malloc(262144),Cs=Es._malloc(65536),Rs=Es._malloc(256)}function Fs(){Es&&(As&&Es._free(As),Cs&&Es._free(Cs),Rs&&Es._free(Rs),As=0,Cs=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,As/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,Rs,i).set(o),t.geometry_init(s,As,n,Rs,i,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=ks(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,As/4),n.geometry_updateVertices(e,As,i,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 i=n/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;s.push(o,r,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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);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:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};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 Vs={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,i){Hs?.renderer_setScissor(e,t,s,n,i)},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 Ys=null;function Gs(e){Ys=e}function qs(){Ys=null}const Ks={enable(){Ys?.gl_enableErrorCheck(!0)},disable(){Ys?.gl_enableErrorCheck(!1)},check:e=>Ys?.gl_checkErrors(e)??0,diagnose(){Ys?.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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Vs.resize(n,i),Ws.isInitialized()&&Ws.getPassCount()>0&&Ws.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Vs.setViewport(0,0,n,i),Vs.clearBuffers(3),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,o),Vs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Vs.setViewport(n.x,n.y,n.w,n.h),Vs.setScissor(n.x,n.y,n.w,n.h,!0),Vs.clearBuffers(i),Vs.setScissor(0,0,0,0,!1),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,o),Vs.end()}executeDrawCallbacks(e,t){const s=bs;if(s.size>0){_s.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.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,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),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,me)){const s=this.app_.world.get(e,me);s.persistent=t,this.app_.world.insert(e,me,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,i=t.color??{...L.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,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:i.r,g:i.g,b:i.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 i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();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 s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}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 i=t?.keepPersistent??!0;for(const e of s.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)}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},i={collectAssets:s};this.app_.hasResource(Jt)&&(i.assetServer=this.app_.getResource(Jt));const o=await Vt(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,me,{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 i=this.contexts_.get(t);s.setup&&await s.setup(i)}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 i=!1;if(s.has(e,re)){const t=s.get(e,re);n.sprite=t.color.a,t.color.a=0,s.insert(e,re,t),i=!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),i=!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),i=!0}i&&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,re)){const t=s.get(e,re);t.color.a=n.sprite,s.insert(e,re,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 on=st([Pe(sn),Se(Ee)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),rn={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,on)}};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 i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),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 it(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 it(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,ms];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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.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 s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),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,i){const o=e*t/s,r=e;switch(n){case se.FixedWidth:return o;case se.FixedHeight:return r;case se.Expand:return Math.max(o,r);case se.Shrink:return Math.min(o,r);case se.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}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,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,me);return!t||""===t.scene||o.has(t.scene)}):r;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 i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===ee.Orthographic){if(d=i.orthoSize,l){d=un(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=mn(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=yn(i.fov*Math.PI/180,r,i.nearPlane,i.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=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.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 mn(e,t,s,n,i,o){const r=fn;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const gn=new Float32Array(16);function yn(e,t,s,n){const i=gn;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}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 i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const bn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Sn(e,t,s,n,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,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}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,re)||e.insert(t,re,{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 An(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 Cn(e,t,s,n){if(!e.has(t,Pn))return;const i=e.get(t,Pn),o=An(s,n);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,Pn,i)}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"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(In(r.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?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}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,i){if(!e.has(t,Pn))return;const o=e.get(t,Pn),r=Sn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,re)){const s=e.get(t,re);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,re,s))}if(e.has(t,ne)){const s=e.get(t,ne);s.position.x=r.originX-n,s.position.y=r.originY-i,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 i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](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},Vn={Visible:0,Clip:1,Ellipsis:2},Yn=V("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:jn.Left,verticalAlign:Nn.Top,wordWrap:!0,overflow:Vn.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 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=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=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Vn.Ellipsis&&h>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_,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 m=Math.round(255*e.color.r),g=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(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===Vn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){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}i&&e.overflow===Vn.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 i=this.renderText(t,s);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[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",Yn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Gn(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Yn));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Yn)){if(n.valid(e)&&n.has(e,re)){const t=n.get(e,re);n.insert(e,re,{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})}i.delete(e)}const e=n.getEntitiesWithComponents([Yn]);for(const t of e){const e=n.get(t,Yn),o=n.has(t,Pn)?n.get(t,Pn):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!qn.changed(a,r)){if(n.has(t,re)&&n.get(t,re).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,re);n.insert(t,re,{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,qn.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Jn=new Kn,Qn=0,Zn=1,ei=Z("UIMask",{enabled:!0,mode:Qn});function ti(e,t){const s=Math.max(e.x,t.x),n=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:s,y:n,w:Math.max(0,i-s),h:Math.max(0,o-n)}}function si(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,E=d*_-f*m,A=h*y-p*g,C=h*_-f*g,R=p*_-f*y;let I=x*R-w*C+v*A+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*C+u*A)*I,s[1]=(o*C-i*R-r*A)*I,s[2]=(g*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+r*T)*I,s[6]=(y*v-m*P-_*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*C-l*E+u*M)*I,s[9]=(i*E-n*C-r*M)*I,s[10]=(m*S-g*v+_*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(l*T-a*A-c*M)*I,s[13]=(n*A-i*T+o*M)*I,s[14]=(g*w-m*b-y*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function ni(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*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 ii(e,t){return 2*Math.atan2(e,t)}function oi(e,t,s,n,i,o,r){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,i+(.5*(l/c)+.5)*r]}function ri(e,t,s,n,i,o,r){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,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=ii(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[d+m*w-y*v,h+m*v+y*w],[d+g*w-y*v,h+g*v+y*w],[d+g*w-_*v,h+g*v+_*w],[d+m*w-_*v,h+m*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=oi(e,t,s,n,i,o,r);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 ai(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ei]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,ei);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,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Ln(t,e,e=>{if(i.has(e)){if(t.get(e,ei).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(i.has(s)){if(t.get(s,ei).mode===Qn){const e=ri(t,s,o,r,a,l,c);e&&(n=ti(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ri(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Ln(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&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,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,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,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,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,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 li{build(e){if(J("UIMask",ei),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ai(e.wasmModule,e.world))}}const ci=new li,ui=Z("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),di=Z("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),hi={Normal:0,Hovered:1,Pressed:2,Disabled:3},pi=V("Button",{state:hi.Normal,transition:null});class fi{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 mi=be(new fi,"UIEvents");class gi{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 yi=new gi;let _i=!1,xi=!1;function wi(){return _i}function vi(){return xi}const bi=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&&(si(t,e),s=!1),e)}}();function Si(e,t,s,n){t.emit(s,n,s),Ln(e,s,i=>{if(!e.has(i,ui))return!1;const o=e.get(i,ui);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Pi{build(e){J("Interactable",ui),J("Button",pi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new fi;e.insertResource(mi,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(rt),Se(ct)],(e,a)=>{if(i.drain(),wi()&&!vi())return;const l=t.getEntitiesWithComponents([di]);for(const e of l){const s=t.get(e,di);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,di,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;bi.update(a.viewProjection);const p=ni(d,h,bi.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);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,di)){const e=t.get(o,di);e.hovered=!1,t.insert(o,di,e),i.emit(o,"hover_exit")}if(null!==_){zn(t,_,di);const e=t.get(_,di);e.hovered=!0,t.insert(_,di,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,di);e.pressed=!0,e.justPressed=!0,t.insert(_,di,e),r=_,Si(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,di)){const e=t.get(r,di);e.pressed=!1,e.justReleased=!0,t.insert(r,di,e),Si(t,i,r,"release"),r===o&&Si(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,st([],()=>{const e=t.getEntitiesWithComponents([pi]);for(const s of e){if(zn(t,s,ui,{enabled:!0}),!t.has(s,di))continue;const e=t.get(s,di),n=t.get(s,pi),i=t.get(s,ui),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=hi.Pressed:e.hovered?n.state=hi.Hovered:n.state=hi.Normal:n.state=hi.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=Rn(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const Mi=new Pi,Ti=V("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Ei=V("Focusable",{tabIndex:0,isFocused:!1});class Ai{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 Ci=be(new Ai,"FocusManager");class Ri{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(J("TextInput",Ti),wi()&&!vi())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l(L.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=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 m(){const t=e.getResource(Ci);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Ti)?n:null}const g=()=>{c||null===m()||v()},y=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Ti);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(mi).emit(n,"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,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Ti);n.focused=!1,n.dirty=!0;e.getResource(Ci).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Ti);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(mi).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Ti);e.focused=!1,e.dirty=!0}e.getResource(Ci).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),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!==r&&(t._free(r),r=0,a=0)};let P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=kn(Math.max(i.width,c)),i.height=kn(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.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,m=p?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),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+=g}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 i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}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!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,d,r,x.length,1,!0);n.set(e,b);const S=s.get(e,re);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,re,S)}e.addSystemToSchedule(exports.Schedule.Update,st([Se(Ci)],e=>{const t=s.getEntitiesWithComponents([Ti]);for(const e of t)zn(s,e,Ei,{tabIndex:0,isFocused:!1}),zn(s,e,ui,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Ti)){const e=s.get(P,Ti);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Ti);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 i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,u=!u;s.get(o,Ti).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ti)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ti,Pn]);for(const e of a){const t=s.get(e,Ti);if(!t.dirty)continue;const n=s.get(e,Pn),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(En(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Ii=new Ri,Fi={Simple:0,Sliced:1,Tiled:2,Filled:3},ki={Horizontal:0,Vertical:1},Bi={Left:0,Right:1,Bottom:2,Top:3},Di=V("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:Fi.Simple,fillMethod:ki.Horizontal,fillOrigin:Bi.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ui=$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 Li=new class{build(e){J("Image",Di);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,Di)||s.delete(e);const e=t.getEntitiesWithComponents([Di]);for(const n of e){const e=t.get(n,Di),i=t.has(n,Pn)?t.get(n,Pn):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Ui.changed(r,o))continue;En(t,n);const a=t.get(n,re);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=Dn(i,n),a.size.y=Un(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fi.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===ki.Horizontal?e.fillOrigin===Bi.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===Bi.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===Fi.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,re,a),s.set(n,Ui.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,Ui.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},zi=V("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Wi=V("ToggleGroup",{allowSwitchOff:!1});const $i=new class{build(e){J("Toggle",zi),J("ToggleGroup",Wi);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,st([Se(mi)],e=>{const n=t.getEntitiesWithComponents([zi]);if(!wi()||vi()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,zi);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,zi,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,zi);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,ui,{enabled:!0}),!t.has(s,di))continue;const n=t.get(s,di),i=t.get(s,zi),r=t.get(s,ui);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Wi);if(i.isOn&&r){if(!t.get(n,Wi).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,zi,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,zi);i.isOn&&(i.isOn=!1,t.insert(n,zi,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,re)){const e=t.get(s,re);e.color=Rn(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,zi);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,re)){const e=t.get(s.graphicEntity,re);e.enabled=s.isOn,t.insert(s.graphicEntity,re,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Oi=bn,Hi=V("ProgressBar",{value:0,fillEntity:0,direction:bn.LeftToRight});function Xi(e,t,s,n){if(!e.has(t,Pn))return;const i=e.get(t,Pn),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=Sn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,re)){const s=e.get(t,re);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,re,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 ji{build(e){J("ProgressBar",Hi);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([],()=>{const e=t.getEntitiesWithComponents([Hi,Pn]);for(const s of e){const e=t.get(s,Hi);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Pn),i=Math.max(0,Math.min(1,e.value));Cn(t,e.fillEntity,e.direction,i);const o=Dn(n,s),r=Un(n,s);Xi(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ni=new ji,Vi=V("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Yi=V("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 Gi=new class{build(e){J("Draggable",Vi),J("DragState",Yi);const t=e.world,s=e.getResource(mi);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(rt),Se(ct)],(e,r)=>{if(wi()&&!vi())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Vi,di]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Vi).enabled)continue;if(t.get(n,di).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const i=Bn(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Yi)||t.insert(s,Yi);const e=t.get(s,Yi),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,Yi)){t.get(n,Yi).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,Vi);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Yi).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Yi))return void(o=null);const n=t.get(o,Yi),i=t.get(o,Vi),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;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,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 i=e.get(t,ue).entity;if(!e.valid(i)||!e.has(i,ne))return{x:s,y:n};const o=e.get(i,ne),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=ii(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,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"}))}},qi=V("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Ki(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 Ji(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}const Qi=new class{build(e){J("ScrollView",qi);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,st([Se(rt),Se(ct),Se(Ee)],(e,i,o)=>{const r=wi()&&!vi(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([qi,Pn]);for(const o of l){zn(t,o,ei,{enabled:!0,mode:Qn});const l=t.get(o,qi),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,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,ne))continue;const e=t.get(r,ne);let a=0,l=0,c=.5,u=.5;if(t.has(r,Pn)){const e=t.get(r,Pn);a=Dn(e,r)||e.size.x,l=Un(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,re)){const e=t.get(r,re);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<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){zn(t,o,ui,{enabled:!0,blockRaycast:!0});const s=t.has(o,di)?t.get(o,di):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=Ki(l.scrollX,0,m,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=Ki(l.scrollY,0,g,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=Ki(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ki(l.scrollX,0,m,d);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=Ji(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:g,t=Ji(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,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*d,t=.5*h;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,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"]})}},Zi=bn,eo=V("Slider",{value:0,minValue:0,maxValue:1,direction:bn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function to(e,t,s,n,i,o){const r=Dn(n,i)*s.worldScale.x,a=Un(n,i)*s.worldScale.y,l=ii(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,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case bn.LeftToRight:return r>0?(p-m)/r:0;case bn.RightToLeft:return r>0?1-(p-m)/r:0;case bn.BottomToTop:return a>0?(f-g)/a:0;case bn.TopToBottom:return a>0?1-(f-g)/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(rt),Se(ct),Se(mi)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([eo,Pn]);for(const r of o){const o=t.get(r,eo),a=t.get(r,Pn);if(!wi()||vi()){if(t.has(r,ne)){zn(t,r,ui,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&zn(t,o.handleEntity,ui,{enabled:!0,blockRaycast:!1});const l=t.get(r,ne),c=t.has(r,di)?t.get(r,di):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,di)&&(u=t.get(o.handleEntity,di).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=to(n.worldMouseX,n.worldMouseY,l,a,r,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(r,eo,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Dn(a,r),d=Un(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/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,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 io=new no;const oo=new class{build(e){J("Focusable",Ei);const t=e.world,s=new Ai;e.insertResource(Ci,s),e.addSystemToSchedule(exports.Schedule.Update,st([Se(rt),Se(mi)],(e,n)=>{if(wi()&&!vi())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ei]);for(const e of i){if(!t.has(e,di))continue;t.get(e,di).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,ui)){if(!t.get(s,ui).enabled)continue}const n=t.get(s,Ei);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 r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ei)){t.get(i,Ei).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ei).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ro=V("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:i}=t;return{top:s.top,bottom:i-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",ro);const t=e.world;let n=ao(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ao(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ao(),i=!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===r||(o=e.screenH,r=a,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([ro,Pn]);for(const e of d){const s=t.get(e,ro),i=t.get(e,Pn),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,Pn,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},co=V("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(rt)],e=>{const n=wi()&&!vi();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 i=t.getEntitiesWithComponents([co,Pn]);for(const o of i){zn(t,o,ui,{enabled:!0,blockRaycast:!0}),zn(t,o,ei,{enabled:!0,mode:Qn});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,co),a=t.get(o,Pn),l=Un(a,o),c=Dn(a,o);if(!n){const s=t.has(o,di)?t.get(o,di):null;if(s?.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 d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.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:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,ne)){const n=t.get(s,ne);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,ne,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},po=V("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 i(e){if(t.has(e,re)){const s=t.get(e,re);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,re,{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 i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,re),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Hn;t.insert(i,Pn,{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,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(i,re,{texture:$,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<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:r,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,re,{texture:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,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,ui,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),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,Yn,{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:Vn.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:r,y:Hn},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Yn))return;const n=t.get(s,Yn);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.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(s,Yn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,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,ui)&&t.insert(e,ui,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,re))){const n=t.get(e,re);t.insert(e,re,{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,re))continue;const i=s===e.highlightIndex?{...Xn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:$,color:i,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,di))continue;if(t.get(s,di).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,st([Se(rt),Se(mi)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=wi()&&!vi(),f=t.getEntitiesWithComponents([po]);for(const m of f){const f=t.get(m,po);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;zn(t,m,ui,{enabled:!0,blockRaycast:!0});const y=t.has(m,di)?t.get(m,di):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,di))continue;if(t.get(s,di).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,di))continue;if(t.get(n,di).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},mo=0,go=0,yo=2,_o=V("LayoutGroup",{direction:mo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:go,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),i=t.get(s,de);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.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 r=Dn(n,s),a=Un(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===mo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Dn(n.rect,n.entity),p=Un(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===go?(1-c)*a-u.top-(1-m)*p:e.childAlignment===yo?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===go?-l*r+u.left+f*i:e.childAlignment===yo?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,ne);_.position.x=g,_.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 i=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/i,r=e.world;r.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=r.getEntitiesWithComponents([ge,ne]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,ge),l=r.get(i,ne);if(t.has(i)){const e=s.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||(n._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=Mo(l.worldRotation);n._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),Ao(e,n,i),t.add(i),s.set(i,{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(i,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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,ne);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,ue)){const t=e.world.get(r,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),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(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(r,ne,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],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;n.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]*s,contactY:t.HEAPF32[i+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;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,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Po,Co._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Ao(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 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 Ro={nearest:0,linear:1},Io={repeat:0,clamp:1,mirror:2};function Fo(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=Ro[n.filterMode??"linear"]??1,a=Io[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}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 i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=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,m=a*h,g=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))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(f+x))*o,(_+w)*o,0,(g+v)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Do(e,t,s,n,i,o,r,a,l){const c=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Wt(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===n[o])try{const t=i?.[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 i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let u={},d=null;if(i&&(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"])}}(i),u=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=$t(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===_(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.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,r);if(t._free(d),p<0)continue;o[a]=p;const f=ko(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Fo(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,d,s,n)),o){const t={gravity:r?.gravity??{...D},fixedTimestep:r?.fixedTimestep??U,subStepCount:r?.subStepCount??4};new Eo("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=Wt(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=_(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Wt(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.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 i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=xt.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=xt.createFromAsset(e,r)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const i={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=i[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,me,{scene:l,persistent:!1});if(i&&d){const n=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=$t(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.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}(d,s,u,f);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=B);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,pe)?c.get(o,pe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,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(r);for(let e=0;e<p;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,i,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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=$t(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.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 i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):"material"===s.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 s)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 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(),i=await createImageBitmap(n),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 zo="__preview__";const Wo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Vs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Vs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Vs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Vs.releaseRenderTarget(e._handle),Wo.create({width:t,height:s,depth:!0})),begin(e,t){Vs.begin(t,e._handle)},end(){Vs.end()},getDepthTexture:e=>Vs.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 i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}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 Vo{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 Yo=null,Go=null;function qo(e,t){Yo=e,Go=t}function Ko(){Yo=null,Go=null}function Jo(){if(!Yo)throw new Error("Tween API not initialized");return Yo}function Qo(){if(!Go)throw new Error("Tween API not initialized");return Go}const Zo={to(e,t,s,n,i,o){const r=Jo(),a=Qo(),l=o?.easing??jo.Linear,c=o?.delay??0,u=o?.loop??No.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Vo(r,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 er{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 tr=new er;class sr{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,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 sr?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class nr{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new sr(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new sr(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new sr(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new sr(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new sr(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 sr(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 ir{constructor(e,t=16){this.pool_=[],this.activeCount_=0,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,this.activeCount_++,t}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}var or;exports.AttenuationModel=void 0,(or=exports.AttenuationModel||(exports.AttenuationModel={}))[or.Linear=0]="Linear",or[or.Inverse=1]="Inverse",or[or.Exponential=2]="Exponential";const rr={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ar(e,t=rr){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;return 1-(Math.min(Math.max(r,n),i)-n)/e}case exports.AttenuationModel.Inverse:return n/Math.max(r,n);case exports.AttenuationModel.Exponential:return Math.pow(Math.max(r,n)/n,-o);default:return 1}}function lr(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const cr=V("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}),ur=V("AudioListener",{enabled:!0});class dr{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class hr{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new nr(this.context_,e.mixerConfig),this.pool_=new ir(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),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}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),i=++this.nextBufferId_;return this.buffers_.set(i,n),{id:i,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),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new dr(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.context_?.close(),this.context_=null}}class pr{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 fr{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 i=++this.nextId_;this.contexts_.set(i,n);const o=new pr(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.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 mr(){return s()?new fr:new hr}class gr{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const t=mr(),s=this.config_;t instanceof hr?t.initialize({initialPoolSize:s.initialPoolSize}):t.initialize();let n=null;t instanceof hr&&(n=t.mixer),Ut.init(t,n),n&&(void 0!==s.masterVolume&&(n.master.volume=s.masterVolume),void 0!==s.musicVolume&&(n.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(n.sfx.volume=s.sfxVolume));const i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,st([Se(Ee)],s=>{const n=e.world;let o=0,r=0;const a=n.getEntitiesWithComponents([ur,oe]);for(const e of a){if(n.get(e,ur).enabled){const t=n.get(e,oe);o=t.position.x,r=t.position.y;break}}const l=n.getEntitiesWithComponents([cr,oe]),c=new Set;for(const e of l){const s=n.get(e,cr);if(!s.enabled||!s.clip)continue;c.add(e);const a=n.get(e,oe);if(s.playOnAwake&&!i.has(e)){const n=Ut.getBufferHandle(s.clip);if(n){const o=t.play(n,{bus:s.bus,volume:s.volume,loop:s.loop,playbackRate:s.pitch,priority:s.priority});i.set(e,o)}else console.warn(`[AudioPlugin] playOnAwake: clip "${s.clip}" not preloaded`)}if(s.spatial&&i.has(e)){const t=i.get(e);if(!t.isPlaying){i.delete(e);continue}const n=a.position.x-o,l=a.position.y-r,c=ar(Math.sqrt(n*n+l*l),{model:s.attenuationModel,refDistance:s.minDistance,maxDistance:s.maxDistance,rolloff:s.rolloff}),u=lr(a.position.x,a.position.y,o,0,s.maxDistance);t.setVolume(s.volume*c),t.setPan(u)}}for(const[e,t]of i)c.has(e)&&t.isPlaying||i.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){Ut.dispose()}}const yr=new gr;class _r{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 i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.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 xr(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 wr=[Jn,ci,yi,Li,Ni,Mi,Gi,Qi,io,$i,Ii,oo,lo,ho,fo,xo,vo],vr=[...wr,tr];function br(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),gt(e),Is(e),Us(e),js(e),Gs(e);const i=new Js;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=pn(e,n,t,i));const r=s.getResource(ct);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.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}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}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Vs.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Vs.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))}i.setActiveScenes(h??null);const p=pn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.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),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Vs.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(rn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:vr,...t})}class Sr{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 i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Pr(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function Mr(e,t){try{return await e({instantiateWasm:Pr(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},i=await d(s,n);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: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 i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}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 i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=I,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=er,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=At,exports.Audio=Ut,exports.AudioBus=sr,exports.AudioListener=ur,exports.AudioMixer=nr,exports.AudioPlugin=gr,exports.AudioPool=ir,exports.AudioSource=cr,exports.BitmapText=he,exports.BodyType=we,exports.BoxCollider=ye,exports.Button=pi,exports.ButtonState=hi,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=Yi,exports.Draggable=Vi,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=ki,exports.FillOrigin=Bi,exports.FocusManager=Ci,exports.FocusManagerState=Ai,exports.Focusable=Ei,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=Di,exports.ImageType=Fi,exports.Input=rt,exports.InputPlugin=at,exports.InputState=ot,exports.Interactable=ui,exports.ListView=co,exports.LocalTransform=ie,exports.Logger=Ho,exports.LoopMode=No,exports.Material=xt,exports.MaterialLoader=Ct,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=fe,exports.Parent=ue,exports.Physics=Co,exports.PhysicsEvents=So,exports.PhysicsPlugin=Eo,exports.PostProcess=Ws,exports.PrefabServer=os,exports.Prefabs=rs,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 i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await Do(this.app_,this.app_.wasmModule,t,s,i,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 i of n){const n=e.get(i,le);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(sn).getScene(zo),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,ne,r);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=Hi,exports.ProgressBarDirection=Oi,exports.ProgressBarPlugin=ji,exports.ProjectionType=ee,exports.Query=function(...e){return Ne(e)},exports.QueryInstance=Ve,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ye,exports.RenderPipeline=Js,exports.RenderTexture=Wo,exports.Renderer=Vs,exports.Res=Se,exports.ResMut=Pe,exports.RigidBody=ge,exports.RuntimeConfig=L,exports.SafeArea=ro,exports.ScaleMode=se,exports.SceneManager=sn,exports.SceneManagerState=tn,exports.SceneOwner=me,exports.ScrollView=qi,exports.ShaderSources=Et,exports.Slider=eo,exports.SliderDirection=Zi,exports.SliderPlugin=no,exports.SpineAnimation=pe,exports.Sprite=re,exports.SpriteAnimator=Bt,exports.SystemRunner=it,exports.Text=Yn,exports.TextAlign=jn,exports.TextInput=Ti,exports.TextInputPlugin=Ri,exports.TextOverflow=Vn,exports.TextPlugin=Kn,exports.TextRenderer=Gn,exports.TextVerticalAlign=Nn,exports.Time=Ee,exports.Toggle=zi,exports.Transform=ne,exports.Tween=Zo,exports.TweenHandle=Vo,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=fi,exports.UIEvents=mi,exports.UIInteraction=di,exports.UIInteractionPlugin=Pi,exports.UILayoutPlugin=gi,exports.UIMask=ei,exports.UIMaskPlugin=li,exports.UIRect=Pn,exports.UIRenderOrderPlugin=wo,exports.Velocity=ce,exports.WeChatAssetProvider=Sr,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=tr,exports.applyBuildRuntimeConfig=W,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=Zt,exports.audioPlugin=yr,exports.calculateAttenuation=ar,exports.calculatePanning=lr,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=An,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=mr,exports.createMaskProcessor=ai,exports.createRuntimeSceneConfig=Uo,exports.createWebApp=br,exports.debug=function(e,t,s){Xo.debug(e,t,s)},exports.defineComponent=V,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 g},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=Y,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=gt,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(Jt);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0)),ln(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await xr(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 xr(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Uo(o,i,{app:t,module:s,provider:new _r(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),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:Pr("esengine.wasm")}),l=i.getContext("webgl2")||i.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=br(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&W(u,e.runtimeConfig),ln(u);let d=null;e.spineFactory&&(d=await Mr(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await Mr(e.physicsFactory,"physics.wasm"));const p={app:u,module:a,provider:new Sr(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 m=i.width/i.height;qt(u.world,m),u.run()},exports.inputPlugin=lt,exports.instantiatePrefab=es,exports.intersectRects=ti,exports.invertMatrix4=si,exports.isBuiltinComponent=q,exports.isCustomExtension=v,exports.isEditor=wi,exports.isKnownAssetExtension=x,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=vi,exports.isRuntime=function(){return!_i},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=Vt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&x(y(e)))},exports.parseAnimClipData=It,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=ii(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=ls,exports.progressBarPlugin=Ni,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=rn,exports.screenToWorld=ni,exports.setEditorMode=function(e){_i=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){xi=e},exports.setWasmErrorHandler=Fe,exports.shutdownDrawAPI=ms,exports.shutdownGLDebugAPI=qs,exports.shutdownGeometryAPI=Fs,exports.shutdownMaterialAPI=yt,exports.shutdownPostProcessAPI=Ls,exports.shutdownRendererAPI=Ns,exports.shutdownTweenAPI=Ko,exports.sliderPlugin=io,exports.spriteAnimatorSystemUpdate=Dt,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,re))return;const r=e.get(t,re);let a,l;switch(s){case bn.BottomToTop:case bn.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,re,r))},exports.textInputPlugin=Ii,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=Mi,exports.uiLayoutPlugin=yi,exports.uiMaskPlugin=ci,exports.uiPlugins=wr,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=A,exports.wxLoadImage=E,exports.wxLoadImagePixels=C,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}`))}})})};
+"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 i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(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}class u{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,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 u?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{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 p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}async initialize(e){}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 i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.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 f(e,t){return new Promise((s,n)=>{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,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 m(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 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,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(w(e))}function b(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=v(e);return t?.wechatPackInclude??!1}function M(e){const t=v(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 T=null;function E(){return T||(T=wx.getFileSystemManager()),T}function C(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(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 A(e){const t=E();try{return t.accessSync(e),!0}catch{return!1}}function R(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 I(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 i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return E().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return E().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(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),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=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(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}},D=1920,U=1080,L=1/60,z={x:0,y:-9.81},W=1/60,$={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const O={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function H(e,t){if(void 0!==t.maxDeltaTime&&($.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&($.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&($.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&($.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&($.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");$.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&&($.canvasScaleMode=O[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&($.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const X=4294967295,j=4294967295;function V(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(V);const t={};for(const s in e)t[s]=V(e[s]);return t}let N=0;function Y(e,t){const s=++N,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?{...V(t),...e}:V(t):e?{...t,...e}:{...t}}}function G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function q(e,t){const s=Z.get(e)??G().get(e);if(s)return s;const n=Y(e,t);return G().set(e,n),Z.set(e,n),J(e,t,!1),n}function K(e){return G().get(e)}function J(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Q(e){return!0===e._builtin}const Z=new Map;function ee(e,t){Z.set(e,t)}function te(e){return Z.get(e)??K(e)}function se(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Z.set(e,s),s}const ne={Perspective:0,Orthographic:1},ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},re=se("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}}),ae=re,le=re,ce=se("Sprite",{texture:X,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}),de=se("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:ie.ColorAndDepth}),ue=se("Canvas",{designResolution:{x:D,y:U},pixelsPerUnit:100,scaleMode:oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),he=se("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),pe=se("Parent",{entity:0}),fe=se("Children",{entities:[]}),me=se("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:j,enabled:!0}),ge=se("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=q("Name",{value:""}),_e=q("SceneOwner",{scene:"",persistent:!1});const xe=se("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=se("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=se("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be=se("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 s=++Pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_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 Ae{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 Re=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ie(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=Fe(t[e]),o=Fe(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function Fe(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(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 Be=null;function De(e){Be=e}function Ue(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Be&&Be(e,t)}function Le(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 ze=1;const We=new WeakMap;function $e(e){let t=We.get(e);return void 0===t&&(t=ze++,We.set(e,t)),t}const Oe=[];function He(e,t=[],s=[]){Oe.length=0;for(const t of e)Oe.push($e(t));Oe.sort((e,t)=>e-t);let n=Oe.join(",");if(t.length>0){Oe.length=0;for(const e of t)Oe.push($e(e));Oe.sort((e,t)=>e-t),n+="|+"+Oe.join(",")}if(s.length>0){Oe.length=0;for(const e of s)Oe.push($e(e));Oe.sort((e,t)=>e-t),n+="|-"+Oe.join(",")}return n}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 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){Ue(s,`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,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,Le(s))}catch(s){Ue(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 Ue(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}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"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:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.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=Ie(t._name,t._default,n);if(e.length>0)throw new Error(ke(t._name,e))}const i={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Le(i))}catch(s){Ue(s,`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 s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){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 i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,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}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ue(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 Ue(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ue(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 i=Ie(t._name,t._default,e);if(i.length>0)throw new Error(ke(t._name,i));n=e}const i=t.create(n),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 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 Z)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=G();for(const n of s)for(const[s,i]of e)if(i._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 i=n??He(e,t,s),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(!Q(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,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 n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{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 i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>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 je(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ne(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ye(e){return je(e)||Ve(e)||Ne(e)?e._component:e}function Ge(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{je(e)&&n.push(t),Ve(e)?i.push({index:t,component:e._component}):Ne(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>Ge(e,[...t,...n],s),without:(...n)=>Ge(e,t,[...s,...n])}}class qe{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(Ye),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: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,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 d of s)if(!o||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)}r[0]=d;for(let e=0;e<n;e++)r[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=d}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,...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 Ke{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 Je{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 Je(this,null);return this.spawned_.push(e),e}entity(e){return new Je(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 Ze{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 et{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ze)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ze,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class tt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class st{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var nt;function it(){return{_type:"get_world"}}exports.Schedule=void 0,(nt=exports.Schedule||(exports.Schedule={}))[nt.Startup=0]="Startup",nt[nt.First=1]="First",nt[nt.PreUpdate=2]="PreUpdate",nt[nt.Update=3]="Update",nt[nt.PostUpdate=4]="PostUpdate",nt[nt.Last=5]="Last",nt[nt.FixedPreUpdate=10]="FixedPreUpdate",nt[nt.FixedUpdate=11]="FixedUpdate",nt[nt.FixedPostUpdate=12]="FixedPostUpdate";let ot=0;function rt(e,t,s){const n=++ot;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function at(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class lt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}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]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new qe(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 tt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new st(s)}case"removed":{const t=e;return new Ke(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class ct{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 dt=Me(new ct,"Input");class ut{constructor(e){this.target_=e??null}build(e){const s=new ct;e.insertResource(dt,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,rt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ht=new ut,pt=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 ft;function mt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(ft=exports.BlendMode||(exports.BlendMode={}))[ft.Normal=0]="Normal",ft[ft.Additive=1]="Additive",ft[ft.Multiply=2]="Multiply",ft[ft.Screen=3]="Screen",ft[ft.PremultipliedAlpha=4]="PremultipliedAlpha";let gt=null,yt=null,_t=1;const xt=new Map;function wt(e){gt=e,yt=e.getResourceManager(),Rt()}function vt(){0!==Mt&&gt&&(gt._free(Mt),Mt=0),xt.clear(),_t=1,Pt=!1,Et.clear(),Ct=null,yt=null,gt=null}function bt(){if(!yt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return yt}const St={createShader:(e,t)=>bt().createShader(e,t),releaseShader(e){e>0&&bt().releaseShader(e)},create(e){const t=_t++,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 xt.set(t,s),t},get:e=>xt.get(e),setUniform(e,t,s){const n=xt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,gt?.invalidateMaterialCache(e))},getUniform(e,t){const s=xt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=xt.get(e);s&&(s.blendMode=t,gt?.invalidateMaterialCache(e))},getBlendMode(e){const t=xt.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=xt.get(e);s&&(s.depthTest=t,gt?.invalidateMaterialCache(e))},getShader(e){const t=xt.get(e);return t?.shader??0},release(e){xt.delete(e),gt?.invalidateMaterialCache(e)},isValid:e=>xt.has(e),releaseAll(){xt.clear(),gt?.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=xt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=_t++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return xt.set(s,n),s},toAssetData(e,t){const s=xt.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=xt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Pt=!1,Mt=0;const Tt=16384,Et=new Map;let Ct=null;function At(e){const t=(0===Mt&&gt&&(Mt=gt._malloc(Tt)),Mt);if(0===t||!gt)return{ptr:0,count:0};let s=0,n=0;const i=gt.HEAPU8,o=gt.HEAPU32,r=gt.HEAPF32;for(const[a,l]of e){if(mt(l))continue;let e=Et.get(a);e||(Ct||(Ct=new TextEncoder),e=Ct.encode(a),Et.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>Tt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Tt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.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++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Rt(){if(!gt||Pt)return;gt.materialDataProvider=(e,t,s,n,i)=>{const o=xt.get(e);if(!o)return gt.HEAPU32[t>>2]=0,gt.HEAPU32[s>>2]=0,gt.HEAPU32[n>>2]=0,void(gt.HEAPU32[i>>2]=0);gt.HEAPU32[t>>2]=o.shader,gt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=At(o.uniforms);gt.HEAPU32[n>>2]=r,gt.HEAPU32[i>>2]=a},Pt=!0}const It={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 Ft{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 i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),i=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,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 kt{constructor(e,t=""){this.cache_=new Ft,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&&(St.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())St.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await r(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 i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:St.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 Bt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Dt(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 Ut=new Map;function Lt(e){Ut.set(e.name,e)}const zt=q("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Wt(e,t){const s=e.getEntitiesWithComponents([zt]);for(const n of s){const s=e.get(n,zt);if(!s.enabled||!s.playing||!s.clip)continue;const i=Ut.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ce)){const t=i.frames[s.currentFrame],o=e.get(n,ce);o.texture=t.texture,e.insert(n,ce,o)}a&&e.insert(n,zt,s)}}class $t{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}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})}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),this.createPendingHandle())}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,this.bgmVolume_):this.bgmHandle_&&this.bgmHandle_.stop();const s=t?.volume??1;this.bgmVolume_=s;const n=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:n?0:s,loop:!0}),n&&this.fadeIn(this.bgmHandle_,n,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else 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 dispose(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createPendingHandle(){return{id:-1,stop(){},pause(){},resume(){},setVolume(){},setPan(){},setLoop(){},setPlaybackRate(){},isPlaying:!1,currentTime:0,duration:0}}}$t.mixer_=null,$t.bufferCache_=new Map,$t.bgmHandle_=null,$t.bgmVolume_=1,$t.fadeAnimId_=0;const Ot=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 Ht(e){const t=Ot.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 Xt(e){return Ot.get(e)?.fields??[]}function jt(e){return Ot.get(e)?.spine??null}const Vt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Nt(e){return Vt.get(e)}function Yt(e,t){const s=Vt.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function Gt(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,ye,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)Yt(i,s),Qt(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function qt(e,t){return Gt(e,t)}async function Kt(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Jt.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=Ot.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),r.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=[...Jt.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),d=r.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]),i){for(const e of n.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=Ot.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 i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=Gt(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 r}const Jt=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.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,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Bt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Lt(Dt(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,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await $t.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Qt(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 i=te(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Zt(e,t){const s=e.getEntitiesWithComponents([de]);for(const n of s){const s=e.get(n,de);s&&(s.aspectRatio=t,e.insert(n,de,s))}}class es{constructor(e){this.textureCache_=new Ft,this.shaderCache_=new Ft,this.jsonCache_=new Ft,this.textCache_=new Ft,this.binaryCache_=new Ft,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ft,this.prefabCache_=new Ft,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($.textCanvasSize,$.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 kt(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),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.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(),St.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 i=this.resolveUrl(t,s),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,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"===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(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),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.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=v(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 i=s?`${s}/${n}`:n;return this.loadFntFile(i)}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],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,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 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 Ht(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=jt(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}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 Kt(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 i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).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 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 s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,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,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,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 i=this.ctx_.getImageData(0,0,t,s),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,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:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return St.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(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:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return St.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(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 i(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 i="";for(const e of n){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 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 ts=Me(null,"Assets");class ss{build(e){const t=e.wasmModule;t?e.insertResource(ts,new es(t)):console.warn("AssetPlugin: No WASM module available")}}const ns=new ss;async function is(e,t,s){const{entities:n,rootId:i}=await rs(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}))},r=await Kt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const os=10;async function rs(e,t,s,n,i,o=0){if(o>os)throw new Error(`Prefab nesting depth exceeded ${os}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){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=n;for(const t of e.entities)t.nestedPrefab||r.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(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await rs(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};as(u.components,r),ls(u,t),l.push(u)}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 as(e,t){for(const s of e){const e=Nt(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function ls(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 cs{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return is(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const ds=Me(null,"Prefabs");class us{constructor(){this.name="PrefabsPlugin",this.dependencies=[ts]}build(e){const t=e.getResource(ts);e.insertResource(ds,new cs(e.world,t))}}const hs=new us;let ps=null,fs=0,ms=0,gs=0;const ys=new Float32Array(256);function _s(e){ps=e,fs=ps._malloc(64),ms=ps._malloc(64),gs=ps._malloc(1024)}function xs(){ps&&(fs&&(ps._free(fs),fs=0),ms&&(ps._free(ms),ms=0),gs&&(ps._free(gs),gs=0)),ps=null}function ws(){if(!ps)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ps}const vs={r:1,g:1,b:1,a:1},bs={begin(e){const t=ws();try{t.HEAPF32.set(e,fs/4),t.draw_begin(fs)}catch(e){Ue(e,"Draw.begin")}},end(){try{ws().draw_end()}catch(e){Ue(e,"Draw.end")}},line(e,t,s,n=1){try{ws().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.line")}},rect(e,t,s,n=!0){try{ws().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ws().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ue(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{ws().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ue(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{ws().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ue(e,"Draw.circleOutline")}},texture(e,t,s,n=vs){try{ws().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ue(e,"Draw.texture")}},textureRotated(e,t,s,n,i=vs){try{ws().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ue(e,"Draw.textureRotated")}},setLayer(e){ws().draw_setLayer(e)},setDepth(e){ws().draw_setDepth(e)},getDrawCallCount:()=>ps?ps.draw_getDrawCallCount():0,getPrimitiveCount:()=>ps?ps.draw_getPrimitiveCount():0,setBlendMode(e){ws().draw_setBlendMode(e)},setDepthTest(e){ws().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ws();n.HEAPF32.set(s,ms/4),n.draw_mesh(e,t,ms)}catch(s){Ue(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ws(),i=St.get(t);if(!i)return;if(bs.setBlendMode(i.blendMode),bs.setDepthTest(i.depthTest),0===i.uniforms.size)return void bs.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,ms/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Ms(t);if(!(n<0)){if(mt(s))ys[o++]=10,ys[o++]=n,ys[o++]=s.slot??e++,ys[o++]=s.textureId;else if("number"==typeof s)ys[o++]=1,ys[o++]=n,ys[o++]=s;else if(Array.isArray(s)){ys[o++]=s.length,ys[o++]=n;for(let e=0;e<s.length;e++)ys[o++]=s[e]}else"w"in s?(ys[o++]=4,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y,ys[o++]=s.z,ys[o++]=s.w):"z"in s?(ys[o++]=3,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.y,ys[o++]=s.z):(ys[o++]=2,ys[o++]=n,ys[o++]=s.x,ys[o++]=s.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(ys.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,ms);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),gs/4),n.draw_meshWithUniforms(e,i.shader,ms,gs,o)}catch(s){Ue(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ss={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},Ps=new Set;function Ms(e){const t=Ss[e];return void 0!==t?t:(Ps.has(e)||(Ps.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ss).join(", ")}`)),-1)}const Ts=new Map;function Es(e,t,s){Ts.set(e,{fn:t,scene:s??""})}function Cs(e){Ts.delete(e)}function As(){Ts.clear()}var Rs;exports.DataType=void 0,(Rs=exports.DataType||(exports.DataType={}))[Rs.Float=1]="Float",Rs[Rs.Float2=2]="Float2",Rs[Rs.Float3=3]="Float3",Rs[Rs.Float4=4]="Float4",Rs[Rs.Int=5]="Int",Rs[Rs.Int2=6]="Int2",Rs[Rs.Int3=7]="Int3",Rs[Rs.Int4=8]="Int4";let Is=null,Fs=0,ks=0,Bs=0;function Ds(e){Is=e,Fs=Is._malloc(262144),ks=Is._malloc(65536),Bs=Is._malloc(256)}function Us(){Is&&(Fs&&Is._free(Fs),ks&&Is._free(ks),Bs&&Is._free(Bs),Fs=0,ks=0,Bs=0),Is=null}function Ls(){if(!Is)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Is}const zs={create(e){const t=Ls(),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,Fs/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,Bs,i).set(o),t.geometry_init(s,Fs,n,Bs,i,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,ks,n).set(e.indices),t.geometry_setIndices16(s,ks,n)}else{new Uint32Array(t.HEAPU8.buffer,ks,n).set(e.indices),t.geometry_setIndices32(s,ks,n)}}return s},updateVertices(e,t,s=0){const n=Ls(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Fs/4),n.geometry_updateVertices(e,Fs,i,s)},release(e){e>0&&Ls().geometry_release(e)},isValid:e=>!(!Is||e<=0)&&Is.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return zs.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 i=n/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;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return zs.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,i=-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),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);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 zs.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let Ws=null;function $s(e){Ws=e}function Os(){Ws&&Xs.isInitialized()&&Xs.shutdown(),Ws=null}function Hs(){if(!Ws)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ws}const Xs={init(e,t){try{return Hs().postprocess_init(e,t)}catch(s){return Ue(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Hs().postprocess_shutdown()}catch(e){Ue(e,"PostProcess.shutdown")}},resize(e,t){try{Hs().postprocess_resize(e,t)}catch(s){Ue(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Hs().postprocess_addPass(e,t)}catch(t){return Ue(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Hs().postprocess_removePass(e)}catch(t){Ue(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Hs().postprocess_setPassEnabled(e,t)}catch(t){Ue(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Hs().postprocess_isPassEnabled(e)}catch(t){return Ue(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Hs().postprocess_setUniformFloat(e,t,s)}catch(s){Ue(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Hs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ue(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Hs().postprocess_begin()}catch(e){Ue(e,"PostProcess.begin")}},end(){try{Hs().postprocess_end()}catch(e){Ue(e,"PostProcess.end")}},getPassCount(){try{return Hs().postprocess_getPassCount()}catch(e){return Ue(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ws)return!1;try{return Ws.postprocess_isInitialized()}catch(e){return Ue(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Hs().postprocess_setBypass(e)}catch(e){Ue(e,"PostProcess.setBypass")}},isBypassed(){if(!Ws)return!0;try{return Ws.postprocess_isBypassed()}catch(e){return Ue(e,"PostProcess.isBypassed"),!0}},createBlur:()=>St.createShader(js,"#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:()=>St.createShader(js,"#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:()=>St.createShader(js,"#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:()=>St.createShader(js,"#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")},js="#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 Vs;exports.RenderStage=void 0,(Vs=exports.RenderStage||(exports.RenderStage={}))[Vs.Background=0]="Background",Vs[Vs.Opaque=1]="Opaque",Vs[Vs.Transparent=2]="Transparent",Vs[Vs.Overlay=3]="Overlay";let Ns=null,Ys=0;function Gs(e){Ns=e,Ys=Ns._malloc(64)}function qs(){Ns&&Ys&&(Ns._free(Ys),Ys=0),Ns=null}const Ks={init(e,t){Ns?.renderer_init(e,t)},resize(e,t){Ns?.renderer_resize(e,t)},begin(e,t){if(Ns&&Ys)try{Ns.HEAPF32.set(e,Ys/4),Ns.renderer_begin(Ys,t??0)}catch(e){Ue(e,"Renderer.begin")}},flush(){try{Ns?.renderer_flush()}catch(e){Ue(e,"Renderer.flush")}},end(){try{Ns?.renderer_end()}catch(e){Ue(e,"Renderer.end")}},submitSprites(e){if(Ns)try{Ns.renderer_submitSprites(e._cpp)}catch(e){Ue(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ns)try{Ns.renderer_submitBitmapText(e._cpp)}catch(e){Ue(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ns)try{Ns.renderer_submitSpine?.(e._cpp)}catch(e){Ue(e,"Renderer.submitSpine")}},setStage(e){Ns?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ns?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ns?.renderer_releaseTarget(e)},getTargetTexture:e=>Ns?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ns?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ns?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ns?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Ns?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Ns?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ns?Ns.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ns?{drawCalls:Ns.renderer_getDrawCalls(),triangles:Ns.renderer_getTriangles(),sprites:Ns.renderer_getSprites(),text:Ns.renderer_getText(),spine:Ns.renderer_getSpine?.()??0,meshes:Ns.renderer_getMeshes(),culled:Ns.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Js=null;function Qs(e){Js=e}function Zs(){Js=null}const en={enable(){Js?.gl_enableErrorCheck(!0)},disable(){Js?.gl_enableErrorCheck(!1)},check:e=>Js?.gl_checkErrors(e)??0,diagnose(){Js?.renderer_diagnose()}};class tn{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:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ks.resize(n,i),Xs.isInitialized()&&Xs.getPassCount()>0&&Xs.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ks.setViewport(0,0,n,i),Ks.clearBuffers(3),Ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),Ks.submitSprites(t),Ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ks.submitSpine(t),Ks.flush(),this.executeDrawCallbacks(s,o),Ks.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o}=e;Ks.setViewport(n.x,n.y,n.w,n.h),Ks.setScissor(n.x,n.y,n.w,n.h,!0),Ks.clearBuffers(i),Ks.setScissor(0,0,0,0,!1),Ks.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ks.submitSprites(t),Ks.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ks.submitSpine(t),Ks.flush(),this.executeDrawCallbacks(s,o),Ks.end()}executeDrawCallbacks(e,t){const s=Ts;if(s.size>0){bs.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}bs.end();for(const e of n)Cs(e)}}}const sn="__scene_transition_overlay__";class nn{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 on{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),Es(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Xs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Xs.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 s=this.app_.world.get(e,_e);s.persistent=t,this.app_.world.insert(e,_e,s)}}}class rn{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??$.sceneTransitionDuration,i=t.color??{...$.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},Es(sn,()=>{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;bs.setLayer(9999),bs.setDepth(9999),bs.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.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,Cs(sn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Cs(sn),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 nn(t);this.scenes_.set(e,s);const n=new on(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();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 s=new nn(t);this.scenes_.set(e,s);const n=new on(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ts)?this.app_.getResource(ts):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}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 i=t?.keepPersistent??!0;for(const e of s.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)}s.entities.clear();for(const e of s.drawCallbacks.keys())Cs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Xs.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},i={collectAssets:s};this.app_.hasResource(ts)&&(i.assetServer=this.app_.getResource(ts));const o=await Kt(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,_e,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ln(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(ts)?this.app_.getResource(ts):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)St.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 i=!1;if(s.has(e,ce)){const t=s.get(e,ce);n.sprite=t.color.a,t.color.a=0,s.insert(e,ce,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.spine=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}if(s.has(e,me)){const t=s.get(e,me);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,me,t),i=!0}i&&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,ce)){const t=s.get(e,ce);t.color.a=n.sprite,s.insert(e,ce,t)}if(void 0!==n.spine&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.spine,s.insert(e,ge,t)}if(void 0!==n.bitmapText&&s.has(e,me)){const t=s.get(e,me);t.color.a=n.bitmapText,s.insert(e,me,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Xs.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 an=Me(null,"SceneManager");function ln(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(an).getSceneStatus(t)&&s._fn(...n)}}}const cn=rt([Ee(an),Te(Re)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),dn={name:"SceneManager",build(e){const t=new rn(e);e.insertResource(an,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(an),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,cn)}};class un{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 et,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,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 Xe,this.resources_=new Ae;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new un}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 i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),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 De(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_}enableStats(){return this.statsEnabled_=!0,this}getSystemTimings(){return this.runner_?.getTimings()??null}getEntityCount(){return this.world_.entityCount()}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(an).register(e),this}setInitialScene(e){return this.getResource(an).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new lt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Re)||this.resources_.insert(Re,{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 lt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Re,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,As();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=[Zs,qs,Os,Us,vt,xs];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 i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.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 s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),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(Re);t.delta=e,t.elapsed+=e,t.frameCount++}}function hn(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 pn=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function fn(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case oe.FixedWidth:return o;case oe.FixedHeight:return r;case oe.Expand:return Math.max(o,r);case oe.Shrink:return Math.min(o,r);case oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const mn=[];function gn(e){if(e<mn.length)return mn[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 mn.push(t),t}function yn(e,t,s,n,i,o){if(0===s||0===n)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 s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,d=0,u=0;if(i.projectionType===ne.Orthographic){if(u=i.orthoSize,l){u=fn(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}d=u*r,a=xn(-d,d,-u,u,-i.farPlane,i.farPlane)}else a=vn(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Sn(o.position.x,o.position.y,o.position.z),p=gn(c.length);p.entity=e,p.viewProjection.set(Mn(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.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 _n=new Float32Array(16);function xn(e,t,s,n,i,o){const r=_n;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const wn=new Float32Array(16);function vn(e,t,s,n){const i=wn;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const bn=new Float32Array(16);function Sn(e,t,s){const n=bn;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 Pn=new Float32Array(16);function Mn(e,t){const s=Pn;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const Tn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function En(e,t,s,n,i,o,r={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,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=d+n.x),e.y===t.y?(f=u+s.y-i.y*r.y,g=f+i.y):(f=u+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const Cn=se("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 An=null,Rn=null;function In(e,t){e.has(t,ce)||e.insert(t,ce,{texture:X,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 Fn(e,t){switch(e){case Tn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Tn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Tn.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 kn(e,t,s,n){if(!e.has(t,Cn))return;const i=e.get(t,Cn),o=Fn(s,n);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,Cn,i)}function Bn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Dn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Un(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Dn(r.charCodeAt(0))&&n.length>0&&Dn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Dn(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function Ln(e){let t=1;for(;t<e;)t*=2;return t}function zn(e,t){let s=0,n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;s++,n=t}return s}function Wn(e,t){if(An&&Rn){const e=An.getUIRectComputedWidth(Rn,t);if(e>0)return e}return e.size.x}function $n(e,t){if(An&&Rn){const e=An.getUIRectComputedHeight(Rn,t);if(e>0)return e}return e.size.y}function On(e,t,s){let n=t;for(;e.has(n,pe);){const t=e.get(n,pe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Hn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Xn(e,t,s,n,i){if(!e.has(t,Cn))return;const o=e.get(t,Cn),r=En(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,re,s)}}function jn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Vn=.1,Nn=30,Yn={r:.3,g:.5,b:.8,a:1},Gn={Left:0,Center:1,Right:2},qn={Top:0,Middle:1,Bottom:2},Kn={Visible:0,Clip:1,Ellipsis:2},Jn=q("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Gn.Left,verticalAlign:qn.Top,wordWrap:!0,overflow:Kn.Visible,lineHeight:1.2});class Qn{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l($.textCanvasSize,$.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,Ln(this.frameMaxW_)),e.height=Math.max(e.height,Ln(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ln(this.frameMaxW_),e.height=Ln(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 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=Un(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=i?Math.ceil(o):u+2*d,f=i?Math.ceil(r):h+2*d;if(i&&e.overflow===Kn.Ellipsis&&h>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_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,Ln(p)),n.height=Math.max(n.height,Ln(f)));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;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(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===Kn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case qn.Top:w=d;break;case qn.Middle:w=d+(f-2*d-x)/2;break;case qn.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 Gn.Left:n=d;break;case Gn.Center:n=p/2;break;case Gn.Right:n=p-d;break;default:n=d}s.fillText(t,n,v),v+=c}i&&e.overflow===Kn.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 i=this.renderText(t,s);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[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 Gn.Left:return"left";case Gn.Center:return"center";case Gn.Right:return"right"}}}const Zn=jn({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?Wn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?$n(e.uiRect,e.entity):0});class ei{build(e){ee("Text",Jn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Qn(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Jn));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Jn)){if(n.valid(e)&&n.has(e,ce)){const t=n.get(e,ce);n.insert(e,ce,{texture:X,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=n.getEntitiesWithComponents([Jn]);for(const t of e){const e=n.get(t,Jn),o=n.has(t,Cn)?n.get(t,Cn):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Zn.changed(a,r)){if(n.has(t,ce)&&n.get(t,ce).texture!==X)continue}In(n,t);const l=o?{size:{x:Wn(o,t),y:$n(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,ce);n.insert(t,ce,{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,Zn.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ti=new ei,si=0,ni=1,ii=se("UIMask",{enabled:!0,mode:si});function oi(e,t){const s=Math.max(e.x,t.x),n=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:s,y:n,w:Math.max(0,i-s),h:Math.max(0,o-n)}}function ri(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=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],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,v=n*d-r*a,b=i*c-o*l,S=i*d-r*l,P=o*d-r*c,M=u*g-h*m,T=u*y-p*m,E=u*_-f*m,C=h*y-p*g,A=h*_-f*g,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+d*C)*I,s[1]=(o*A-i*R-r*C)*I,s[2]=(g*P-y*S+_*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(c*E-a*R-d*T)*I,s[5]=(n*R-o*E+r*T)*I,s[6]=(y*v-m*P-_*w)*I,s[7]=(u*P-p*v+f*w)*I,s[8]=(a*A-l*E+d*M)*I,s[9]=(i*E-n*A-r*M)*I,s[10]=(m*S-g*v+_*x)*I,s[11]=(h*v-u*S-f*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-i*T+o*M)*I,s[14]=(g*w-m*b-y*x)*I,s[15]=(u*b-h*w+p*x)*I),s}function ai(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*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 li(e,t){return 2*Math.atan2(e,t)}function ci(e,t,s,n,i,o,r){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,i+(.5*(l/c)+.5)*r]}function di(e,t,s,n,i,o,r){if(!e.has(t,Cn)||!e.has(t,re))return null;const a=e.get(t,Cn),l=e.get(t,re),c=Wn(a,t)*l.worldScale.x,d=$n(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-d*f,_=d*(1-f),x=li(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+m*w-y*v,h+m*v+y*w],[u+g*w-y*v,h+g*v+y*w],[u+g*w-_*v,h+g*v+_*w],[u+m*w-_*v,h+m*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=ci(e,t,s,n,i,o,r);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 ui(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ii]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,ii);s.enabled&&(u.add(e),s.mode===ni?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const d=[];for(const e of n){let s=!0;On(t,e,e=>{if(i.has(e)){if(t.get(e,ii).mode===si)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(i.has(s)){if(t.get(s,ii).mode===si){const e=di(t,s,o,r,a,l,c);e&&(n=oi(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=di(t,e,o,r,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,i,o,r,a),d.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;On(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&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,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,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,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,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,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 hi{build(e){if(ee("UIMask",ii),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ui(e.wasmModule,e.world))}}const pi=new hi,fi=se("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),mi=se("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),gi={Normal:0,Hovered:1,Pressed:2,Disabled:3},yi=q("Button",{state:gi.Normal,transition:null});class _i{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 xi=Me(new _i,"UIEvents");class wi{build(e){ee("UIRect",Cn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){An=e,Rn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(pt)],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,rt([Te(pt)],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,rt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const vi=new wi;let bi=!1,Si=!1;function Pi(){return bi}function Mi(){return Si}const Ti=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&&(ri(t,e),s=!1),e)}}();function Ei(e,t,s,n){t.emit(s,n,s),On(e,s,i=>{if(!e.has(i,fi))return!1;const o=e.get(i,fi);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Ci{build(e){ee("Interactable",fi),ee("Button",yi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new _i;e.insertResource(xi,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(dt),Te(pt)],(e,a)=>{if(i.drain(),Pi()&&!Mi())return;const l=t.getEntitiesWithComponents([mi]);for(const e of l){const s=t.get(e,mi);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,mi,s))}if(!a.valid)return;const c=d(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Ti.update(a.viewProjection);const p=ai(u,h,Ti.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);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,mi)){const e=t.get(o,mi);e.hovered=!1,t.insert(o,mi,e),i.emit(o,"hover_exit")}if(null!==_){Hn(t,_,mi);const e=t.get(_,mi);e.hovered=!0,t.insert(_,mi,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,mi);e.pressed=!0,e.justPressed=!0,t.insert(_,mi,e),r=_,Ei(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,mi)){const e=t.get(r,mi);e.pressed=!1,e.justReleased=!0,t.insert(r,mi,e),Ei(t,i,r,"release"),r===o&&Ei(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,rt([],()=>{const e=t.getEntitiesWithComponents([yi]);for(const s of e){if(Hn(t,s,fi,{enabled:!0}),!t.has(s,mi))continue;const e=t.get(s,mi),n=t.get(s,yi),i=t.get(s,fi),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=gi.Pressed:e.hovered?n.state=gi.Hovered:n.state=gi.Normal:n.state=gi.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ce)){const o=t.get(s,ce);o.color=Bn(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ce,o)}}},{name:"ButtonSystem"}))}}const Ai=new Ci,Ri=q("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}),Ii=q("Focusable",{tabIndex:0,isFocused:!1});class Fi{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 ki=Me(new Fi,"FocusManager");class Bi{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ee("TextInput",Ri),Pi()&&!Mi())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l($.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=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 m(){const t=e.getResource(ki);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Ri)?n:null}const g=()=>{c||null===m()||v()},y=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Ri);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(xi).emit(n,"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,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Ri);n.focused=!1,n.dirty=!0;e.getResource(ki).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Ri);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(xi).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Ri);e.focused=!1,e.dirty=!0}e.getResource(ki).blur(),f.blur()}function S(){d=!0,u=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),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!==r&&(t._free(r),r=0,a=0)};let P=null;function M(e,l,c,u){(i.width<c||i.height<u)&&(i.width=Ln(Math.max(i.width,c)),i.height=Ln(Math.max(i.height,u))),o.clearRect(0,0,i.width,i.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,m=p?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),y=l.padding;if(l.multiline){const e=Un(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(u-l.fontSize)/2;o.fillText(f,y,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=Un(o,l.value,c-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const d=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(d).width,s=y+r*g,n=g}else t=y+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!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,u,r,x.length,1,!0);n.set(e,b);const S=s.get(e,ce);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,ce,S)}e.addSystemToSchedule(exports.Schedule.Update,rt([Te(ki)],e=>{const t=s.getEntitiesWithComponents([Ri]);for(const e of t)Hn(s,e,Ii,{tabIndex:0,isFocused:!1}),Hn(s,e,fi,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Ri)){const e=s.get(P,Ri);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Ri);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,rt([],()=>{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 o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,d=!d;s.get(o,Ri).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Ri)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Ri,Cn]);for(const e of a){const t=s.get(e,Ri);if(!t.dirty)continue;const n=s.get(e,Cn),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(In(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Di=new Bi,Ui={Simple:0,Sliced:1,Tiled:2,Filled:3},Li={Horizontal:0,Vertical:1},zi={Left:0,Right:1,Bottom:2,Top:3},Wi=q("Image",{texture:X,color:{r:1,g:1,b:1,a:1},imageType:Ui.Simple,fillMethod:Li.Horizontal,fillOrigin:zi.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$i=jn({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?Wn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?$n(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Oi=new class{build(e){ee("Image",Wi);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Wi)||s.delete(e);const e=t.getEntitiesWithComponents([Wi]);for(const n of e){const e=t.get(n,Wi),i=t.has(n,Cn)?t.get(n,Cn):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!$i.changed(r,o))continue;In(t,n);const a=t.get(n,ce);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=Wn(i,n),a.size.y=$n(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Ui.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Li.Horizontal?e.fillOrigin===zi.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===zi.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===Ui.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,ce,a),s.set(n,$i.take(o))}else a.color.a=0,t.insert(n,ce,a),s.set(n,$i.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Hi=q("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Xi=q("ToggleGroup",{allowSwitchOff:!1});const ji=new class{build(e){ee("Toggle",Hi),ee("ToggleGroup",Xi);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,rt([Te(xi)],e=>{const n=t.getEntitiesWithComponents([Hi]);if(!Pi()||Mi()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Hi);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Hi,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Hi);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(Hn(t,s,fi,{enabled:!0}),!t.has(s,mi))continue;const n=t.get(s,mi),i=t.get(s,Hi),r=t.get(s,fi);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Xi);if(i.isOn&&r){if(!t.get(n,Xi).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Hi,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,Hi);i.isOn&&(i.isOn=!1,t.insert(n,Hi,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ce)){const e=t.get(s,ce);e.color=Bn(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ce,e)}}}for(const e of n){const s=t.get(e,Hi);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ce)){const e=t.get(s.graphicEntity,ce);e.enabled=s.isOn,t.insert(s.graphicEntity,ce,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Vi=Tn,Ni=q("ProgressBar",{value:0,fillEntity:0,direction:Tn.LeftToRight});function Yi(e,t,s,n){if(!e.has(t,Cn))return;const i=e.get(t,Cn),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=En(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ce)){const s=e.get(t,ce);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ce,s))}if(e.has(t,re)){const s=e.get(t,re),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,re,s))}}class Gi{build(e){ee("ProgressBar",Ni);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e=t.getEntitiesWithComponents([Ni,Cn]);for(const s of e){const e=t.get(s,Ni);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Cn),i=Math.max(0,Math.min(1,e.value));kn(t,e.fillEntity,e.direction,i);const o=Wn(n,s),r=$n(n,s);Yi(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const qi=new Gi,Ki=q("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ji=q("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 Qi=new class{build(e){ee("Draggable",Ki),ee("DragState",Ji);const t=e.world,s=e.getResource(xi);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(dt),Te(pt)],(e,r)=>{if(Pi()&&!Mi())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ki,mi]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Ki).enabled)continue;if(t.get(n,mi).hovered){let e=0;t.has(n,ce)&&(e=t.get(n,ce).layer);const i=zn(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Ji)||t.insert(s,Ji);const e=t.get(s,Ji),o=t.get(s,re);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,Ji)){t.get(n,Ji).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Ki);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Ji).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Ji))return void(o=null);const n=t.get(o,Ji),i=t.get(o,Ki),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;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,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,re)){const e=function(e,t,s,n){if(!e.has(t,pe))return{x:s,y:n};const i=e.get(t,pe).entity;if(!e.valid(i)||!e.has(i,re))return{x:s,y:n};const o=e.get(i,re),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=li(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/r,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,re);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,re,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Zi=q("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function eo(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 to(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const so=new class{build(e){ee("ScrollView",Zi);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(dt),Te(pt),Te(Re)],(e,i,o)=>{const r=Pi()&&!Mi(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Zi,Cn]);for(const o of l){Hn(t,o,ii,{enabled:!0,mode:si});const l=t.get(o,Zi),c=t.get(o,Cn);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=Wn(c,o),h=$n(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,fe)){const e=t.get(l.contentEntity,fe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,re))continue;const e=t.get(r,re);let a=0,l=0,c=.5,d=.5;if(t.has(r,Cn)){const e=t.get(r,Cn);a=Wn(e,r)||e.size.x,l=$n(e,r)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(r,ce)){const e=t.get(r,ce);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<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-u),g=Math.max(0,f-h);if(!r&&i.valid){Hn(t,o,fi,{enabled:!0,blockRaycast:!0});const s=t.has(o,mi)?t.get(o,mi):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=eo(l.scrollX,0,m,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=eo(l.scrollY,0,g,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=eo(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=eo(l.scrollX,0,m,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.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=to(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)<Vn&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Vn?(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:g,t=to(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)<Vn&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Vn?(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,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),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,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,re)){const e=t.get(l.contentEntity,re),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,re,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},no=Tn,io=q("Slider",{value:0,minValue:0,maxValue:1,direction:Tn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function oo(e,t,s,n,i,o){const r=Wn(n,i)*s.worldScale.x,a=$n(n,i)*s.worldScale.y,l=li(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,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case Tn.LeftToRight:return r>0?(p-m)/r:0;case Tn.RightToLeft:return r>0?1-(p-m)/r:0;case Tn.BottomToTop:return a>0?(f-g)/a:0;case Tn.TopToBottom:return a>0?1-(f-g)/a:0}}function ro(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Tn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case Tn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case Tn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case Tn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ao{build(e){ee("Slider",io);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(dt),Te(pt),Te(xi)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([io,Cn]);for(const r of o){const o=t.get(r,io),a=t.get(r,Cn);if(!Pi()||Mi()){if(t.has(r,re)){Hn(t,r,fi,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Hn(t,o.handleEntity,fi,{enabled:!0,blockRaycast:!1});const l=t.get(r,re),c=t.has(r,mi)?t.get(r,mi):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,mi)&&(d=t.get(o.handleEntity,mi).justPressed),d&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=oo(n.worldMouseX,n.worldMouseY,l,a,r,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(r,io,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Wn(a,r),u=$n(a,r),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(kn(t,o.fillEntity,o.direction,c),Xn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Cn)){const e=t.get(o.handleEntity,Cn);ro(e,o.direction,c),t.insert(o.handleEntity,Cn,e),Xn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const lo=new ao;const co=new class{build(e){ee("Focusable",Ii);const t=e.world,s=new Fi;e.insertResource(ki,s),e.addSystemToSchedule(exports.Schedule.Update,rt([Te(dt),Te(xi)],(e,n)=>{if(Pi()&&!Mi())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ii]);for(const e of i){if(!t.has(e,mi))continue;t.get(e,mi).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,fi)){if(!t.get(s,fi).enabled)continue}const n=t.get(s,Ii);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 r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Ii)){t.get(i,Ii).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ii).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},uo=q("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ho(){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:i}=t;return{top:s.top,bottom:i-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 po=new class{build(e){ee("SafeArea",uo);const t=e.world;let n=ho(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=ho(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=ho(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([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,i=!0),!i)return;i=!1;const l=d(),c=s()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([uo,Cn]);for(const e of u){const s=t.get(e,uo),i=t.get(e,Cn),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 d=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,Cn,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},fo=q("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let mo=null;const go=new class{build(e){ee("ListView",fo);const t=e.world,s=new Map;mo=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(dt)],e=>{const n=Pi()&&!Mi();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 i=t.getEntitiesWithComponents([fo,Cn]);for(const o of i){Hn(t,o,fi,{enabled:!0,blockRaycast:!0}),Hn(t,o,ii,{enabled:!0,mode:si});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,fo),a=t.get(o,Cn),l=$n(a,o),c=Wn(a,o);if(!n){const s=t.has(o,mi)?t.get(o,mi):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const d=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,d));const u=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=u;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ye,{value:`ListItem_${e}`}),t.insert(s,Cn,{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(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,re)){const n=t.get(s,re);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,re,n)}}i.visibleStart=u,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},yo=q("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const _o=new class{build(e){ee("Dropdown",yo);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,re))return;const s=t.get(e,re);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,re,{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 i(e){if(t.has(e,ce)){const s=t.get(e,ce);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ce,{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 i=s.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(n);const o=t.get(e,ce),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Nn;t.insert(i,Cn,{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,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,ce,{texture:X,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<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Nn;t.insert(o,ye,{value:`Option_${e}`}),t.insert(o,Cn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Nn},offsetMax:{x:0,y:0},size:{x:r,y:Nn},pivot:{x:.5,y:.5}}),t.insert(o,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(o,ce,{texture:X,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Nn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,fi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);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,Jn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Gn.Left,verticalAlign:qn.Middle,wordWrap:!1,overflow:Kn.Clip,lineHeight:1.2}),t.insert(c,Cn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Nn},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function r(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Jn))return;const n=t.get(s,Jn);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.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(s,Jn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,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,fi)&&t.insert(e,fi,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ce))){const n=t.get(e,ce);t.insert(e,ce,{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,ce))continue;const i=s===e.highlightIndex?{...Yn}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ce,{texture:X,color:i,size:{x:e.ddWidth,y:Nn},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,mi))continue;if(t.get(s,mi).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,rt([Te(dt),Te(xi)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=Pi()&&!Mi(),f=t.getEntitiesWithComponents([yo]);for(const m of f){const f=t.get(m,yo);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||d(f.listEntity,!1),l(f),p)continue;Hn(t,m,fi,{enabled:!0,blockRaycast:!0});const y=t.has(m,mi)?t.get(m,mi):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,mi))continue;if(t.get(s,mi).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,mi))continue;if(t.get(n,mi).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,u(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,u(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,u(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},xo=0,wo=0,vo=2,bo=q("LayoutGroup",{direction:xo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:wo,reverseOrder:!1});const So=new class{build(e){ee("LayoutGroup",bo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([],()=>{const e=t.getEntitiesWithComponents([bo,Cn,fe]);for(const s of e){const e=t.get(s,bo),n=t.get(s,Cn),i=t.get(s,fe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Cn)&&t.has(e,re)&&o.push({entity:e,rect:t.get(e,Cn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Wn(n,s),a=$n(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===xo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Wn(n.rect,n.entity),p=$n(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;u?(g=-l*r+d.left+h+f*i,y=e.childAlignment===wo?(1-c)*a-d.top-(1-m)*p:e.childAlignment===vo?-c*a+d.bottom+m*p:(.5-c)*a+.5*(d.bottom-d.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===wo?-l*r+d.left+f*i:e.childAlignment===vo?(1-l)*r-d.right-(1-f)*i:(.5-l)*r+.5*(d.left-d.right)+(f-.5)*i,y=(1-c)*a-d.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,re);_.position.x=g,_.position.y=y,t.insert(n.entity,re,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};se("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),se("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class Po{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Mo=new Po;async function To(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 Eo=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Co=Me(null,"PhysicsAPI");function Ao(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Ro(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Io{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(Eo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=To(this.wasmUrl_,this.factory_).then(n=>{n._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 s of t){const t=e.world.get(s,ue);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,rt([Te(Re)],a=>{const l=r.getEntitiesWithComponents([xe,re]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,xe),l=r.get(i,re);if(t.has(i)){const e=s.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||(n._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=Ao(l.worldRotation);n._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),Fo(e,n,i),t.add(i),s.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=Ao(l.worldRotation);n._physics_setBodyTransform(i,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 i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const d=e.world.get(r,re);if(!d)continue;let u=a,h=l,p=c;if(e.world.has(r,pe)){const t=e.world.get(r,pe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,re)){const s=e.world.get(t.entity,re),n=Ao(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),d=Math.sin(-n);u=(i*r-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*d+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}d.position.x=u,d.position.y=h;const f=Ro(p);d.rotation.w=f.w,d.rotation.x=f.x,d.rotation.y=f.y,d.rotation.z=f.z,e.world.insert(r,re,d)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],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;n.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]*s,contactY:t.HEAPF32[i+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;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(Eo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Co,ko._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function Fo(e,t,s){const n=e.world;if(n.has(s,we)){const e=n.get(s,we);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,ve)){const e=n.get(s,ve);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,be)){const e=n.get(s,be);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 ko{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(ko.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 Bo={nearest:0,linear:1},Do={repeat:0,clamp:1,mirror:2};function Uo(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=Bo[n.filterMode??"linear"]??1,a=Do[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function Lo(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 zo(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=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,m=a*h,g=a*p,y=l*h,_=l*p,x=c*p,w=d*u,v=d*h,b=d*p;return new Float32Array([(1-(y+x))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(f+x))*o,(_+w)*o,0,(g+v)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Wo(e,t,s,n,i,o,r,a,l){const c=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Xt(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===n[o])try{const t=i?.[o];n[o]=Uo(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 i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,s,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,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=jt(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===v(c)?.contentType;let u,h;if(r){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),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,r);if(t._free(u),p<0)continue;o[a]=p;const f=Lo(n),m=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=Uo(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,u,s,n)),o){const t={gravity:r?.gravity??{...z},fixedTimestep:r?.fixedTimestep??W,subStepCount:r?.subStepCount??4};new Io("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=Xt(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=v(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=Uo(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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Xt(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.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 i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=St.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=St.createFromAsset(e,r)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Xt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(s,c,h,p);const f=qt(e.world,s);if(l&&e.hasResource(an))for(const t of f.values())e.world.insert(t,_e,{scene:l,persistent:!1});if(i&&u){const n=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=jt(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.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}(u,s,d,f);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=L);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ge)?c.get(o,ge):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(r,l*u);let h=0;if(c.has(o,re)){const e=zo(c.get(o,re),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,d,u,p);const f=s.HEAPU32[u>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(p)}h&&t._free(h)}})}(e,t,i,u,n)}if(a){const t=e.getResource(ts);t&&t.setAddressableManifest(a)}}function $o(e,t,s){return{name:e,async setup(){await Wo(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class Oo{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 i of e.entities)for(const e of i.components){if(!e.data)continue;const i=jt(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===v(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Xt(e.type);for(const s of o){const i=e.data[s.field];"string"==typeof i&&i&&("font"===s.type?(n.add(i),t.add(i)):"material"===s.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 s)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 n){const t=v(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(),i=await createImageBitmap(n),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 Ho="__preview__";const Xo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ks.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ks.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ks.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ks.releaseRenderTarget(e._handle),Xo.create({width:t,height:s,depth:!0})),begin(e,t){Ks.begin(t,e._handle)},end(){Ks.end()},getDepthTexture:e=>Ks.getTargetDepthTexture(e._handle)};var jo;exports.LogLevel=void 0,(jo=exports.LogLevel||(exports.LogLevel={}))[jo.Debug=0]="Debug",jo[jo.Info=1]="Info",jo[jo.Warn=2]="Warn",jo[jo.Error=3]="Error";class Vo{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 No{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Vo)}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 i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Yo=new No;const Go={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},qo={None:0,Restart:1,PingPong:2};class Ko{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 Jo=null,Qo=null;function Zo(e,t){Jo=e,Qo=t}function er(){Jo=null,Qo=null}function tr(){if(!Jo)throw new Error("Tween API not initialized");return Jo}function sr(){if(!Qo)throw new Error("Tween API not initialized");return Qo}const nr={to(e,t,s,n,i,o){const r=tr(),a=sr(),l=o?.easing??Go.Linear,c=o?.delay??0,d=o?.loop??qo.None,u=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,d,u);return new Ko(r,a,h)},cancel(e){tr()._anim_cancelTween(sr(),e.entity)},cancelAll(e){tr()._anim_cancelAllTweens(sr(),e)},update(e){tr()._anim_updateTweens(sr(),e)}};class ir{constructor(){this.name="AnimationPlugin"}build(e){Zo(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,rt([Te(Re)],e=>{nr.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,rt([Te(Re)],e=>{Wt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){er()}}const or=new ir;var rr;exports.AttenuationModel=void 0,(rr=exports.AttenuationModel||(exports.AttenuationModel={}))[rr.Linear=0]="Linear",rr[rr.Inverse=1]="Inverse",rr[rr.Exponential=2]="Exponential";const ar={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function lr(e,t=ar){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;return 1-(Math.min(Math.max(r,n),i)-n)/e}case exports.AttenuationModel.Inverse:return n/Math.max(r,n);case exports.AttenuationModel.Exponential:return Math.pow(Math.max(r,n)/n,-o);default:return 1}}function cr(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const dr=q("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}),ur=q("AudioListener",{enabled:!0});class hr{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize});const i=s.mixer;$t.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,rt([Te(Re)],t=>{const n=e.world;let i=0,r=0;const a=n.getEntitiesWithComponents([ur,le]);for(const e of a){if(n.get(e,ur).enabled){const t=n.get(e,le);i=t.position.x,r=t.position.y;break}}const l=n.getEntitiesWithComponents([dr,le]),c=new Set;for(const e of l){const t=n.get(e,dr);if(!t.enabled||!t.clip)continue;c.add(e);const a=n.get(e,le);if(t.playOnAwake&&!o.has(e)){const n=$t.getBufferHandle(t.clip);if(n){const i=s.play(n,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch,priority:t.priority});o.set(e,i)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(e)){const s=o.get(e);if(!s.isPlaying){o.delete(e);continue}const n=a.position.x-i,l=a.position.y-r,c=lr(Math.sqrt(n*n+l*l),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),d=cr(a.position.x,a.position.y,i,0,t.maxDistance);s.setVolume(t.volume*c),s.setPan(d)}}for(const[e,t]of o)c.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){$t.dispose()}}const pr=new hr;function fr(e,t){return e.toFixed(t)}class mr{constructor(e,t="bottom-left"){this.visible_=!0,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${fr(e.fps,1)}</span> Frame: <span style="color:#d19a66">${fr(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${fr(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.el_.parentElement?.removeChild(this.el_)}}function gr(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const yr=Me(gr(),"Stats");class _r{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60)}getFps(){return 0===this.count_||0===this.sum_?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||0===this.sum_?0:this.sum_/this.count_*1e3}}class xr{constructor(e){this.name="Stats",this.collector_=new _r,this.overlay_=null,this.options_=e??{}}build(e){e.enableStats(),e.insertResource(yr,gr());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new mr(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=rt([Te(Re),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(yr);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();o.systemTimings=r?new Map(r):new Map;const a=Ks.getStats();o.drawCalls=a.drawCalls,o.triangles=a.triangles,o.sprites=a.sprites,o.text=a.text,o.spine=a.spine,o.meshes=a.meshes,o.culled=a.culled,s?.update(o)},{name:"StatsCollect"});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const wr=new xr;class vr{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 i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.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 br(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 Sr=[ti,pi,vi,Oi,qi,Ai,Qi,so,lo,ji,Di,co,po,go,_o,So,Mo],Pr=[...Sr,or];function Mr(e,t){return function(e,t){const s=un.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),_s(e),wt(e),Ds(e),$s(e),Gs(e),Qs(e);const i=new tn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=d();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=yn(e,n,t,i));const r=s.getResource(pt);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.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}s.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)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;Ks.setClearColor(e.x,e.y,e.z,e.w)}const u=(c()-o)/1e3;let h;if(Ks.resize(t,l),Xs.isInitialized()&&Xs.getPassCount()>0&&!Xs.isBypassed()&&Xs.resize(t,l),s.hasResource(an)){const e=s.getResource(an).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=yn(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:pn,width:t,height:l,elapsed:u});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u})}Ks.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(ns),s.addPlugin(hs),s.addPlugin(ht),s.addPlugin(dn),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Pr,...t})}class Tr{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 i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function Er(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function Cr(e,t){try{return await e({instantiateWasm:Er(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!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},i=await f(s,n);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: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 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),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}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 i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=ir,exports.App=un,exports.AssetPlugin=ss,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=es,exports.Assets=ts,exports.AsyncCache=Ft,exports.Audio=$t,exports.AudioBus=u,exports.AudioListener=ur,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new u(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new u(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new u(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new u(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new u(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 u(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}},exports.AudioPlugin=hr,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,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,this.activeCount_++,t}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=dr,exports.BitmapText=me,exports.BodyType=Se,exports.BoxCollider=we,exports.Button=yi,exports.ButtonState=gi,exports.Camera=de,exports.Canvas=ue,exports.CapsuleCollider=be,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=fe,exports.CircleCollider=ve,exports.ClearFlags=ie,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Qe,exports.DEFAULT_DESIGN_HEIGHT=U,exports.DEFAULT_DESIGN_WIDTH=D,exports.DEFAULT_FALLBACK_DT=L,exports.DEFAULT_FIXED_TIMESTEP=W,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=z,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=Ji,exports.Draggable=Ki,exports.Draw=bs,exports.Dropdown=yo,exports.EasingType=Go,exports.EntityCommands=Je,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=st,exports.EventRegistry=et,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=tt,exports.FillDirection=Tn,exports.FillMethod=Li,exports.FillOrigin=zi,exports.FocusManager=ki,exports.FocusManagerState=Fi,exports.Focusable=Ii,exports.GLDebug=en,exports.Geometry=zs,exports.GetWorld=it,exports.INVALID_ENTITY=0,exports.INVALID_FONT=j,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=X,exports.Image=Wi,exports.ImageType=Ui,exports.Input=dt,exports.InputPlugin=ut,exports.InputState=ct,exports.Interactable=fi,exports.ListView=fo,exports.LocalTransform=ae,exports.Logger=No,exports.LoopMode=qo,exports.Material=St,exports.MaterialLoader=kt,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ye,exports.Parent=pe,exports.Physics=ko,exports.PhysicsEvents=Eo,exports.PhysicsPlugin=Io,exports.PostProcess=Xs,exports.PrefabServer=cs,exports.Prefabs=ds,exports.PrefabsPlugin=us,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(an);t.register({name:Ho,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Ho),this.loadPromise_=t.load(Ho).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 Oo(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await Wo(this.app_,this.app_.wasmModule,t,s,i,null,void 0,null,Ho)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([de]);for(const n of s){if(e.get(n,de).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([ue]);for(const i of n){const n=e.get(i,ue);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(an).getScene(Ho),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,re,r);const a={isActive:!0,projectionType:ne.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ie.ColorAndDepth};e.insert(o,de,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(an);await e.switchTo(Ho),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=Ni,exports.ProgressBarDirection=Vi,exports.ProgressBarPlugin=Gi,exports.ProjectionType=ne,exports.Query=function(...e){return Ge(e)},exports.QueryInstance=qe,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ke,exports.RenderPipeline=tn,exports.RenderTexture=Xo,exports.Renderer=Ks,exports.Res=Te,exports.ResMut=Ee,exports.RigidBody=xe,exports.RuntimeConfig=$,exports.SafeArea=uo,exports.ScaleMode=oe,exports.SceneManager=an,exports.SceneManagerState=rn,exports.SceneOwner=_e,exports.ScrollView=Zi,exports.ShaderSources=It,exports.Slider=io,exports.SliderDirection=no,exports.SliderPlugin=ao,exports.SpineAnimation=ge,exports.Sprite=ce,exports.SpriteAnimator=zt,exports.Stats=yr,exports.StatsCollector=_r,exports.StatsOverlay=mr,exports.StatsPlugin=xr,exports.SystemRunner=lt,exports.Text=Jn,exports.TextAlign=Gn,exports.TextInput=Ri,exports.TextInputPlugin=Bi,exports.TextOverflow=Kn,exports.TextPlugin=ei,exports.TextRenderer=Qn,exports.TextVerticalAlign=qn,exports.Time=Re,exports.Toggle=Hi,exports.Transform=re,exports.Tween=nr,exports.TweenHandle=Ko,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=pt,exports.UIEventQueue=_i,exports.UIEvents=xi,exports.UIInteraction=mi,exports.UIInteractionPlugin=Ci,exports.UILayoutPlugin=wi,exports.UIMask=ii,exports.UIMaskPlugin=hi,exports.UIRect=Cn,exports.UIRenderOrderPlugin=Po,exports.Velocity=he,exports.WeChatAssetProvider=Tr,exports.WebAssetProvider=Oo,exports.World=Xe,exports.WorldTransform=le,exports.addStartupSystem=function(e){at().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){at().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){at().push({schedule:e,system:t})},exports.animationPlugin=or,exports.applyBuildRuntimeConfig=H,exports.applyDirectionalFill=kn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=$.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=$.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=$.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=$.canvasMatchWidthOrHeight)},exports.assetPlugin=ns,exports.audioPlugin=pr,exports.calculateAttenuation=lr,exports.calculatePanning=cr,exports.clearAnimClips=function(){Ut.clear()},exports.clearDrawCallbacks=As,exports.clearUserComponents=function(){const e=G();for(const t of e.keys())Z.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Fn,exports.computeFillSize=function(e,t,s,n){switch(e){case Tn.BottomToTop:case Tn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case Tn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Tn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Tn.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=En,exports.createMaskProcessor=ui,exports.createRuntimeSceneConfig=$o,exports.createWebApp=Mr,exports.debug=function(e,t,s){Yo.debug(e,t,s)},exports.defaultFrameStats=gr,exports.defineComponent=q,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Me,exports.defineSystem=rt,exports.defineTag=function(e){const t=Z.get(e)??G().get(e);if(t)return t;const s=Y(e,{});return G().set(e,s),Z.set(e,s),J(e,{},!0),s},exports.error=function(e,t,s){Yo.error(e,t,s)},exports.extractAnimClipTexturePaths=Bt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ye]);for(const n of s){const s=e.get(n,ye);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=hn,exports.getAddressableType=function(e){return v(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAnimClip=function(e){return Ut.get(e)},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=v,exports.getComponent=te,exports.getComponentAssetFieldDescriptors=Xt,exports.getComponentAssetFields=Ht,exports.getComponentDefaults=function(e){const t=te(e);return t?V(t._default):null},exports.getComponentEntityFields=Nt,exports.getComponentSpineFieldDescriptor=jt,exports.getCustomExtensions=S,exports.getEditorType=function(e){return v(e)?.editorType??"unknown"},exports.getLogger=function(){return Yo},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=K,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Yo.info(e,t,s)},exports.initDrawAPI=_s,exports.initGLDebugAPI=Qs,exports.initGeometryAPI=Ds,exports.initMaterialAPI=wt,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,sceneData:i,sceneName:o}=e,r=t.getResource(ts);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0)),hn(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await br(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 br(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=$o(o,i,{app:t,module:s,provider:new vr(n),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(an);d.register(c),d.setInitial(o),await d.load(o);const u=e.canvas.width/e.canvas.height;Zt(t.world,u),t.run()},exports.initPostProcessAPI=$s,exports.initRendererAPI=Gs,exports.initTweenAPI=Zo,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=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:Er("esengine.wasm")}),l=i.getContext("webgl2")||i.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=Mr(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&H(d,e.runtimeConfig),hn(d);let u=null;e.spineFactory&&(u=await Cr(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await Cr(e.physicsFactory,"physics.wasm"));const p={app:d,module:a,provider:new Tr(n),spineModule:u,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s},f=d.getResource(an);for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`),s=JSON.parse(e);f.register($o(t,s,p))}e.firstScene&&(f.setInitial(e.firstScene),await f.load(e.firstScene));const m=i.width/i.height;Zt(d.world,m),d.run()},exports.inputPlugin=ht,exports.instantiatePrefab=is,exports.intersectRects=oi,exports.invertMatrix4=ri,exports.isBuiltinComponent=Q,exports.isCustomExtension=P,exports.isEditor=Pi,exports.isKnownAssetExtension=b,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=Mi,exports.isRuntime=function(){return!bi},exports.isTextureRef=mt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=Qt,exports.loadPhysicsModule=To,exports.loadRuntimeScene=Wo,exports.loadSceneData=qt,exports.loadSceneWithAssets=Kt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&b(w(e)))},exports.parseAnimClipData=Dt,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const d=li(l,c),u=Math.sin(-d),h=Math.cos(-d),p=e-s,f=t-n,m=p*h-f*u+s,g=p*u+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=hs,exports.progressBarPlugin=qi,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Lt,exports.registerComponent=ee,exports.registerComponentAssetFields=function(e,t){Ot.set(e,t)},exports.registerComponentEntityFields=function(e,t){Vt.set(e,t)},exports.registerDrawCallback=Es,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ts);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Rt,exports.remapEntityFields=Yt,exports.sceneManagerPlugin=dn,exports.screenToWorld=ai,exports.setEditorMode=function(e){bi=e},exports.setListViewRenderer=function(e,t){if(!mo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=mo.get(e);s?s.renderer=t:mo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Yo.setMinLevel(e)},exports.setPlayMode=function(e){Si=e},exports.setWasmErrorHandler=De,exports.shutdownDrawAPI=xs,exports.shutdownGLDebugAPI=Zs,exports.shutdownGeometryAPI=Us,exports.shutdownMaterialAPI=vt,exports.shutdownPostProcessAPI=Os,exports.shutdownRendererAPI=qs,exports.shutdownTweenAPI=er,exports.sliderPlugin=lo,exports.spriteAnimatorSystemUpdate=Wt,exports.statsPlugin=wr,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ce))return;const r=e.get(t,ce);let a,l;switch(s){case Tn.BottomToTop:case Tn.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ce,r))},exports.textInputPlugin=Di,exports.textPlugin=ti,exports.toBuildPath=M,exports.transitionTo=async function(e,t,s){const n=e.getResource(an);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=Ai,exports.uiLayoutPlugin=vi,exports.uiMaskPlugin=pi,exports.uiPlugins=Sr,exports.uiRenderOrderPlugin=Mo,exports.unregisterAnimClip=function(e){Ut.delete(e)},exports.unregisterComponent=function(e){G().delete(e),Z.delete(e)},exports.unregisterDrawCallback=Cs,exports.updateCameraAspectRatio=Zt,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){Yo.warn(e,t,s)},exports.wrapSceneSystem=ln,exports.wxFileExists=function(e){return new Promise(t=>{E().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{E().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(C(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{E().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(C(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{E().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 ae9334336..3ab55156c 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 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}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}],_={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"},y=new Map,w=new Set;for(const e of g)for(const t of e.extensions)y.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 y.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 A(){return C().map(e=>({type:"suffix",value:e}))}function R(e){return _[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 $(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 W(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 o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=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(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},V=1920,N=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",oe={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function re(e){e.Text&&(e.Text._default.fontFamily=oe.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=oe.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=oe.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=oe.canvasMatchWidthOrHeight)}const ae={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function le(e,t){if(void 0!==t.maxDeltaTime&&(oe.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(oe.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(oe.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(oe.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(oe.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");oe.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&&(oe.canvasScaleMode=ae[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(oe.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}),_e=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ye(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ye);const t={};for(const n in e)t[n]=ye(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?{...ye(t),...e}:ye(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=Ae.get(e)??ve().get(e);if(n)return n;const s=xe(e,t);return ve().set(e,s),Ae.set(e,s),Ee(e,t,!1),s}function Se(e){const t=Ae.get(e)??ve().get(e);if(t)return t;const n=xe(e,{});return ve().set(e,n),Ae.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())Ae.delete(t);e.clear()}function Te(e){ve().delete(e),Ae.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 Ae=new Map;function Re(e,t){Ae.set(e,t)}function Ie(e){return Ae.get(e)??Pe(e)}function ke(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ae.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}}),$e=Ue,We=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:V,y:N},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}),Ve=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}),Ne=be("Name",{value:""}),Ge=be("SceneOwner",{scene:"",persistent:!1});function qe(e){const t=Ie(e);return t?ye(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 ot{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 rt{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 ot(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]),o=ct(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,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 _t(e){let t=gt.get(e);return void 0===t&&(t=mt++,gt.set(e,t)),t}const yt=[];function wt(e,t=[],n=[]){yt.length=0;for(const t of e)yt.push(_t(t));yt.sort((e,t)=>e-t);let s=yt.join(",");if(t.length>0){yt.length=0;for(const e of t)yt.push(_t(e));yt.sort((e,t)=>e-t),s+="|+"+yt.join(",")}if(n.length>0){yt.length=0;for(const e of n)yt.push(_t(e));yt.sort((e,t)=>e-t),s+="|-"+yt.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}`],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=lt(t._name,t._default,s);if(e.length>0)throw new Error(ut(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,pt(i))}catch(n){ft(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 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),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 Ae)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),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(!Ce(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 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=[],o=[];return e.forEach((e,t)=>{bt(e)&&s.push(t),Mt(e)?i.push({index:t,component:e._component}):Tt(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Ct(e,[...t,...s],n),without:(...s)=>Ct(e,t,[...n,...s])}}function At(...e){return Ct(e)}class Rt{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,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 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 $t{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 Wt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new $t)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new $t,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 Vt(e,t,n){const s=++Yt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Nt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Gt(e){Nt().push({schedule:jt.Update,system:e})}function qt(e){Nt().push({schedule:jt.Startup,system:e})}function Kt(e,t){Nt().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 Rt(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,Vt([],()=>{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 on(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 rn=null,an=null,ln=1;const cn=new Map;function un(e){rn=e,an=e.getResourceManager(),xn()}function hn(){0!==mn&&rn&&(rn._free(mn),mn=0),cn.clear(),ln=1,pn=!1,_n.clear(),yn=null,an=null,rn=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,rn?.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,rn?.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,rn?.invalidateMaterialCache(e))},getShader(e){const t=cn.get(e);return t?.shader??0},release(e){cn.delete(e),rn?.invalidateMaterialCache(e)},isValid:e=>cn.has(e),releaseAll(){cn.clear(),rn?.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,_n=new Map;let yn=null;function wn(e){const t=(0===mn&&rn&&(mn=rn._malloc(gn)),mn);if(0===t||!rn)return{ptr:0,count:0};let n=0,s=0;const i=rn.HEAPU8,o=rn.HEAPU32,r=rn.HEAPF32;for(const[a,l]of e){if(on(l))continue;let e=_n.get(a);e||(yn||(yn=new TextEncoder),e=yn.encode(a),_n.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}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 xn(){if(!rn||pn)return;rn.materialDataProvider=(e,t,n,s,i)=>{const o=cn.get(e);if(!o)return rn.HEAPU32[t>>2]=0,rn.HEAPU32[n>>2]=0,rn.HEAPU32[s>>2]=0,void(rn.HEAPU32[i>>2]=0);rn.HEAPU32[t>>2]=o.shader,rn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=wn(o.uniforms);rn.HEAPU32[s>>2]=r,rn.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 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 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),o=await this.shaderLoader_.load(i);return{handle:fn.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 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 An(e){return Tn.get(e)}function Rn(){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 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,De)){const t=i.frames[n.currentFrame],o=e.get(s,De);o.texture=t.texture,e.insert(s,De,o)}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,this.bgmVolume_=1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}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})}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),this.createPendingHandle())}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,this.bgmVolume_):this.bgmHandle_&&this.bgmHandle_.stop();const n=t?.volume??1;this.bgmVolume_=n;const s=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:s?0:n,loop:!0}),s&&this.fadeIn(this.bgmHandle_,s,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else 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 dispose(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}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?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}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,Fn.bgmVolume_=1,Fn.fadeAnimId_=0;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 $n(e){return Bn.get(e)?.fields??[]}function Wn(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 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 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,Ne,{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),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 Xn(e,t){return jn(e,t)}async function Yn(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 Vn.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=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),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=[...Vn.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=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,o,n?.collectAssets);const r=jn(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 Vn=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=Pn(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);En(Mn(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 Fn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),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 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([Ne]);for(const s of n){const n=e.get(s,Ne);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(oe.textCanvasSize,oe.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 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(),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),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"===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,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=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("/")),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 Un(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 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 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 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:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return fn.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(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 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 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),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 Yn(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 ss=10;async function is(e,t,n,s,i,o=0){if(o>ss)throw new Error(`Prefab nesting depth exceeded ${ss}. 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 is(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};os(h.components,r),rs(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 os(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 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 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 _s(){hs&&(ds&&(hs._free(ds),ds=0),fs&&(hs._free(fs),fs=0),ps&&(hs._free(ps),ps=0)),hs=null}function ys(){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=ys();try{t.HEAPF32.set(e,ds/4),t.draw_begin(ds)}catch(e){ft(e,"Draw.begin")}},end(){try{ys().draw_end()}catch(e){ft(e,"Draw.end")}},line(e,t,n,s=1){try{ys().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{ys().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{ys().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{ys().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{ys().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{ys().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{ys().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){ys().draw_setLayer(e)},setDepth(e){ys().draw_setDepth(e)},getDrawCallCount:()=>hs?hs.draw_getDrawCallCount():0,getPrimitiveCount:()=>hs?hs.draw_getPrimitiveCount():0,setBlendMode(e){ys().draw_setBlendMode(e)},setDepthTest(e){ys().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ys();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=ys(),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 o;if(s.HEAPF32.set(n,fs/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=Ss(t);if(!(s<0)){if(on(n))ms[o++]=10,ms[o++]=s,ms[o++]=n.slot??e++,ms[o++]=n.textureId;else if("number"==typeof n)ms[o++]=1,ms[o++]=s,ms[o++]=n;else if(Array.isArray(n)){ms[o++]=n.length,ms[o++]=s;for(let e=0;e<n.length;e++)ms[o++]=n[e]}else"w"in n?(ms[o++]=4,ms[o++]=s,ms[o++]=n.x,ms[o++]=n.y,ms[o++]=n.z,ms[o++]=n.w):"z"in n?(ms[o++]=3,ms[o++]=s,ms[o++]=n.x,ms[o++]=n.y,ms[o++]=n.z):(ms[o++]=2,ms[o++]=s,ms[o++]=n.x,ms[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(ms.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,fs);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),ps/4),s.draw_meshWithUniforms(e,i.shader,fs,ps,o)}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 As=null,Rs=0,Is=0,ks=0;function Fs(e){As=e,Rs=As._malloc(262144),Is=As._malloc(65536),ks=As._malloc(256)}function Bs(){As&&(Rs&&As._free(Rs),Is&&As._free(Is),ks&&As._free(ks),Rs=0,Is=0,ks=0),As=null}function zs(){if(!As)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return As}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,Rs/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,ks,i).set(o),t.geometry_init(n,Rs,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,Rs/4),s.geometry_updateVertices(e,Rs,i,n)},release(e){e>0&&zs().geometry_release(e)},isValid:e=>!(!As||e<=0)&&As.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,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 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 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 Us.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Cs.Float2},{name:"a_texCoord",type:Cs.Float2}],indices:new Uint16Array(r)})}};let $s=null;function Ws(e){$s=e}function Ds(){$s&&Ls.isInitialized()&&Ls.shutdown(),$s=null}function Os(){if(!$s)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return $s}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(!$s)return!1;try{return $s.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(!$s)return!0;try{return $s.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 Vs(e){Xs=e,Ys=Xs._malloc(64)}function Ns(){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:o}=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,o):Gs.submitSpine(t),Gs.flush(),this.executeDrawCallbacks(n,o),Gs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o}=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,o):Gs.submitSpine(t),Gs.flush(),this.executeDrawCallbacks(n,o),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??oe.sceneTransitionDuration,i=t.color??{...oe.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 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(Jn)&&(i.assetServer=this.app_.getResource(Jn));const o=await Yn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.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=oi(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,Ve)){const t=n.get(e,Ve);s.spine=t.color.a,t.color.a=0,n.insert(e,Ve,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,Ve)){const t=n.get(e,Ve);t.color.a=s.spine,n.insert(e,Ve,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 oi(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 ri=Vt([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,ri)}};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 Wt,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 rt;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,Ns,Ds,Bs,hn,_s];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(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 o=e*t/n,r=e;switch(s){case ze.FixedWidth:return o;case ze.FixedHeight:return r;case ze.Expand:return Math.max(o,r);case ze.Shrink:return Math.min(o,r);case ze.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}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,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,Ge);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===Fe.Orthographic){if(h=i.orthoSize,l){h=hi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=gi(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=yi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=xi(o.position.x,o.position.y,o.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=o.position.x,f.cameraY=o.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,o){const r=mi;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 _i=new Float32Array(16);function yi(e,t,n,s){const i=_i;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 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,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 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 Ai(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 Ri(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),o=Ai(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,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 o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Bi(r.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)+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 Ui(e){let t=1;for(;t<e;)t*=2;return t}function $i(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(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,o){if(!e.has(t,De))return;const r=e.get(t,De);let a,l;switch(n){case Si.BottomToTop:case Si.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,De,r))}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 o=e.get(t,Mi),r=Pi(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,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=r.originX-s,n.position.y=r.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,Vi=30,Ni={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(oe.textCanvasSize,oe.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,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=zi(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===Ki.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,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),_=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===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?Wi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0});class eo{build(e){Re("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,Vt([],()=>{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),o=s.has(t,Mi)?s.get(t,Mi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Zi.changed(a,r)){if(s.has(t,De)&&s.get(t,De).texture!==ue)continue}Ci(s,t);const l=o?{size:{x:Wi(o,t),y:Di(o,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(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const to=new eo,no=0,so=1,io=ke("UIMask",{enabled:!0,mode:no});function oo(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 ro(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,P=o*u-r*c,M=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,A=d*y-p*g,R=f*y-p*_;let I=w*R-x*A+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*C)*I,n[1]=(o*A-i*R-r*C)*I,n[2]=(g*P-_*S+y*b)*I,n[3]=(f*S-d*P-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+r*T)*I,n[6]=(_*v-m*P-y*x)*I,n[7]=(h*P-f*v+p*x)*I,n[8]=(a*A-l*E+u*M)*I,n[9]=(i*E-s*A-r*M)*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*M)*I,n[13]=(s*C-i*T+o*M)*I,n[14]=(g*x-m*b-_*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function ao(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 lo(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 co(e,t){return 2*Math.atan2(e,t)}function uo(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 ho(e,t,n,s,i,o,r,a,l,c){const u=co(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 fo(e,t,n,s,i,o,r){if(!e.has(t,Mi)||!e.has(t,Ue))return null;const a=e.get(t,Mi),l=e.get(t,Ue),c=Wi(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),_=-u*p,y=u*(1-p),w=co(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,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=uo(e,t,n,s,i,o,r);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 po(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([io]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const n=t.get(e,io);n.enabled&&(h.add(e),n.mode===so?(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;Li(t,e,e=>{if(i.has(e)){if(t.get(e,io).mode===no)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,io).mode===no){const e=fo(t,n,o,r,a,l,c);e&&(s=oo(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of u){const n=fo(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;Li(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 mo{build(e){if(Re("UIMask",io),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(po(e.wasmModule,e.world))}}const go=new mo,_o=ke("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),yo=ke("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),wo={Normal:0,Hovered:1,Pressed:2,Disabled:3},xo=be("Button",{state:wo.Normal,transition:null});class vo{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 bo=nt(new vo,"UIEvents");class So{build(e){Re("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,Vt([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,Vt([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,Vt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Po=new So;let Mo=!1,To=!1;function Eo(e){Mo=e}function Co(){return Mo}function Ao(){return!Mo}function Ro(e){To=e}function Io(){return To}const ko=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&&(ro(t,e),n=!1),e)}}();function Fo(e,t,n,s){t.emit(n,s,n),Li(e,n,i=>{if(!e.has(i,_o))return!1;const o=e.get(i,_o);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Bo{build(e){Re("Interactable",_o),Re("Button",xo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new vo;e.insertResource(bo,i);let o=null,r=null;e.addSystemToSchedule(jt.PreUpdate,Vt([st(Zt),st(nn)],(e,a)=>{if(i.drain(),Co()&&!Io())return;const l=t.getEntitiesWithComponents([yo]);for(const e of l){const n=t.get(e,yo);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,yo,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;ko.update(a.viewProjection);const d=ao(u,h,ko.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,yo)){const e=t.get(o,yo);e.hovered=!1,t.insert(o,yo,e),i.emit(o,"hover_exit")}if(null!==y){Hi(t,y,yo);const e=t.get(y,yo);e.hovered=!0,t.insert(y,yo,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,yo);e.pressed=!0,e.justPressed=!0,t.insert(y,yo,e),r=y,Fo(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,yo)){const e=t.get(r,yo);e.pressed=!1,e.justReleased=!0,t.insert(r,yo,e),Fo(t,i,r,"release"),r===o&&Fo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(jt.Update,Vt([],()=>{const e=t.getEntitiesWithComponents([xo]);for(const n of e){if(Hi(t,n,_o,{enabled:!0}),!t.has(n,yo))continue;const e=t.get(n,yo),s=t.get(n,xo),i=t.get(n,_o),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=wo.Pressed:e.hovered?s.state=wo.Hovered:s.state=wo.Normal:s.state=wo.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,De)){const o=t.get(n,De);o.color=Fi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,De,o)}}},{name:"ButtonSystem"}))}}const zo=new Bo,Uo=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}),$o=be("Focusable",{tabIndex:0,isFocused:!1});class Wo{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 Do=nt(new Wo,"FocusManager");class Oo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Re("TextInput",Uo),Co()&&!Io())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(oe.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(Do);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Uo)?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,Uo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(bo).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,Uo);s.focused=!1,s.dirty=!0;e.getResource(Do).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,Uo);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(bo).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,Uo);e.focused=!1,e.dirty=!0}e.getResource(Do).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 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))),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=zi(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=zi(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,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,Vt([st(Do)],e=>{const t=n.getEntitiesWithComponents([Uo]);for(const e of t)Hi(n,e,$o,{tabIndex:0,isFocused:!1}),Hi(n,e,_o,{enabled:!0,blockRaycast:!0});const s=m();if(s!==P){if(null!==P&&n.valid(P)&&n.has(P,Uo)){const e=n.get(P,Uo);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Uo);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,Vt([],()=>{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,Uo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Uo)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Uo,Mi]);for(const e of a){const t=n.get(e,Uo);if(!t.dirty)continue;const s=n.get(e,Mi),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Ci(n,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Lo=new Oo,Ho={Simple:0,Sliced:1,Tiled:2,Filled:3},jo={Horizontal:0,Vertical:1},Xo={Left:0,Right:1,Bottom:2,Top:3},Yo=be("Image",{texture:ue,color:{r:1,g:1,b:1,a:1},imageType:Ho.Simple,fillMethod:jo.Horizontal,fillOrigin:Xo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Vo=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?Wi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const No=new class{build(e){Re("Image",Yo);const t=e.world,n=new Map;e.addSystemToSchedule(jt.PreUpdate,Vt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Yo)||n.delete(e);const e=t.getEntitiesWithComponents([Yo]);for(const s of e){const e=t.get(s,Yo),i=t.has(s,Mi)?t.get(s,Mi):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Vo.changed(r,o))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=Wi(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===Ho.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===jo.Horizontal?e.fillOrigin===Xo.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===Xo.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===Ho.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,Vo.take(o))}else a.color.a=0,t.insert(s,De,a),n.set(s,Vo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Go=be("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),qo=be("ToggleGroup",{allowSwitchOff:!1});const Ko=new class{build(e){Re("Toggle",Go),Re("ToggleGroup",qo);const t=e.world,n=new Set;e.addSystemToSchedule(jt.Update,Vt([st(bo)],e=>{const s=t.getEntitiesWithComponents([Go]);if(!Co()||Io()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Go);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Go,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Go);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(Hi(t,n,_o,{enabled:!0}),!t.has(n,yo))continue;const s=t.get(n,yo),i=t.get(n,Go),r=t.get(n,_o);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,qo);if(i.isOn&&r){if(!t.get(s,qo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Go,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,Go);i.isOn&&(i.isOn=!1,t.insert(s,Go,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,r.enabled,s.pressed,s.hovered),t.insert(n,De,e)}}}for(const e of s){const n=t.get(e,Go);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"]})}},Jo=Si,Qo=be("ProgressBar",{value:0,fillEntity:0,direction:Si.LeftToRight});function Zo(e,t,n,s){if(!e.has(t,Mi))return;const i=e.get(t,Mi),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},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 er{build(e){Re("ProgressBar",Qo);const t=e.world;e.addSystemToSchedule(jt.PreUpdate,Vt([],()=>{const e=t.getEntitiesWithComponents([Qo,Mi]);for(const n of e){const e=t.get(n,Qo);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 o=Wi(s,n),r=Di(s,n);Zo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const tr=new er,nr=be("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),sr=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 ir=new class{build(e){Re("Draggable",nr),Re("DragState",sr);const t=e.world,n=e.getResource(bo);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(jt.PreUpdate,Vt([st(Zt),st(nn)],(e,r)=>{if(Co()&&!Io())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([nr,yo]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,nr).enabled)continue;if(t.get(s,yo).hovered){let e=0;t.has(s,De)&&(e=t.get(s,De).layer);const i=$i(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,sr)||t.insert(n,sr);const e=t.get(n,sr),o=t.get(n,Ue);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,sr)){t.get(s,sr).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,nr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,sr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,sr))return void(o=null);const s=t.get(o,sr),i=t.get(o,nr),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,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 o=e.get(i,Ue),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=co(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,Ue);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,Ue,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},or=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 rr(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 ar(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 lr=new class{build(e){Re("ScrollView",or);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(jt.PostUpdate,Vt([st(Zt),st(nn),st(at)],(e,i,o)=>{const r=Co()&&!Io(),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([or,Mi]);for(const o of l){Hi(t,o,io,{enabled:!0,mode:no});const l=t.get(o,or),c=t.get(o,Mi);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=Wi(c,o),d=Di(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,Xe)){const e=t.get(l.contentEntity,Xe).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,Ue))continue;const e=t.get(r,Ue);let a=0,l=0,c=.5,u=.5;if(t.has(r,Mi)){const e=t.get(r,Mi);a=Wi(e,r)||e.size.x,l=Di(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,De)){const e=t.get(r,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>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){Hi(t,o,_o,{enabled:!0,blockRaycast:!0});const n=t.has(o,yo)?t.get(o,yo):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=rr(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=rr(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=rr(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=rr(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=ar(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=ar(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"]})}},cr=Si,ur=be("Slider",{value:0,minValue:0,maxValue:1,direction:Si.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function hr(e,t,n,s,i,o){const r=Wi(s,i)*n.worldScale.x,a=Di(s,i)*n.worldScale.y,l=co(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 Si.LeftToRight:return r>0?(f-m)/r:0;case Si.RightToLeft:return r>0?1-(f-m)/r:0;case Si.BottomToTop:return a>0?(p-g)/a:0;case Si.TopToBottom:return a>0?1-(p-g)/a:0}}function dr(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 fr{build(e){Re("Slider",ur);const t=e.world;let n=null;e.addSystemToSchedule(jt.PreUpdate,Vt([st(Zt),st(nn),st(bo)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([ur,Mi]);for(const r of o){const o=t.get(r,ur),a=t.get(r,Mi);if(!Co()||Io()){if(t.has(r,Ue)){Hi(t,r,_o,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Hi(t,o.handleEntity,_o,{enabled:!0,blockRaycast:!1});const l=t.get(r,Ue),c=t.has(r,yo)?t.get(r,yo):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,yo)&&(u=t.get(o.handleEntity,yo).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=hr(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,ur,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=Wi(a,r),h=Di(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(ki(t,o.fillEntity,o.direction,c),ji(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Mi)){const e=t.get(o.handleEntity,Mi);dr(e,o.direction,c),t.insert(o.handleEntity,Mi,e),ji(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const pr=new fr;const mr=new class{build(e){Re("Focusable",$o);const t=e.world,n=new Wo;e.insertResource(Do,n),e.addSystemToSchedule(jt.Update,Vt([st(Zt),st(bo)],(e,s)=>{if(Co()&&!Io())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([$o]);for(const e of i){if(!t.has(e,yo))continue;t.get(e,yo).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,_o)){if(!t.get(n,_o).enabled)continue}const s=t.get(n,$o);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,$o)){t.get(i,$o).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,$o).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},gr=be("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function _r(){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 yr=new class{build(e){Re("SafeArea",gr);const t=e.world;let n=_r(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=_r(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=_r(),s=!0});e.addSystemToSchedule(jt.PreUpdate,Vt([st(nn)],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([gr,Mi]);for(const e of u){const s=t.get(e,gr),i=t.get(e,Mi),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,Mi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},wr=be("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let xr=null;function vr(e,t){if(!xr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=xr.get(e);n?n.renderer=t:xr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const br=new class{build(e){Re("ListView",wr);const t=e.world,n=new Map;xr=n,e.addSystemToSchedule(jt.PostUpdate,Vt([st(Zt)],e=>{const s=Co()&&!Io();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([wr,Mi]);for(const o of i){Hi(t,o,_o,{enabled:!0,blockRaycast:!0}),Hi(t,o,io,{enabled:!0,mode:no});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,wr),a=t.get(o,Mi),l=Di(a,o),c=Wi(a,o);if(!s){const n=t.has(o,yo)?t.get(o,yo):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,Ne,{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: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,Ue)){const s=t.get(n,Ue);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,Ue,s)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Sr=be("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Pr=new class{build(e){Re("Dropdown",Sr);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 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,De),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Vi;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:r,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: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)*Vi;t.insert(o,Ne,{value:`Option_${e}`}),t.insert(o,Mi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Vi},offsetMax:{x:0,y:0},size:{x:r,y:Vi},pivot:{x:.5,y:.5}}),t.insert(o,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(o,De,{texture:ue,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Vi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,_o,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);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:r,y:Vi},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,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},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,Ji,{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,_o)&&t.insert(e,_o,{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?{...Ni}:{r:.95,g:.95,b:.95,a:1};t.insert(s,De,{texture:ue,color:i,size:{x:e.ddWidth,y:Vi},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,yo))continue;if(t.get(n,yo).hovered)return!0}return!1}e.addSystemToSchedule(jt.Update,Vt([st(Zt),st(bo)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=Co()&&!Io(),p=t.getEntitiesWithComponents([Sr]);for(const m of p){const p=t.get(m,Sr);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,_o,{enabled:!0,blockRaycast:!0});const _=t.has(m,yo)?t.get(m,yo):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,yo))continue;if(t.get(n,yo).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,yo))continue;if(t.get(s,yo).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"]})}},Mr=0,Tr=0,Er=2,Cr=be("LayoutGroup",{direction:Mr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Tr,reverseOrder:!1});const Ar=new class{build(e){Re("LayoutGroup",Cr);const t=e.world;e.addSystemToSchedule(jt.PreUpdate,Vt([],()=>{const e=t.getEntitiesWithComponents([Cr,Mi,Xe]);for(const n of e){const e=t.get(n,Cr),s=t.get(n,Mi),i=t.get(n,Xe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Mi)&&t.has(e,Ue)&&o.push({entity:e,rect:t.get(e,Mi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Wi(s,n),a=Di(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,h=e.direction===Mr;let d=0;for(let n=0;n<o.length;n++){const s=o[n],i=Wi(s.rect,s.entity),f=Di(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===Tr?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Er?-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===Tr?-l*r+u.left+p*i:e.childAlignment===Er?(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,Ue);y.position.x=g,y.position.y=_,t.insert(s.entity,Ue,y)}}},{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 Rr{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(jt.PostUpdate,Vt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Ir=new Rr;async function kr(e,t,n){const s=e.getResource(ii);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Fr(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 Br=nt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),zr=nt(null,"PhysicsAPI");function Ur(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function $r(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Wr{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(Br,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Fr(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),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(jt.PostUpdate,Vt([st(at)],a=>{const l=r.getEntitiesWithComponents([Ke,Ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Ke),l=r.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 r=Ur(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),Dr(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=Ur(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,Ue);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,je)){const t=e.world.get(r,je);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Ue)){const n=e.world.get(t.entity,Ue),s=Ur(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=$r(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,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 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(Br,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(zr,Or._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Dr(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 Or{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(Or.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 Lr={nearest:0,linear:1},Hr={repeat:0,clamp:1,mirror:2};function jr(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=Lr[s.filterMode??"linear"]??1,a=Hr[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 Xr(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 Yr(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 Vr(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=$n(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]=jr(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=Wn(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"===v(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=Xr(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=jr(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??{...ne},fixedTimestep:r?.fixedTimestep??se,subStepCount:r?.subStepCount??4};new Wr("",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=$n(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=v(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=jr(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=$n(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=fn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=fn.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=$n(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 o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=Wn(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=te);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Ve)?c.get(o,Ve):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&s.update(r,l*h);let d=0;if(c.has(o,Ue)){const e=Yr(c.get(o,Ue),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(Jn);t&&t.setAddressableManifest(a)}}function Nr(e,t,n){return{name:e,async setup(){await Vr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Gr{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],o=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=$n(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=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)||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 qr="__preview__";class Kr{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:qr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(qr),this.loadPromise_=t.load(qr).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 Gr(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Vr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,qr)}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(qr),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,Ue,r);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(o,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(qr),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 Jr={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),Jr.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 Qr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Qr||(Qr={}));class Zr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Qr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Qr.Debug:console.debug(t,n);break;case Qr.Info:console.log(t,n);break;case Qr.Warn:console.warn(t,n);break;case Qr.Error:console.error(t,n)}}}class ea{constructor(){this.handlers_=[],this.minLevel_=Qr.Info,this.addHandler(new Zr)}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(Qr.Debug,e,t,n)}info(e,t,n){this.log(Qr.Info,e,t,n)}warn(e,t,n){this.log(Qr.Warn,e,t,n)}error(e,t,n){this.log(Qr.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 oa(e,t,n){ta.info(e,t,n)}function ra(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 _a(){if(!fa)throw new Error("Tween API not initialized");return fa}function ya(){if(!pa)throw new Error("Tween API not initialized");return pa}const wa={to(e,t,n,s,i,o){const r=_a(),a=ya(),l=o?.easing??la.Linear,c=o?.delay??0,u=o?.loop??ha.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,n,s,i,l,c,u,h);return new da(r,a,d)},cancel(e){_a()._anim_cancelTween(ya(),e.entity)},cancelAll(e){_a()._anim_cancelAllTweens(ya(),e)},update(e){_a()._anim_updateTweens(ya(),e)}};class xa{constructor(){this.name="AnimationPlugin"}build(e){ma(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(jt.Update,Vt([st(at)],e=>{wa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(jt.Update,Vt([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_=Math.max(0,Math.min(1,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.activeCount_=0,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,this.activeCount_++,t}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0,this.activeCount_--}}get activeCount(){return this.activeCount_}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:o}=t,r=Math.max(e,.001);switch(n){case Ma.Linear:{const e=i-s;if(e<=0)return 1;return 1-(Math.min(Math.max(r,s),i)-s)/e}case Ma.Inverse:return s/Math.max(r,s);case Ma.Exponential:return Math.pow(Math.max(r,s)/s,-o);default:return 1}}function Ca(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Aa=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}),Ra=be("AudioListener",{enabled:!0});class Ia{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}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,this.resumeHandler_=null}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),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}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);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new Ia(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),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 o=new Fa(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 za(){return i()?new Ba:new ka}class Ua{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const t=za(),n=this.config_;t instanceof ka?t.initialize({initialPoolSize:n.initialPoolSize}):t.initialize();let s=null;t instanceof ka&&(s=t.mixer),Fn.init(t,s),s&&(void 0!==n.masterVolume&&(s.master.volume=n.masterVolume),void 0!==n.musicVolume&&(s.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(s.sfx.volume=n.sfxVolume));const i=new Map;e.addSystemToSchedule(jt.PreUpdate,Vt([st(at)],n=>{const s=e.world;let o=0,r=0;const a=s.getEntitiesWithComponents([Ra,We]);for(const e of a){if(s.get(e,Ra).enabled){const t=s.get(e,We);o=t.position.x,r=t.position.y;break}}const l=s.getEntitiesWithComponents([Aa,We]),c=new Set;for(const e of l){const n=s.get(e,Aa);if(!n.enabled||!n.clip)continue;c.add(e);const a=s.get(e,We);if(n.playOnAwake&&!i.has(e)){const s=Fn.getBufferHandle(n.clip);if(s){const o=t.play(s,{bus:n.bus,volume:n.volume,loop:n.loop,playbackRate:n.pitch,priority:n.priority});i.set(e,o)}else console.warn(`[AudioPlugin] playOnAwake: clip "${n.clip}" not preloaded`)}if(n.spatial&&i.has(e)){const t=i.get(e);if(!t.isPlaying){i.delete(e);continue}const s=a.position.x-o,l=a.position.y-r,c=Ea(Math.sqrt(s*s+l*l),{model:n.attenuationModel,refDistance:n.minDistance,maxDistance:n.maxDistance,rolloff:n.rolloff}),u=Ca(a.position.x,a.position.y,o,0,n.maxDistance);t.setVolume(n.volume*c),t.setPan(u)}}for(const[e,t]of i)c.has(e)&&t.isPlaying||i.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){Fn.dispose()}}const $a=new Ua;class Wa{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:o}=e,r=t.getResource(Jn);r&&(r.registerEmbeddedAssets(s),r.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=Nr(o,i,{app:t,module:n,provider:new Wa(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),u=t.getResource(ii);u.register(c),u.setInitial(o),await u.load(o);const h=e.canvas.width/e.canvas.height;Gn(t.world,h),t.run()}const La=[to,go,Po,No,tr,zo,ir,lr,pr,Ko,Lo,mr,yr,br,Pr,Ar,Ir],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),Ws(e),Vs(e),Ks(e);const i=new Zs;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=pi(e,s,t,i));const r=n.getResource(nn);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(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}=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;Gs.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/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,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})}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 Va(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 Na(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),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:Ya("esengine.wasm")}),c=o.getContext("webgl2")||o.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:o.width,height:o.height})});e.runtimeConfig&&le(h,e.runtimeConfig),ci(h);let d=null;e.spineFactory&&(d=await Va(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Va(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(Nr(t,n,p))}e.firstScene&&(m.setInitial(e.firstScene),await m.load(e.firstScene));const g=o.width/o.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,Ra as AudioListener,Sa as AudioMixer,Ua as AudioPlugin,Pa as AudioPool,Aa as AudioSource,Ye as BitmapText,sn as BlendMode,et as BodyType,Je as BoxCollider,xo as Button,wo 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,N as DEFAULT_DESIGN_HEIGHT,V 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,sr as DragState,nr as Draggable,xs as Draw,Sr as Dropdown,la as EasingType,Bt as EntityCommands,Ot as EventReader,Ht as EventReaderInstance,Wt as EventRegistry,Dt as EventWriter,Lt as EventWriterInstance,Si as FillDirection,jo as FillMethod,Xo as FillOrigin,Do as FocusManager,Wo as FocusManagerState,$o 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,Yo as Image,Ho as ImageType,Zt as Input,en as InputPlugin,Qt as InputState,_o as Interactable,wr as ListView,$e as LocalTransform,Qr as LogLevel,ea as Logger,ha as LoopMode,fn as Material,Sn as MaterialLoader,vt as Mut,Ne as Name,je as Parent,Or as Physics,Br as PhysicsEvents,Wr as PhysicsPlugin,Ls as PostProcess,as as PrefabServer,ls as Prefabs,cs as PrefabsPlugin,Kr as PreviewPlugin,Qo as ProgressBar,Jo as ProgressBarDirection,er as ProgressBarPlugin,Fe as ProjectionType,At as Query,Rt as QueryInstance,It as Removed,kt as RemovedQueryInstance,Zs as RenderPipeline,js as RenderStage,Jr as RenderTexture,Gs as Renderer,st as Res,it as ResMut,Ke as RigidBody,oe as RuntimeConfig,gr as SafeArea,ze as ScaleMode,ii as SceneManager,si as SceneManagerState,Ge as SceneOwner,jt as Schedule,or as ScrollView,vn as ShaderSources,ur as Slider,cr as SliderDirection,fr as SliderPlugin,Ve as SpineAnimation,De as Sprite,In as SpriteAnimator,Jt as SystemRunner,Ji as Text,Gi as TextAlign,Uo as TextInput,Oo as TextInputPlugin,Ki as TextOverflow,eo as TextPlugin,Qi as TextRenderer,qi as TextVerticalAlign,at as Time,Go as Toggle,Ue as Transform,wa as Tween,da as TweenHandle,ua as TweenState,ca as TweenTarget,nn as UICameraInfo,vo as UIEventQueue,bo as UIEvents,yo as UIInteraction,Bo as UIInteractionPlugin,So as UILayoutPlugin,io as UIMask,mo as UIMaskPlugin,Mi as UIRect,Rr as UIRenderOrderPlugin,He as Velocity,Xa as WeChatAssetProvider,Gr as WebAssetProvider,xt as World,We as WorldTransform,qt as addStartupSystem,Gt as addSystem,Kt as addSystemToSchedule,va as animationPlugin,le as applyBuildRuntimeConfig,ki as applyDirectionalFill,re as applyRuntimeConfig,Zn as assetPlugin,$a as audioPlugin,Ea as calculateAttenuation,Ca as calculatePanning,Rn as clearAnimClips,Es as clearDrawCallbacks,Me as clearUserComponents,ge as color,Ai as computeFillAnchors,Ii as computeFillSize,Ri as computeHandleAnchors,Pi as computeUIRectLayout,za as createAudioBackend,po as createMaskProcessor,Nr as createRuntimeSceneConfig,ja as createWebApp,ia as debug,be as defineComponent,Ut as defineEvent,nt as defineResource,Vt 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,An as getAnimClip,R as getAssetMimeType,v as getAssetTypeEntry,Ie as getComponent,$n as getComponentAssetFieldDescriptors,Un as getComponentAssetFields,qe as getComponentDefaults,Ln as getComponentEntityFields,Wn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,na as getLogger,t as getPlatform,s as getPlatformType,Pe as getUserComponent,A as getWeChatPackOptions,oa as info,gs as initDrawAPI,Ks as initGLDebugAPI,Fs as initGeometryAPI,un as initMaterialAPI,Oa as initPlayableRuntime,Ws as initPostProcessAPI,Vs as initRendererAPI,ma as initTweenAPI,Na as initWeChatRuntime,tn as inputPlugin,ns as instantiatePrefab,oo as intersectRects,ro as invertMatrix4,Ce as isBuiltinComponent,I as isCustomExtension,Co as isEditor,M as isKnownAssetExtension,n as isPlatformInitialized,Io as isPlayMode,Ao as isRuntime,on as isTextureRef,i as isWeChat,o as isWeb,Nn as loadComponent,Fr as loadPhysicsModule,Vr as loadRuntimeScene,Xn as loadSceneData,Yn as loadSceneWithAssets,E as looksLikeAssetPath,Mn as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,ho as pointInOBB,lo as pointInWorldRect,us as prefabsPlugin,tr as progressBarPlugin,_e as quat,En as registerAnimClip,Re as registerComponent,zn as registerComponentAssetFields,On as registerComponentEntityFields,Ms as registerDrawCallback,ts as registerEmbeddedAssets,xn as registerMaterialCallback,Hn as remapEntityFields,ai as sceneManagerPlugin,ao as screenToWorld,Eo as setEditorMode,vr as setListViewRenderer,sa as setLogLevel,Ro as setPlayMode,dt as setWasmErrorHandler,_s as shutdownDrawAPI,Js as shutdownGLDebugAPI,Bs as shutdownGeometryAPI,hn as shutdownMaterialAPI,Ds as shutdownPostProcessAPI,Ns as shutdownRendererAPI,ga as shutdownTweenAPI,pr as sliderPlugin,kn as spriteAnimatorSystemUpdate,Oi as syncFillSpriteSize,Lo as textInputPlugin,to as textPlugin,k as toBuildPath,kr as transitionTo,zo as uiInteractionPlugin,Po as uiLayoutPlugin,go as uiMaskPlugin,La as uiPlugins,Ir as uiRenderOrderPlugin,Cn as unregisterAnimClip,Te as unregisterComponent,Ts as unregisterDrawCallback,Gn as updateCameraAspectRatio,fe as vec2,pe as vec3,me as vec4,ra as warn,oi as wrapSceneSystem,W as wxFileExists,D as wxFileExistsSync,H as wxGetImagePixels,L as wxLoadImage,j as wxLoadImagePixels,U as wxReadFile,$ 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 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 d(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}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,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 p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(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 p(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 g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,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,this.activeCount_++,t}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class y{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 _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}async initialize(e){}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 y(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 w(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 x(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 v=[{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}],b={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"},S=new Map,M=new Set;for(const e of v)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function E(e){return T(e)?.editorType??"unknown"}function C(e){return T(e)?.addressableType??null}function A(e){for(const t of v)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function F(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function k(){const e=[];for(const t of v)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return k().map(e=>({type:"suffix",value:e}))}function z(e){return b[e.toLowerCase()]}function $(e){const t=T(e);return t?.wechatPackInclude??!1}function U(e){const t=T(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 W=null;function D(){return W||(W=wx.getFileSystemManager()),W}function O(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if($(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 L(e){return new Promise((t,n)=>{D().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(O(e,t.errMsg)))}})})}function H(e,t="utf-8"){return new Promise((n,s)=>{D().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(O(e,t.errMsg)))}})})}function j(e){return new Promise(t=>{D().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=D();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{D().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function V(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 N(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 G(e){return N(await V(e))}let q=!1;const K=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return D().readFileSync(e)}(U(e))}async readTextFile(e){return function(e,t="utf-8"){return D().readFileSync(e,t)}(U(e))}async fileExists(e){return X(U(e))}async loadImagePixels(e){return G(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(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 o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=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(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}},J=1920,Q=1080,Z=100,ee=512,te={x:100,y:100},ne="Arial",se=24,ie=1.2,oe=.5,re=1/60,ae={x:0,y:-9.81},le=1/60,ce="default",ue={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function de(e){e.Text&&(e.Text._default.fontFamily=ue.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=ue.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=ue.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=ue.canvasMatchWidthOrHeight)}const he={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function fe(e,t){if(void 0!==t.maxDeltaTime&&(ue.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(ue.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(ue.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(ue.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(ue.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");ue.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&&(ue.canvasScaleMode=he[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(ue.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const pe=0,me=4294967295,ge=4294967295,ye=0,_e=(e=0,t=0)=>({x:e,y:t}),we=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),xe=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),ve=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),be=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function Se(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Se);const t={};for(const n in e)t[n]=Se(e[n]);return t}let Me=0;function Pe(e,t){const n=++Me,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?{...Se(t),...e}:Se(t):e?{...t,...e}:{...t}}}function Te(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ee(e,t){const n=Be.get(e)??Te().get(e);if(n)return n;const s=Pe(e,t);return Te().set(e,s),Be.set(e,s),Fe(e,t,!1),s}function Ce(e){const t=Be.get(e)??Te().get(e);if(t)return t;const n=Pe(e,{});return Te().set(e,n),Be.set(e,n),Fe(e,{},!0),n}function Ae(e){return Te().get(e)}function Re(){const e=Te();for(const t of e.keys())Be.delete(t);e.clear()}function Ie(e){Te().delete(e),Be.delete(e)}function Fe(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ke(e){return!0===e._builtin}const Be=new Map;function ze(e,t){Be.set(e,t)}function $e(e){return Be.get(e)??Ae(e)}function Ue(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Be.set(e,n),n}const We={Perspective:0,Orthographic:1},De={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Oe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Le=Ue("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}}),He=Le,je=Le,Xe=Ue("Sprite",{texture:me,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}),Ye=Ue("Camera",{projectionType:We.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:De.ColorAndDepth}),Ve=Ue("Canvas",{designResolution:{x:J,y:Q},pixelsPerUnit:100,scaleMode:Oe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ne=Ue("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ge=Ue("Parent",{entity:0}),qe=Ue("Children",{entities:[]}),Ke=Ue("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:ge,enabled:!0}),Je=Ue("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}),Qe=Ee("Name",{value:""}),Ze=Ee("SceneOwner",{scene:"",persistent:!1});function et(e){const t=$e(e);return t?Se(t._default):null}const tt=Ue("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),nt=Ue("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),st=Ue("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),it=Ue("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ot={Static:0,Kinematic:1,Dynamic:2};let rt=0;function at(e,t){const n=++rt;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function lt(e){return{_type:"res",_resource:e}}function ct(e){return{_type:"res_mut",_resource:e}}class ut{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 dt{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 ut(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ht=at({delta:0,elapsed:0,frameCount:0},"Time");function ft(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=pt(t[e]),o=pt(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function pt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function mt(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 gt=null;function yt(e){gt=e}function _t(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),gt&&gt(e,t)}function wt(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 xt=1;const vt=new WeakMap;function bt(e){let t=vt.get(e);return void 0===t&&(t=xt++,vt.set(e,t)),t}const St=[];function Mt(e,t=[],n=[]){St.length=0;for(const t of e)St.push(bt(t));St.sort((e,t)=>e-t);let s=St.join(",");if(t.length>0){St.length=0;for(const e of t)St.push(bt(e));St.sort((e,t)=>e-t),s+="|+"+St.join(",")}if(n.length>0){St.length=0;for(const e of n)St.push(bt(e));St.sort((e,t)=>e-t),s+="|-"+St.join(",")}return s}class Pt{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 _t(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){_t(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){_t(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){_t(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ke(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ke(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,wt(n))}catch(n){_t(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 ke(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ke(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ke(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return _t(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.");ke(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=ft(t._name,t._default,s);if(e.length>0)throw new Error(mt(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,wt(i))}catch(n){_t(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 _t(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 _t(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){_t(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=ft(t._name,t._default,e);if(i.length>0)throw new Error(mt(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 Be)if(ke(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=Te();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??Mt(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(!ke(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 Tt(e){return{_type:"mut",_component:e}}function Et(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ct(e){return{_filterType:"added",_component:e}}function At(e){return{_filterType:"changed",_component:e}}function Rt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function It(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ft(e){return Et(e)||Rt(e)||It(e)?e._component:e}function kt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Et(e)&&s.push(t),Rt(e)?i.push({index:t,component:e._component}):It(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>kt(e,[...t,...s],n),without:(...s)=>kt(e,t,[...n,...s])}}function Bt(...e){return kt(e)}class zt{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Ft),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_=Mt(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 $t(e){return{_type:"removed",_component:e}}class Ut{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 Wt(){return{_type:"commands"}}class Dt{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=ke(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 Ot{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Dt(this,null);return this.spawned_.push(e),e}entity(e){return new Dt(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 Lt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Ht{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 jt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ht)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ht,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Xt(e){return{_type:"event_writer",_event:e}}function Yt(e){return{_type:"event_reader",_event:e}}class Vt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Nt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Gt;function qt(){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"}(Gt||(Gt={}));let Kt=0;function Jt(e,t,n){const s=++Kt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Qt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Zt(e){Qt().push({schedule:Gt.Update,system:e})}function en(e){Qt().push({schedule:Gt.Startup,system:e})}function tn(e,t){Qt().push({schedule:e,system:t})}class nn{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}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]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Ot&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new zt(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 Ot(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 Vt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Nt(n)}case"removed":{const t=e;return new Ut(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class sn{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 on=at(new sn,"Input");class rn{constructor(e){this.target_=e??null}build(e){const n=new sn;e.insertResource(on,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(Gt.Last,Jt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const an=new rn,ln=at({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 cn;function un(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"}(cn||(cn={}));let dn=null,hn=null,fn=1;const pn=new Map;function mn(e){dn=e,hn=e.getResourceManager(),Pn()}function gn(){0!==xn&&dn&&(dn._free(xn),xn=0),pn.clear(),fn=1,wn=!1,bn.clear(),Sn=null,hn=null,dn=null}function yn(){if(!hn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return hn}const _n={createShader:(e,t)=>yn().createShader(e,t),releaseShader(e){e>0&&yn().releaseShader(e)},create(e){const t=fn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??cn.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 pn.set(t,n),t},get:e=>pn.get(e),setUniform(e,t,n){const s=pn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,dn?.invalidateMaterialCache(e))},getUniform(e,t){const n=pn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=pn.get(e);n&&(n.blendMode=t,dn?.invalidateMaterialCache(e))},getBlendMode(e){const t=pn.get(e);return t?.blendMode??cn.Normal},setDepthTest(e,t){const n=pn.get(e);n&&(n.depthTest=t,dn?.invalidateMaterialCache(e))},getShader(e){const t=pn.get(e);return t?.shader??0},release(e){pn.delete(e),dn?.invalidateMaterialCache(e)},isValid:e=>pn.has(e),releaseAll(){pn.clear(),dn?.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??cn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=pn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=fn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return pn.set(n,s),n},toAssetData(e,t){const n=pn.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=pn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let wn=!1,xn=0;const vn=16384,bn=new Map;let Sn=null;function Mn(e){const t=(0===xn&&dn&&(xn=dn._malloc(vn)),xn);if(0===t||!dn)return{ptr:0,count:0};let n=0,s=0;const i=dn.HEAPU8,o=dn.HEAPU32,r=dn.HEAPF32;for(const[a,l]of e){if(un(l))continue;let e=bn.get(a);e||(Sn||(Sn=new TextEncoder),e=Sn.encode(a),bn.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>vn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${vn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Pn(){if(!dn||wn)return;dn.materialDataProvider=(e,t,n,s,i)=>{const o=pn.get(e);if(!o)return dn.HEAPU32[t>>2]=0,dn.HEAPU32[n>>2]=0,dn.HEAPU32[s>>2]=0,void(dn.HEAPU32[i>>2]=0);dn.HEAPU32[t>>2]=o.shader,dn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Mn(o.uniforms);dn.HEAPU32[s>>2]=r,dn.HEAPU32[i>>2]=a},wn=!0}const Tn={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 En{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 Cn{constructor(e,t=""){this.cache_=new En,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&&(_n.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())_n.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:_n.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 An(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Rn(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 In=new Map;function Fn(e){In.set(e.name,e)}function kn(e){In.delete(e)}function Bn(e){return In.get(e)}function zn(){In.clear()}const $n=Ee("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Un(e,t){const n=e.getEntitiesWithComponents([$n]);for(const s of n){const n=e.get(s,$n);if(!n.enabled||!n.playing||!n.clip)continue;const i=In.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,Xe)){const t=i.frames[n.currentFrame],o=e.get(s,Xe);o.texture=t.texture,e.insert(s,Xe,o)}a&&e.insert(s,$n,n)}}class Wn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}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})}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),this.createPendingHandle())}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,this.bgmVolume_):this.bgmHandle_&&this.bgmHandle_.stop();const n=t?.volume??1;this.bgmVolume_=n;const s=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:s?0:n,loop:!0}),s&&this.fadeIn(this.bgmHandle_,s,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else 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 dispose(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}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?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createPendingHandle(){return{id:-1,stop(){},pause(){},resume(){},setVolume(){},setPan(){},setLoop(){},setPlaybackRate(){},isPlaying:!1,currentTime:0,duration:0}}}Wn.mixer_=null,Wn.bufferCache_=new Map,Wn.bgmHandle_=null,Wn.bgmVolume_=1,Wn.fadeAnimId_=0;const Dn=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 On(e,t){Dn.set(e,t)}function Ln(e){const t=Dn.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 Hn(e){return Dn.get(e)?.fields??[]}function jn(e){return Dn.get(e)?.spine??null}const Xn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Yn(e,t){Xn.set(e,t)}function Vn(e){return Xn.get(e)}function Nn(e,t){const n=Xn.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 Gn(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,Qe,{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)Nn(i,n),Qn(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 qn(e,t){return Gn(e,t)}async function Kn(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 Jn.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=Dn.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=[...Jn.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=Dn.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=Gn(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 Jn=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=An(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);Fn(Rn(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 Wn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}]]);function Qn(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=$e(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 Zn(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function es(e,t){const n=e.getEntitiesWithComponents([Qe]);for(const s of n){const n=e.get(s,Qe);if(n&&n.value===t)return s}return null}class ts{constructor(e){this.textureCache_=new En,this.shaderCache_=new En,this.jsonCache_=new En,this.textCache_=new En,this.binaryCache_=new En,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new En,this.prefabCache_=new En,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_=d(ue.textCanvasSize,ue.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 Cn(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(),_n.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"===T(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(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,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=T(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 Ln(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=jn(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 Kn(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 _n.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 _n.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(U(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 ns=at(null,"Assets");class ss{build(e){const t=e.wasmModule;t?e.insertResource(ns,new ts(t)):console.warn("AssetPlugin: No WASM module available")}}const is=new ss;class os{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 rs(e,t){const n=e.getResource(ns);n&&n.registerEmbeddedAssets(t)}async function as(e,t,n){const{entities:s,rootId:i}=await cs(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 Kn(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 ls=10;async function cs(e,t,n,s,i,o=0){if(o>ls)throw new Error(`Prefab nesting depth exceeded ${ls}. 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 cs(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,d={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};us(d.components,r),ds(d,t),l.push(d)}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 us(e,t){for(const n of e){const e=Vn(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 ds(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 hs{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 as(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const fs=at(null,"Prefabs");class ps{constructor(){this.name="PrefabsPlugin",this.dependencies=[ns]}build(e){const t=e.getResource(ns);e.insertResource(fs,new hs(e.world,t))}}const ms=new ps;let gs=null,ys=0,_s=0,ws=0;const xs=new Float32Array(256);function vs(e){gs=e,ys=gs._malloc(64),_s=gs._malloc(64),ws=gs._malloc(1024)}function bs(){gs&&(ys&&(gs._free(ys),ys=0),_s&&(gs._free(_s),_s=0),ws&&(gs._free(ws),ws=0)),gs=null}function Ss(){if(!gs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return gs}const Ms={r:1,g:1,b:1,a:1},Ps={begin(e){const t=Ss();try{t.HEAPF32.set(e,ys/4),t.draw_begin(ys)}catch(e){_t(e,"Draw.begin")}},end(){try{Ss().draw_end()}catch(e){_t(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){_t(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){_t(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){_t(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){_t(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){_t(e,"Draw.circleOutline")}},texture(e,t,n,s=Ms){try{Ss().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){_t(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Ms){try{Ss().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){_t(e,"Draw.textureRotated")}},setLayer(e){Ss().draw_setLayer(e)},setDepth(e){Ss().draw_setDepth(e)},getDrawCallCount:()=>gs?gs.draw_getDrawCallCount():0,getPrimitiveCount:()=>gs?gs.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,_s/4),s.draw_mesh(e,t,_s)}catch(n){_t(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Ss(),i=_n.get(t);if(!i)return;if(Ps.setBlendMode(i.blendMode),Ps.setDepthTest(i.depthTest),0===i.uniforms.size)return void Ps.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,_s/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(un(n))xs[o++]=10,xs[o++]=s,xs[o++]=n.slot??e++,xs[o++]=n.textureId;else if("number"==typeof n)xs[o++]=1,xs[o++]=s,xs[o++]=n;else if(Array.isArray(n)){xs[o++]=n.length,xs[o++]=s;for(let e=0;e<n.length;e++)xs[o++]=n[e]}else"w"in n?(xs[o++]=4,xs[o++]=s,xs[o++]=n.x,xs[o++]=n.y,xs[o++]=n.z,xs[o++]=n.w):"z"in n?(xs[o++]=3,xs[o++]=s,xs[o++]=n.x,xs[o++]=n.y,xs[o++]=n.z):(xs[o++]=2,xs[o++]=s,xs[o++]=n.x,xs[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(xs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,_s);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),ws/4),s.draw_meshWithUniforms(e,i.shader,_s,ws,o)}catch(n){_t(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ts={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},Es=new Set;function Cs(e){const t=Ts[e];return void 0!==t?t:(Es.has(e)||(Es.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ts).join(", ")}`)),-1)}const As=new Map;function Rs(e,t,n){As.set(e,{fn:t,scene:n??""})}function Is(e){As.delete(e)}function Fs(){As.clear()}var ks;!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"}(ks||(ks={}));let Bs=null,zs=0,$s=0,Us=0;function Ws(e){Bs=e,zs=Bs._malloc(262144),$s=Bs._malloc(65536),Us=Bs._malloc(256)}function Ds(){Bs&&(zs&&Bs._free(zs),$s&&Bs._free($s),Us&&Bs._free(Us),zs=0,$s=0,Us=0),Bs=null}function Os(){if(!Bs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Bs}const Ls={create(e){const t=Os(),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,zs/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,Us,i).set(o),t.geometry_init(n,zs,s,Us,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=Os(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,zs/4),s.geometry_updateVertices(e,zs,i,n)},release(e){e>0&&Os().geometry_release(e)},isValid:e=>!(!Bs||e<=0)&&Bs.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Ls.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:ks.Float2},{name:"a_texCoord",type:ks.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 Ls.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ks.Float2},{name:"a_texCoord",type:ks.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 Ls.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:ks.Float2},{name:"a_texCoord",type:ks.Float2}],indices:new Uint16Array(r)})}};let Hs=null;function js(e){Hs=e}function Xs(){Hs&&Vs.isInitialized()&&Vs.shutdown(),Hs=null}function Ys(){if(!Hs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Hs}const Vs={init(e,t){try{return Ys().postprocess_init(e,t)}catch(n){return _t(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ys().postprocess_shutdown()}catch(e){_t(e,"PostProcess.shutdown")}},resize(e,t){try{Ys().postprocess_resize(e,t)}catch(n){_t(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ys().postprocess_addPass(e,t)}catch(t){return _t(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ys().postprocess_removePass(e)}catch(t){_t(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ys().postprocess_setPassEnabled(e,t)}catch(t){_t(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ys().postprocess_isPassEnabled(e)}catch(t){return _t(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Ys().postprocess_setUniformFloat(e,t,n)}catch(n){_t(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Ys().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){_t(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ys().postprocess_begin()}catch(e){_t(e,"PostProcess.begin")}},end(){try{Ys().postprocess_end()}catch(e){_t(e,"PostProcess.end")}},getPassCount(){try{return Ys().postprocess_getPassCount()}catch(e){return _t(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Hs)return!1;try{return Hs.postprocess_isInitialized()}catch(e){return _t(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ys().postprocess_setBypass(e)}catch(e){_t(e,"PostProcess.setBypass")}},isBypassed(){if(!Hs)return!0;try{return Hs.postprocess_isBypassed()}catch(e){return _t(e,"PostProcess.isBypassed"),!0}},createBlur:()=>_n.createShader(Ns,"#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:()=>_n.createShader(Ns,"#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:()=>_n.createShader(Ns,"#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:()=>_n.createShader(Ns,"#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")},Ns="#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 Gs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Gs||(Gs={}));let qs=null,Ks=0;function Js(e){qs=e,Ks=qs._malloc(64)}function Qs(){qs&&Ks&&(qs._free(Ks),Ks=0),qs=null}const Zs={init(e,t){qs?.renderer_init(e,t)},resize(e,t){qs?.renderer_resize(e,t)},begin(e,t){if(qs&&Ks)try{qs.HEAPF32.set(e,Ks/4),qs.renderer_begin(Ks,t??0)}catch(e){_t(e,"Renderer.begin")}},flush(){try{qs?.renderer_flush()}catch(e){_t(e,"Renderer.flush")}},end(){try{qs?.renderer_end()}catch(e){_t(e,"Renderer.end")}},submitSprites(e){if(qs)try{qs.renderer_submitSprites(e._cpp)}catch(e){_t(e,"Renderer.submitSprites")}},submitBitmapText(e){if(qs)try{qs.renderer_submitBitmapText(e._cpp)}catch(e){_t(e,"Renderer.submitBitmapText")}},submitSpine(e){if(qs)try{qs.renderer_submitSpine?.(e._cpp)}catch(e){_t(e,"Renderer.submitSpine")}},setStage(e){qs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>qs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){qs?.renderer_releaseTarget(e)},getTargetTexture:e=>qs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>qs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){qs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){qs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){qs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){qs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>qs?qs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>qs?{drawCalls:qs.renderer_getDrawCalls(),triangles:qs.renderer_getTriangles(),sprites:qs.renderer_getSprites(),text:qs.renderer_getText(),spine:qs.renderer_getSpine?.()??0,meshes:qs.renderer_getMeshes(),culled:qs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ei=null;function ti(e){ei=e}function ni(){ei=null}const si={enable(){ei?.gl_enableErrorCheck(!0)},disable(){ei?.gl_enableErrorCheck(!1)},check:e=>ei?.gl_checkErrors(e)??0,diagnose(){ei?.renderer_diagnose()}};class ii{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_||(Zs.resize(s,i),Vs.isInitialized()&&Vs.getPassCount()>0&&Vs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Zs.setViewport(0,0,s,i),Zs.clearBuffers(3),Zs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Zs.submitSprites(t),Zs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zs.submitSpine(t),Zs.flush(),this.executeDrawCallbacks(n,o),Zs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o}=e;Zs.setViewport(s.x,s.y,s.w,s.h),Zs.setScissor(s.x,s.y,s.w,s.h,!0),Zs.clearBuffers(i),Zs.setScissor(0,0,0,0,!1),Zs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Zs.submitSprites(t),Zs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Zs.submitSpine(t),Zs.flush(),this.executeDrawCallbacks(n,o),Zs.end()}executeDrawCallbacks(e,t){const n=As;if(n.size>0){Ps.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)}Ps.end();for(const e of s)Is(e)}}}const oi="__scene_transition_overlay__";class ri{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 ai{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,Ze,{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),Rs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Vs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Vs.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,Ze)){const n=this.app_.world.get(e,Ze);n.persistent=t,this.app_.world.insert(e,Ze,n)}}}class li{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??ue.sceneTransitionDuration,i=t.color??{...ue.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Rs(oi,()=>{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;Ps.setLayer(9999),Ps.setDepth(9999),Ps.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,Is(oi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Is(oi),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 ri(t);this.scenes_.set(e,n);const s=new ai(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ns)?this.app_.getResource(ns):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 ri(t);this.scenes_.set(e,n);const s=new ai(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(ns)?this.app_.getResource(ns):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,Ze)){if(this.app_.world.get(e,Ze).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Is(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Vs.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(ns)&&(i.assetServer=this.app_.getResource(ns));const o=await Kn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,Ze,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=ui(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(ns)?this.app_.getResource(ns):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)_n.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,Xe)){const t=n.get(e,Xe);s.sprite=t.color.a,t.color.a=0,n.insert(e,Xe,t),i=!0}if(n.has(e,Je)){const t=n.get(e,Je);s.spine=t.color.a,t.color.a=0,n.insert(e,Je,t),i=!0}if(n.has(e,Ke)){const t=n.get(e,Ke);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Ke,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,Xe)){const t=n.get(e,Xe);t.color.a=s.sprite,n.insert(e,Xe,t)}if(void 0!==s.spine&&n.has(e,Je)){const t=n.get(e,Je);t.color.a=s.spine,n.insert(e,Je,t)}if(void 0!==s.bitmapText&&n.has(e,Ke)){const t=n.get(e,Ke);t.color.a=s.bitmapText,n.insert(e,Ke,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Vs.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 ci=at(null,"SceneManager");function ui(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ci).getSceneStatus(t)&&n._fn(...s)}}}const di=Jt([ct(ci),lt(ht)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),hi={name:"SceneManager",build(e){const t=new li(e);e.insertResource(ci,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ci),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Gt.Startup,n),e.addSystemToSchedule(Gt.Last,di)}};class fi{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 jt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,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(Gt.Last);else{this.runSchedule(Gt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Gt.FixedPreUpdate),this.runSchedule(Gt.FixedUpdate),this.runSchedule(Gt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Gt.PreUpdate),this.runSchedule(Gt.Update),this.runSchedule(Gt.PostUpdate),this.runSchedule(Gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Pt,this.resources_=new dt;for(const e of Object.values(Gt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new fi}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(Gt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Gt.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 yt(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_}enableStats(){return this.statsEnabled_=!0,this}getSystemTimings(){return this.runner_?.getTimings()??null}getEntityCount(){return this.world_.entityCount()}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(ci).register(e),this}setInitialScene(e){return this.getResource(ci).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new nn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ht)||this.resources_.insert(ht,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Gt.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(Gt.Last);else{this.runSchedule(Gt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Gt.FixedPreUpdate),this.runSchedule(Gt.FixedUpdate),this.runSchedule(Gt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Gt.PreUpdate),this.runSchedule(Gt.Update),this.runSchedule(Gt.PostUpdate),this.runSchedule(Gt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new nn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ht,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Gt.Startup),this.lastTime_=h(),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=[ni,Qs,Xs,Ds,gn,bs];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(ht);t.delta=e,t.elapsed+=e,t.frameCount++}}function pi(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 mi=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function gi(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case Oe.FixedWidth:return o;case Oe.FixedHeight:return r;case Oe.Expand:return Math.max(o,r);case Oe.Shrink:return Math.min(o,r);case Oe.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const yi=[];function _i(e){if(e<yi.length)return yi[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 yi.push(t),t}function wi(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,Ze);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,d=0;if(i.projectionType===We.Orthographic){if(d=i.orthoSize,l){d=gi(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=vi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Si(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Pi(o.position.x,o.position.y,o.position.z),f=_i(c.length);f.entity=e,f.viewProjection.set(Ei(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=u,f.halfH=d,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const xi=new Float32Array(16);function vi(e,t,n,s,i,o){const r=xi;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 bi=new Float32Array(16);function Si(e,t,n,s){const i=bi;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 Mi=new Float32Array(16);function Pi(e,t,n){const s=Mi;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 Ti=new Float32Array(16);function Ei(e,t){const n=Ti;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 Ai(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,d=o.bottom+e.y*l,h=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=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Ri=Ue("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 Ii=null,Fi=null;function ki(e,t){e.has(t,Xe)||e.insert(t,Xe,{texture:me,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 Bi(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 zi(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 Ui(e,t,n,s){if(!e.has(t,Ri))return;const i=e.get(t,Ri),o=Bi(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,Ri,i)}function Wi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Di(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Oi(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(Di(r.charCodeAt(0))&&s.length>0&&Di(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Di(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 Li(e){let t=1;for(;t<e;)t*=2;return t}function Hi(e,t){let n=0,s=t;for(;e.has(s,Ge);){const t=e.get(s,Ge).entity;if(!e.valid(t))break;n++,s=t}return n}function ji(e,t){if(Ii&&Fi){const e=Ii.getUIRectComputedWidth(Fi,t);if(e>0)return e}return e.size.x}function Xi(e,t){if(Ii&&Fi){const e=Ii.getUIRectComputedHeight(Fi,t);if(e>0)return e}return e.size.y}function Yi(e,t,n,s,i,o){if(!e.has(t,Xe))return;const r=e.get(t,Xe);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,Xe,r))}function Vi(e,t,n){let s=t;for(;e.has(s,Ge);){const t=e.get(s,Ge).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ni(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Gi(e,t,n,s,i){if(!e.has(t,Ri))return;const o=e.get(t,Ri),r=Ai(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,Xe)){const n=e.get(t,Xe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Xe,n))}if(e.has(t,Le)){const n=e.get(t,Le);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,Le,n)}}function qi(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 Ki=.1,Ji=30,Qi={r:.3,g:.5,b:.8,a:1},Zi={Left:0,Center:1,Right:2},eo={Top:0,Middle:1,Bottom:2},to={Visible:0,Clip:1,Ellipsis:2},no=Ee("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Zi.Left,verticalAlign:eo.Top,wordWrap:!0,overflow:to.Visible,lineHeight:1.2});class so{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(ue.textCanvasSize,ue.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,Li(this.frameMaxW_)),e.height=Math.max(e.height,Li(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Li(this.frameMaxW_),e.height=Li(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=Oi(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===to.Ellipsis&&h>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,Li(f)),s.height=Math.max(s.height,Li(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===to.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 eo.Top:x=u;break;case eo.Middle:x=u+(p-2*u-w)/2;break;case eo.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 Zi.Left:s=u;break;case Zi.Center:s=f/2;break;case Zi.Right:s=f-u;break;default:s=u}n.fillText(t,s,v),v+=c}i&&e.overflow===to.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 Zi.Left:return"left";case Zi.Center:return"center";case Zi.Right:return"right"}}}const io=qi({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?ji(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Xi(e.uiRect,e.entity):0});class oo{build(e){ze("Text",no);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new so(t),s=e.world,i=new Map;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,no));for(const e of i.keys())if(!s.valid(e)||!s.has(e,no)){if(s.valid(e)&&s.has(e,Xe)){const t=s.get(e,Xe);s.insert(e,Xe,{texture:me,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([no]);for(const t of e){const e=s.get(t,no),o=s.has(t,Ri)?s.get(t,Ri):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!io.changed(a,r)){if(s.has(t,Xe)&&s.get(t,Xe).texture!==me)continue}ki(s,t);const l=o?{size:{x:ji(o,t),y:Xi(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Xe);s.insert(t,Xe,{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,io.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const ro=new oo,ao=0,lo=1,co=Ue("UIMask",{enabled:!0,mode:ao});function uo(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 ho(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],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-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=d*g-h*m,T=d*y-f*m,E=d*_-p*m,C=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let I=w*R-x*A+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*C)*I,n[1]=(o*A-i*R-r*C)*I,n[2]=(g*M-y*S+_*b)*I,n[3]=(f*S-h*M-p*b)*I,n[4]=(c*E-a*R-u*T)*I,n[5]=(s*R-o*E+r*T)*I,n[6]=(y*v-m*M-_*x)*I,n[7]=(d*M-f*v+p*x)*I,n[8]=(a*A-l*E+u*P)*I,n[9]=(i*E-s*A-r*P)*I,n[10]=(m*S-g*v+_*w)*I,n[11]=(h*v-d*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-y*w)*I,n[15]=(d*b-h*x+f*w)*I),n}function fo(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],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function po(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 mo(e,t){return 2*Math.atan2(e,t)}function go(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 yo(e,t,n,s,i,o,r,a,l,c){const u=mo(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function _o(e,t,n,s,i,o,r){if(!e.has(t,Ri)||!e.has(t,Le))return null;const a=e.get(t,Ri),l=e.get(t,Le),c=ji(a,t)*l.worldScale.x,u=Xi(a,t)*l.worldScale.y,d=l.worldPosition.x,h=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=mo(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[d+m*x-y*v,h+m*v+y*x],[d+g*x-y*v,h+g*v+y*x],[d+g*x-_*v,h+g*v+_*x],[d+m*x-_*v,h+m*v+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=go(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 wo(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([co]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,co);n.enabled&&(d.add(e),n.mode===lo?(u.push(e),h.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;Vi(t,e,e=>{if(i.has(e)){if(t.get(e,co).mode===ao)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,co).mode===ao){const e=_o(t,n,o,r,a,l,c);e&&(s=uo(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=_o(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,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;Vi(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,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class xo{build(e){if(ze("UIMask",co),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(wo(e.wasmModule,e.world))}}const vo=new xo,bo=Ue("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),So=Ue("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Mo={Normal:0,Hovered:1,Pressed:2,Disabled:3},Po=Ee("Button",{state:Mo.Normal,transition:null});class To{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 Eo=at(new To,"UIEvents");class Co{build(e){ze("UIRect",Ri);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Ii=e,Fi=t}(n,s);e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(ln)],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(Gt.PostUpdate,Jt([lt(ln)],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(Gt.PostUpdate,Jt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ao=new Co;let Ro=!1,Io=!1;function Fo(e){Ro=e}function ko(){return Ro}function Bo(){return!Ro}function zo(e){Io=e}function $o(){return Io}const Uo=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&&(ho(t,e),n=!1),e)}}();function Wo(e,t,n,s){t.emit(n,s,n),Vi(e,n,i=>{if(!e.has(i,bo))return!1;const o=e.get(i,bo);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Do{build(e){ze("Interactable",bo),ze("Button",Po);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new To;e.insertResource(Eo,i);let o=null,r=null;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(on),lt(ln)],(e,a)=>{if(i.drain(),ko()&&!$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,d=a.screenH-e.mouseY*c;Uo.update(a.viewProjection);const h=fo(u,d,Uo.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,h.x,h.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){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!==_){Ni(t,_,So);const e=t.get(_,So);e.hovered=!0,t.insert(_,So,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,So);e.pressed=!0,e.justPressed=!0,t.insert(_,So,e),r=_,Wo(t,i,_,"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(Gt.Update,Jt([],()=>{const e=t.getEntitiesWithComponents([Po]);for(const n of e){if(Ni(t,n,bo,{enabled:!0}),!t.has(n,So))continue;const e=t.get(n,So),s=t.get(n,Po),i=t.get(n,bo),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Mo.Pressed:e.hovered?s.state=Mo.Hovered:s.state=Mo.Normal:s.state=Mo.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Xe)){const o=t.get(n,Xe);o.color=Wi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Xe,o)}}},{name:"ButtonSystem"}))}}const Oo=new Do,Lo=Ee("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}),Ho=Ee("Focusable",{tabIndex:0,isFocused:!1});class jo{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 Xo=at(new jo,"FocusManager");class Yo{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ze("TextInput",Lo),ko()&&!$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=d(ue.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=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 m(){const t=e.getResource(Xo);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Lo)?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,Lo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Eo).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,Lo);s.focused=!1,s.dirty=!0;e.getResource(Xo).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,Lo);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(Eo).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,Lo);e.focused=!1,e.dirty=!0}e.getResource(Xo).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!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,d){(i.width<u||i.height<d)&&(i.width=Li(Math.max(i.width,u)),i.height=Li(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.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,u,d),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,d),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),y=l.padding;if(l.multiline){const e=Oi(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.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=Oi(o,l.value,u-2*y);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=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(d-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 _=o.getImageData(0,0,u,d),w=new Uint8Array(_.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,d,r,w.length,1,!0);s.set(e,b);const S=n.get(e,Xe);S.texture=b,S.size.x=u,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},n.insert(e,Xe,S)}e.addSystemToSchedule(Gt.Update,Jt([lt(Xo)],e=>{const t=n.getEntitiesWithComponents([Lo]);for(const e of t)Ni(n,e,Ho,{tabIndex:0,isFocused:!1}),Ni(n,e,bo,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Lo)){const e=n.get(M,Lo);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Lo);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(Gt.PreUpdate,Jt([],()=>{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 o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,Lo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Lo)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Lo,Ri]);for(const e of a){const t=n.get(e,Lo);if(!t.dirty)continue;const s=n.get(e,Ri),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(ki(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Vo=new Yo,No={Simple:0,Sliced:1,Tiled:2,Filled:3},Go={Horizontal:0,Vertical:1},qo={Left:0,Right:1,Bottom:2,Top:3},Ko=Ee("Image",{texture:me,color:{r:1,g:1,b:1,a:1},imageType:No.Simple,fillMethod:Go.Horizontal,fillOrigin:qo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Jo=qi({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?ji(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Xi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Qo=new class{build(e){ze("Image",Ko);const t=e.world,n=new Map;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Ko)||n.delete(e);const e=t.getEntitiesWithComponents([Ko]);for(const s of e){const e=t.get(s,Ko),i=t.has(s,Ri)?t.get(s,Ri):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Jo.changed(r,o))continue;ki(t,s);const a=t.get(s,Xe);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=ji(i,s),a.size.y=Xi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===No.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Go.Horizontal?e.fillOrigin===qo.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===qo.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===No.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,Xe,a),n.set(s,Jo.take(o))}else a.color.a=0,t.insert(s,Xe,a),n.set(s,Jo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Zo=Ee("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),er=Ee("ToggleGroup",{allowSwitchOff:!1});const tr=new class{build(e){ze("Toggle",Zo),ze("ToggleGroup",er);const t=e.world,n=new Set;e.addSystemToSchedule(Gt.Update,Jt([lt(Eo)],e=>{const s=t.getEntitiesWithComponents([Zo]);if(!ko()||$o()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Zo);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Zo,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Zo);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(Ni(t,n,bo,{enabled:!0}),!t.has(n,So))continue;const s=t.get(n,So),i=t.get(n,Zo),r=t.get(n,bo);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,er);if(i.isOn&&r){if(!t.get(s,er).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Zo,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,Zo);i.isOn&&(i.isOn=!1,t.insert(s,Zo,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Xe)){const e=t.get(n,Xe);e.color=Wi(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Xe,e)}}}for(const e of s){const n=t.get(e,Zo);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Xe)){const e=t.get(n.graphicEntity,Xe);e.enabled=n.isOn,t.insert(n.graphicEntity,Xe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},nr=Ci,sr=Ee("ProgressBar",{value:0,fillEntity:0,direction:Ci.LeftToRight});function ir(e,t,n,s){if(!e.has(t,Ri))return;const i=e.get(t,Ri),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=Ai(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Xe,n))}if(e.has(t,Le)){const n=e.get(t,Le),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,Le,n))}}class or{build(e){ze("ProgressBar",sr);const t=e.world;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{const e=t.getEntitiesWithComponents([sr,Ri]);for(const n of e){const e=t.get(n,sr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Ri),i=Math.max(0,Math.min(1,e.value));Ui(t,e.fillEntity,e.direction,i);const o=ji(s,n),r=Xi(s,n);ir(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const rr=new or,ar=Ee("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),lr=Ee("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 cr=new class{build(e){ze("Draggable",ar),ze("DragState",lr);const t=e.world,n=e.getResource(Eo);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(on),lt(ln)],(e,r)=>{if(ko()&&!$o())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([ar,So]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,ar).enabled)continue;if(t.get(s,So).hovered){let e=0;t.has(s,Xe)&&(e=t.get(s,Xe).layer);const i=Hi(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,lr)||t.insert(n,lr);const e=t.get(n,lr),o=t.get(n,Le);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,lr)){t.get(s,lr).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,ar);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,lr).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,lr))return void(o=null);const s=t.get(o,lr),i=t.get(o,ar),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=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=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,Le)){const e=function(e,t,n,s){if(!e.has(t,Ge))return{x:n,y:s};const i=e.get(t,Ge).entity;if(!e.valid(i)||!e.has(i,Le))return{x:n,y:s};const o=e.get(i,Le),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=mo(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,Le);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,Le,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},ur=Ee("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function dr(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 hr(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 fr=new class{build(e){ze("ScrollView",ur);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Gt.PostUpdate,Jt([lt(on),lt(ln),lt(ht)],(e,i,o)=>{const r=ko()&&!$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([ur,Ri]);for(const o of l){Ni(t,o,co,{enabled:!0,mode:ao});const l=t.get(o,ur),c=t.get(o,Ri);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 d=ji(c,o),h=Xi(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,qe)){const e=t.get(l.contentEntity,qe).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,Le))continue;const e=t.get(r,Le);let a=0,l=0,c=.5,u=.5;if(t.has(r,Ri)){const e=t.get(r,Ri);a=ji(e,r)||e.size.x,l=Xi(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Xe)){const e=t.get(r,Xe);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);d<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){Ni(t,o,bo,{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=dr(l.scrollX,0,m,d);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=dr(l.scrollY,0,g,h);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*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(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=dr(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=dr(l.scrollX,0,m,d);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=hr(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)<Ki&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Ki?(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=hr(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)<Ki&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Ki?(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*d,t=.5*h;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,Le)){const e=t.get(l.contentEntity,Le),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,Le,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},pr=Ci,mr=Ee("Slider",{value:0,minValue:0,maxValue:1,direction:Ci.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function gr(e,t,n,s,i,o){const r=ji(s,i)*n.worldScale.x,a=Xi(s,i)*n.worldScale.y,l=mo(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*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 yr(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 _r{build(e){ze("Slider",mr);const t=e.world;let n=null;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(on),lt(ln),lt(Eo)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([mr,Ri]);for(const r of o){const o=t.get(r,mr),a=t.get(r,Ri);if(!ko()||$o()){if(t.has(r,Le)){Ni(t,r,bo,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ni(t,o.handleEntity,bo,{enabled:!0,blockRaycast:!1});const l=t.get(r,Le),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=gr(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,mr,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=ji(a,r),d=Xi(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ui(t,o.fillEntity,o.direction,c),Gi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Ri)){const e=t.get(o.handleEntity,Ri);yr(e,o.direction,c),t.insert(o.handleEntity,Ri,e),Gi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const wr=new _r;const xr=new class{build(e){ze("Focusable",Ho);const t=e.world,n=new jo;e.insertResource(Xo,n),e.addSystemToSchedule(Gt.Update,Jt([lt(on),lt(Eo)],(e,s)=>{if(ko()&&!$o())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Ho]);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,bo)){if(!t.get(n,bo).enabled)continue}const s=t.get(n,Ho);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,Ho)){t.get(i,Ho).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Ho).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},vr=Ee("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function br(){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 Sr=new class{build(e){ze("SafeArea",vr);const t=e.world;let n=br(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=br(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=br(),s=!0});e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(ln)],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([vr,Ri]);for(const e of u){const s=t.get(e,vr),i=t.get(e,Ri),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,Ri,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Mr=Ee("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Pr=null;function Tr(e,t){if(!Pr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Pr.get(e);n?n.renderer=t:Pr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const Er=new class{build(e){ze("ListView",Mr);const t=e.world,n=new Map;Pr=n,e.addSystemToSchedule(Gt.PostUpdate,Jt([lt(on)],e=>{const s=ko()&&!$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([Mr,Ri]);for(const o of i){Ni(t,o,bo,{enabled:!0,blockRaycast:!0}),Ni(t,o,co,{enabled:!0,mode:ao});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,Mr),a=t.get(o,Ri),l=Xi(a,o),c=ji(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 d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Qe,{value:`ListItem_${e}`}),t.insert(n,Ri,{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,Le)){const s=t.get(n,Le);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,Le,s)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Cr=Ee("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Ar=new class{build(e){ze("Dropdown",Cr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Le))return;const n=t.get(e,Le);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Le,{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,Xe)){const n=t.get(e,Xe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Xe,{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,Xe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*Ji;t.insert(i,Ri,{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,Le,{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,Xe,{texture:me,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)*Ji;t.insert(o,Qe,{value:`Option_${e}`}),t.insert(o,Ri,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Ji},offsetMax:{x:0,y:0},size:{x:r,y:Ji},pivot:{x:.5,y:.5}}),t.insert(o,Le,{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,Xe,{texture:me,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Ji},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,bo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,Le,{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,no,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Zi.Left,verticalAlign:eo.Middle,wordWrap:!1,overflow:to.Clip,lineHeight:1.2}),t.insert(c,Ri,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Ji},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(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,no))return;const s=t.get(n,no);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,no,{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,bo)&&t.insert(e,bo,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Xe))){const s=t.get(e,Xe);t.insert(e,Xe,{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 d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Xe))continue;const i=n===e.highlightIndex?{...Qi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Xe,{texture:me,color:i,size:{x:e.ddWidth,y:Ji},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,So))continue;if(t.get(n,So).hovered)return!0}return!1}e.addSystemToSchedule(Gt.Update,Jt([lt(on),lt(Eo)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=ko()&&!$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;Ni(t,m,bo,{enabled:!0,blockRaycast:!0});const y=t.has(m,So)?t.get(m,So):null;if(y?.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,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Rr=0,Ir=0,Fr=2,kr=Ee("LayoutGroup",{direction:Rr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Ir,reverseOrder:!1});const Br=new class{build(e){ze("LayoutGroup",kr);const t=e.world;e.addSystemToSchedule(Gt.PreUpdate,Jt([],()=>{const e=t.getEntitiesWithComponents([kr,Ri,qe]);for(const n of e){const e=t.get(n,kr),s=t.get(n,Ri),i=t.get(n,qe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Ri)&&t.has(e,Le)&&o.push({entity:e,rect:t.get(e,Ri)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=ji(s,n),a=Xi(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===Rr;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=ji(s.rect,s.entity),f=Xi(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===Ir?(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,h+=i,n<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Ir?-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,y=(1-c)*a-u.top-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const _=t.get(s.entity,Le);_.position.x=g,_.position.y=y,t.insert(s.entity,Le,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Ue("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Ue("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class zr{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Gt.PostUpdate,Jt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const $r=new zr;async function Ur(e,t,n){const s=e.getResource(ci);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 Dr=at({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Or=at(null,"PhysicsAPI");function Lr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Hr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class jr{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(Dr,{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([Ve]);for(const n of t){const t=e.world.get(n,Ve);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(Gt.PostUpdate,Jt([lt(ht)],a=>{const l=r.getEntitiesWithComponents([tt,Le]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,tt),l=r.get(i,Le);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=Lr(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),Xr(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===ot.Kinematic){const e=Lr(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,Le);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(r,Ge)){const t=e.world.get(r,Ge);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Le)){const n=e.world.get(t.entity,Le),s=Lr(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=Hr(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,Le,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(Dr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Or,Yr._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Xr(e,t,n){const s=e.world;if(s.has(n,nt)){const e=s.get(n,nt);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,st)){const e=s.get(n,st);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,it)){const e=s.get(n,it);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 Yr{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(Yr.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 Vr={nearest:0,linear:1},Nr={repeat:0,clamp:1,mirror:2};function Gr(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=Vr[s.filterMode??"linear"]??1,a=Nr[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 qr(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 Kr(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,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,v=u*h,b=u*f;return new Float32Array([(1-(y+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(_+x)*o,0,(g+v)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Jr(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=Hn(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]=Gr(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={},d=null;if(i&&(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"])}}(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=jn(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"===T(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=qr(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=Gr(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,i,d,n,s)),o){const t={gravity:r?.gravity??{...ae},fixedTimestep:r?.fixedTimestep??le,subStepCount:r?.subStepCount??4};new jr("",t,()=>Promise.resolve(o)).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=Hn(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=T(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=Gr(e,c,!1),d=e.getResourceManager();s[o]=d.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=Hn(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=_n.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=_n.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=Hn(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=qn(e.world,n);if(l&&e.hasResource(ci))for(const t of p.values())e.world.insert(t,Ze,{scene:l,persistent:!1});if(i&&d){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=jn(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}(d,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=re);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Je)?c.get(o,Je):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,Le)){const e=Kr(c.get(o,Le),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>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),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(e,t,i,d,s)}if(a){const t=e.getResource(ns);t&&t.setAddressableManifest(a)}}function Qr(e,t,n){return{name:e,async setup(){await Jr(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Zr{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=jn(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===T(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=Hn(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=T(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 ea="__preview__";class ta{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(ci);t.register({name:ea,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ea),this.loadPromise_=t.load(ea).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 Zr(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Jr(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,ea)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).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([Ve]);for(const i of s){const s=e.get(i,Ve);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(ci).getScene(ea),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,Le,r);const a={isActive:!0,projectionType:We.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:De.ColorAndDepth};e.insert(o,Ye,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(ci);await e.switchTo(ea),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 na={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Zs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Zs.getTargetTexture(n),width:e.width,height:e.height}},release(e){Zs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Zs.releaseRenderTarget(e._handle),na.create({width:t,height:n,depth:!0})),begin(e,t){Zs.begin(t,e._handle)},end(){Zs.end()},getDepthTexture:e=>Zs.getTargetDepthTexture(e._handle)};var sa;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(sa||(sa={}));class ia{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${sa[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case sa.Debug:console.debug(t,n);break;case sa.Info:console.log(t,n);break;case sa.Warn:console.warn(t,n);break;case sa.Error:console.error(t,n)}}}class oa{constructor(){this.handlers_=[],this.minLevel_=sa.Info,this.addHandler(new ia)}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(sa.Debug,e,t,n)}info(e,t,n){this.log(sa.Info,e,t,n)}warn(e,t,n){this.log(sa.Warn,e,t,n)}error(e,t,n){this.log(sa.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 ra=new oa;function aa(){return ra}function la(e){ra.setMinLevel(e)}function ca(e,t,n){ra.debug(e,t,n)}function ua(e,t,n){ra.info(e,t,n)}function da(e,t,n){ra.warn(e,t,n)}function ha(e,t,n){ra.error(e,t,n)}const fa={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},pa={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},ma={Running:0,Paused:1,Completed:2,Cancelled:3},ga={None:0,Restart:1,PingPong:2};class ya{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 _a=null,wa=null;function xa(e,t){_a=e,wa=t}function va(){_a=null,wa=null}function ba(){if(!_a)throw new Error("Tween API not initialized");return _a}function Sa(){if(!wa)throw new Error("Tween API not initialized");return wa}const Ma={to(e,t,n,s,i,o){const r=ba(),a=Sa(),l=o?.easing??fa.Linear,c=o?.delay??0,u=o?.loop??ga.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new ya(r,a,h)},cancel(e){ba()._anim_cancelTween(Sa(),e.entity)},cancelAll(e){ba()._anim_cancelAllTweens(Sa(),e)},update(e){ba()._anim_updateTweens(Sa(),e)}};class Pa{constructor(){this.name="AnimationPlugin"}build(e){xa(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Gt.Update,Jt([lt(ht)],e=>{Ma.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Gt.Update,Jt([lt(ht)],e=>{Un(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){va()}}const Ta=new Pa;var Ea;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Ea||(Ea={}));const Ca={model:Ea.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Aa(e,t=Ca){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);switch(n){case Ea.Linear:{const e=i-s;if(e<=0)return 1;return 1-(Math.min(Math.max(r,s),i)-s)/e}case Ea.Inverse:return s/Math.max(r,s);case Ea.Exponential:return Math.pow(Math.max(r,s)/s,-o);default:return 1}}function Ra(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const Ia=Ee("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Ea.Inverse,rolloff:1,priority:0,enabled:!0}),Fa=Ee("AudioListener",{enabled:!0});class ka{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize});const i=n.mixer;Wn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;e.addSystemToSchedule(Gt.PreUpdate,Jt([lt(ht)],t=>{const s=e.world;let i=0,r=0;const a=s.getEntitiesWithComponents([Fa,je]);for(const e of a){if(s.get(e,Fa).enabled){const t=s.get(e,je);i=t.position.x,r=t.position.y;break}}const l=s.getEntitiesWithComponents([Ia,je]),c=new Set;for(const e of l){const t=s.get(e,Ia);if(!t.enabled||!t.clip)continue;c.add(e);const a=s.get(e,je);if(t.playOnAwake&&!o.has(e)){const s=Wn.getBufferHandle(t.clip);if(s){const i=n.play(s,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch,priority:t.priority});o.set(e,i)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(e)){const n=o.get(e);if(!n.isPlaying){o.delete(e);continue}const s=a.position.x-i,l=a.position.y-r,c=Aa(Math.sqrt(s*s+l*l),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),u=Ra(a.position.x,a.position.y,i,0,t.maxDistance);n.setVolume(t.volume*c),n.setPan(u)}}for(const[e,t]of o)c.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){Wn.dispose()}}const Ba=new ka;function za(e,t){return e.toFixed(t)}class $a{constructor(e,t="bottom-left"){this.visible_=!0,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${za(e.fps,1)}</span> Frame: <span style="color:#d19a66">${za(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of n){s+=`<div>${(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${za(t,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.el_.parentElement?.removeChild(this.el_)}}function Ua(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Wa=at(Ua(),"Stats");class Da{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60)}getFps(){return 0===this.count_||0===this.sum_?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||0===this.sum_?0:this.sum_/this.count_*1e3}}class Oa{constructor(e){this.name="Stats",this.collector_=new Da,this.overlay_=null,this.options_=e??{}}build(e){e.enableStats(),e.insertResource(Wa,Ua());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new $a(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=Jt([lt(ht),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Wa);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();o.systemTimings=r?new Map(r):new Map;const a=Zs.getStats();o.drawCalls=a.drawCalls,o.triangles=a.triangles,o.sprites=a.sprites,o.text=a.text,o.spine=a.spine,o.meshes=a.meshes,o.culled=a.culled,n?.update(o)},{name:"StatsCollect"});e.addSystemToSchedule(Gt.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const La=new Oa;class Ha{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 ja(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 Xa(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:o}=e,r=t.getResource(ns);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0)),pi(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ja(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 ja(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Qr(o,i,{app:t,module:n,provider:new Ha(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),u=t.getResource(ci);u.register(c),u.setInitial(o),await u.load(o);const d=e.canvas.width/e.canvas.height;Zn(t.world,d),t.run()}const Ya=[ro,vo,Ao,Qo,rr,Oo,cr,fr,wr,tr,Vo,xr,Sr,Er,Ar,Br,$r],Va=[...Ya,Ta];function Na(e,t){return function(e,t){const n=fi.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),vs(e),mn(e),Ws(e),js(e),Js(e),ti(e);const i=new ii;n.setPipeline(i);let o=h();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=wi(e,s,t,i));const r=n.getResource(ln);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(ln,{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;Zs.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(Zs.resize(t,l),Vs.isInitialized()&&Vs.getPassCount()>0&&!Vs.isBypassed()&&Vs.resize(t,l),n.hasResource(ci)){const e=n.getResource(ci).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=wi(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:mi,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})}Zs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Gt.First,l),n.addSystemToSchedule(Gt.Last,c),n.addPlugin(is),n.addPlugin(ms),n.addPlugin(an),n.addPlugin(hi),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Va,...t})}class Ga{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 qa(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Ka(e,t){try{return await e({instantiateWasm:qa(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Ja(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=U(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:qa("esengine.wasm")}),c=o.getContext("webgl2")||o.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}),d=Na(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&fe(d,e.runtimeConfig),pi(d);let h=null;e.spineFactory&&(h=await Ka(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Ka(e.physicsFactory,"physics.wasm"));const p={app:d,module:a,provider:new Ga(i),spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n},m=d.getResource(ci);for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`),n=JSON.parse(e);m.register(Qr(t,n,p))}e.firstScene&&(m.setInitial(e.firstScene),await m.load(e.firstScene));const g=o.width/o.height;Zn(d.world,g),d.run()}q||(q=!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 w(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 x(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=K;export{Ct as Added,Pa as AnimationPlugin,fi as App,ss as AssetPlugin,os as AssetRefCounter,ts as AssetServer,ns as Assets,En as AsyncCache,Ea as AttenuationModel,Wn as Audio,p as AudioBus,Fa as AudioListener,m as AudioMixer,ka as AudioPlugin,g as AudioPool,Ia as AudioSource,Ke as BitmapText,cn as BlendMode,ot as BodyType,nt as BoxCollider,Po as Button,Mo as ButtonState,Ye as Camera,Ve as Canvas,it as CapsuleCollider,At as Changed,qe as Children,st as CircleCollider,De as ClearFlags,Wt as Commands,Ot as CommandsInstance,Q as DEFAULT_DESIGN_HEIGHT,J as DEFAULT_DESIGN_WIDTH,re as DEFAULT_FALLBACK_DT,le as DEFAULT_FIXED_TIMESTEP,ne as DEFAULT_FONT_FAMILY,se as DEFAULT_FONT_SIZE,ae as DEFAULT_GRAVITY,ie as DEFAULT_LINE_HEIGHT,oe as DEFAULT_MAX_DELTA_TIME,Z as DEFAULT_PIXELS_PER_UNIT,ce as DEFAULT_SPINE_SKIN,te as DEFAULT_SPRITE_SIZE,ee as DEFAULT_TEXT_CANVAS_SIZE,ks as DataType,lr as DragState,ar as Draggable,Ps as Draw,Cr as Dropdown,fa as EasingType,Dt as EntityCommands,Yt as EventReader,Nt as EventReaderInstance,jt as EventRegistry,Xt as EventWriter,Vt as EventWriterInstance,Ci as FillDirection,Go as FillMethod,qo as FillOrigin,Xo as FocusManager,jo as FocusManagerState,Ho as Focusable,si as GLDebug,Ls as Geometry,qt as GetWorld,pe as INVALID_ENTITY,ge as INVALID_FONT,ye as INVALID_MATERIAL,me as INVALID_TEXTURE,Ko as Image,No as ImageType,on as Input,rn as InputPlugin,sn as InputState,bo as Interactable,Mr as ListView,He as LocalTransform,sa as LogLevel,oa as Logger,ga as LoopMode,_n as Material,Cn as MaterialLoader,Tt as Mut,Qe as Name,Ge as Parent,Yr as Physics,Dr as PhysicsEvents,jr as PhysicsPlugin,Vs as PostProcess,hs as PrefabServer,fs as Prefabs,ps as PrefabsPlugin,ta as PreviewPlugin,sr as ProgressBar,nr as ProgressBarDirection,or as ProgressBarPlugin,We as ProjectionType,Bt as Query,zt as QueryInstance,$t as Removed,Ut as RemovedQueryInstance,ii as RenderPipeline,Gs as RenderStage,na as RenderTexture,Zs as Renderer,lt as Res,ct as ResMut,tt as RigidBody,ue as RuntimeConfig,vr as SafeArea,Oe as ScaleMode,ci as SceneManager,li as SceneManagerState,Ze as SceneOwner,Gt as Schedule,ur as ScrollView,Tn as ShaderSources,mr as Slider,pr as SliderDirection,_r as SliderPlugin,Je as SpineAnimation,Xe as Sprite,$n as SpriteAnimator,Wa as Stats,Da as StatsCollector,$a as StatsOverlay,Oa as StatsPlugin,nn as SystemRunner,no as Text,Zi as TextAlign,Lo as TextInput,Yo as TextInputPlugin,to as TextOverflow,oo as TextPlugin,so as TextRenderer,eo as TextVerticalAlign,ht as Time,Zo as Toggle,Le as Transform,Ma as Tween,ya as TweenHandle,ma as TweenState,pa as TweenTarget,ln as UICameraInfo,To as UIEventQueue,Eo as UIEvents,So as UIInteraction,Do as UIInteractionPlugin,Co as UILayoutPlugin,co as UIMask,xo as UIMaskPlugin,Ri as UIRect,zr as UIRenderOrderPlugin,Ne as Velocity,Ga as WeChatAssetProvider,Zr as WebAssetProvider,Pt as World,je as WorldTransform,en as addStartupSystem,Zt as addSystem,tn as addSystemToSchedule,Ta as animationPlugin,fe as applyBuildRuntimeConfig,Ui as applyDirectionalFill,de as applyRuntimeConfig,is as assetPlugin,Ba as audioPlugin,Aa as calculateAttenuation,Ra as calculatePanning,zn as clearAnimClips,Fs as clearDrawCallbacks,Re as clearUserComponents,ve as color,Bi as computeFillAnchors,$i as computeFillSize,zi as computeHandleAnchors,Ai as computeUIRectLayout,wo as createMaskProcessor,Qr as createRuntimeSceneConfig,Na as createWebApp,ca as debug,Ua as defaultFrameStats,Ee as defineComponent,Lt as defineEvent,at as defineResource,Jt as defineSystem,Ce as defineTag,ha as error,An as extractAnimClipTexturePaths,es as findEntityByName,pi as flushPendingSystems,C as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Bn as getAnimClip,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,Hn as getComponentAssetFieldDescriptors,Ln as getComponentAssetFields,et as getComponentDefaults,Vn as getComponentEntityFields,jn as getComponentSpineFieldDescriptor,k as getCustomExtensions,E as getEditorType,aa as getLogger,t as getPlatform,s as getPlatformType,Ae as getUserComponent,B as getWeChatPackOptions,ua as info,vs as initDrawAPI,ti as initGLDebugAPI,Ws as initGeometryAPI,mn as initMaterialAPI,Xa as initPlayableRuntime,js as initPostProcessAPI,Js as initRendererAPI,xa as initTweenAPI,Ja as initWeChatRuntime,an as inputPlugin,as as instantiatePrefab,uo as intersectRects,ho as invertMatrix4,ke as isBuiltinComponent,$ as isCustomExtension,ko as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,$o as isPlayMode,Bo as isRuntime,un as isTextureRef,i as isWeChat,o as isWeb,Qn as loadComponent,Wr as loadPhysicsModule,Jr as loadRuntimeScene,qn as loadSceneData,Kn as loadSceneWithAssets,F as looksLikeAssetPath,Rn as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,yo as pointInOBB,po as pointInWorldRect,ms as prefabsPlugin,rr as progressBarPlugin,be as quat,Fn as registerAnimClip,ze as registerComponent,On as registerComponentAssetFields,Yn as registerComponentEntityFields,Rs as registerDrawCallback,rs as registerEmbeddedAssets,Pn as registerMaterialCallback,Nn as remapEntityFields,hi as sceneManagerPlugin,fo as screenToWorld,Fo as setEditorMode,Tr as setListViewRenderer,la as setLogLevel,zo as setPlayMode,yt as setWasmErrorHandler,bs as shutdownDrawAPI,ni as shutdownGLDebugAPI,Ds as shutdownGeometryAPI,gn as shutdownMaterialAPI,Xs as shutdownPostProcessAPI,Qs as shutdownRendererAPI,va as shutdownTweenAPI,wr as sliderPlugin,Un as spriteAnimatorSystemUpdate,La as statsPlugin,Yi as syncFillSpriteSize,Vo as textInputPlugin,ro as textPlugin,U as toBuildPath,Ur as transitionTo,Oo as uiInteractionPlugin,Ao as uiLayoutPlugin,vo as uiMaskPlugin,Ya as uiPlugins,$r as uiRenderOrderPlugin,kn as unregisterAnimClip,Ie as unregisterComponent,Is as unregisterDrawCallback,Zn as updateCameraAspectRatio,_e as vec2,we as vec3,xe as vec4,da as warn,ui as wrapSceneSystem,j as wxFileExists,X as wxFileExistsSync,N as wxGetImagePixels,V as wxLoadImage,G as wxLoadImagePixels,L as wxReadFile,H as wxReadTextFile,Y 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 9d10ec8b3..2b28db772 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -1082,7 +1082,10 @@ declare class SystemRunner {
private readonly argsCache_;
private readonly systemTicks_;
private currentLastRunTick_;
+ private timings_;
constructor(world: World, resources: ResourceStorage, eventRegistry?: EventRegistry);
+ setTimingEnabled(enabled: boolean): void;
+ getTimings(): ReadonlyMap<string, number> | null;
run(system: SystemDef): void;
private resolveParam;
}
@@ -1891,6 +1894,7 @@ declare class App {
private readonly sortedSystemsCache_;
private error_handler_;
private system_error_handler_;
+ private statsEnabled_;
private frame_paused_;
private user_paused_;
private step_pending_;
@@ -1929,6 +1933,9 @@ declare class App {
stepFrame(): void;
setPlaySpeed(speed: number): void;
getPlaySpeed(): number;
+ enableStats(): this;
+ getSystemTimings(): ReadonlyMap<string, number> | null;
+ getEntityCount(): number;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
@@ -2719,6 +2726,93 @@ declare class WebAssetProvider implements RuntimeAssetProvider {
private resolveUrl;
}
+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;
+}
+
+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 AudioBackendInitOptions {
+ initialPoolSize?: number;
+ mixerConfig?: AudioMixerConfig;
+}
+interface PlatformAudioBackend {
+ readonly name: string;
+ readonly mixer: AudioMixer | null;
+ initialize(options?: AudioBackendInitOptions): 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;
+}
+
/**
* @file types.ts
* @brief Platform adapter interface definitions
@@ -2768,6 +2862,7 @@ interface PlatformAdapter {
now(): number;
createImage(): HTMLImageElement;
bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void;
+ createAudioBackend(): PlatformAudioBackend;
}
type PlatformType = 'web' | 'wechat';
@@ -3447,88 +3542,6 @@ 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_;
@@ -3619,8 +3632,6 @@ interface AudioListenerData {
}
declare const AudioListener: ComponentDef<AudioListenerData>;
-declare function createAudioBackend(): PlatformAudioBackend;
-
declare enum AttenuationModel {
Linear = 0,
Inverse = 1,
@@ -3635,10 +3646,56 @@ interface SpatialAudioConfig {
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;
+type StatsPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
+declare class StatsOverlay {
+ private el_;
+ private visible_;
+ constructor(container: HTMLElement, position?: StatsPosition);
+ update(stats: FrameStats): void;
+ show(): void;
+ hide(): void;
+ dispose(): void;
+}
+
+interface FrameStats {
+ fps: number;
+ frameTimeMs: number;
+ entityCount: number;
+ systemTimings: Map<string, number>;
+ drawCalls: number;
+ triangles: number;
+ sprites: number;
+ text: number;
+ spine: number;
+ meshes: number;
+ culled: number;
+}
+declare function defaultFrameStats(): FrameStats;
+declare const Stats: ResourceDef<FrameStats>;
+declare class StatsCollector {
+ private deltas_;
+ private cursor_;
+ private count_;
+ private sum_;
+ pushFrame(deltaSeconds: number): void;
+ getFps(): number;
+ getFrameTimeMs(): number;
+}
+interface StatsPluginOptions {
+ overlay?: boolean;
+ position?: StatsPosition;
+ container?: HTMLElement;
+}
+declare class StatsPlugin implements Plugin {
+ readonly name = "Stats";
+ private collector_;
+ private overlay_;
+ private options_;
+ constructor(options?: StatsPluginOptions);
+ build(app: App): void;
+ cleanup(): void;
}
+declare const statsPlugin: StatsPlugin;
/**
* @file playableRuntime.ts
@@ -3667,5 +3724,5 @@ declare const uiPlugins: Plugin[];
declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;
-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 };
+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, Stats, StatsCollector, StatsOverlay, StatsPlugin, 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, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, 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, statsPlugin, 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, AudioBackendInitOptions, 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, FrameStats, 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, StatsPluginOptions, StatsPosition, 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 };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index b640bad92..d74d35543 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 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,_=1080,g=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 V(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 N(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)??N(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:_},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}),_e=Y("Name",{value:""}),ge=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 Ve(e){return{_filterType:"added",_component:e}}function Ne(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=[],o=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),Ge(e)?i.push({index:t,component:e._component}):qe(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 _t(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function gt(e){_t().push({schedule:dt.Update,system:e})}function yt(e){_t().push({schedule:dt.Startup,system:e})}function wt(e,t){_t().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 Vt(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Nt(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 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,this.bgmVolume_=1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}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})}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),this.createPendingHandle())}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,this.bgmVolume_):this.bgmHandle_&&this.bgmHandle_.stop();const n=t?.volume??1;this.bgmVolume_=n;const s=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:s?0:n,loop:!0}),s&&this.fadeIn(this.bgmHandle_,s,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else 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 dispose(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}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?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}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,tn.bgmVolume_=1,tn.fadeAnimId_=0;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,_e,{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),_n(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=Vt(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);qt(Nt(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 _n(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 gn(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([_e]);for(const s of n){const n=e.get(s,_e);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),Vn(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 Vn(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 Hn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Gn=Pe(null,"Prefabs");class qn{constructor(){this.name="PrefabsPlugin",this.dependencies=[$n]}build(e){const t=e.getResource($n);e.insertResource(Gn,new Nn(e.world,t))}}const Kn=new qn;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,_s=0,gs=0,ys=0;function ws(e){ms=e,_s=ms._malloc(262144),gs=ms._malloc(65536),ys=ms._malloc(256)}function xs(){ms&&(_s&&ms._free(_s),gs&&ms._free(gs),ys&&ms._free(ys),_s=0,gs=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,_s/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,_s,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,gs,s).set(e.indices),t.geometry_setIndices16(n,gs,s)}else{new Uint32Array(t.HEAPU8.buffer,gs,s).set(e.indices),t.geometry_setIndices32(n,gs,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,_s/4),s.geometry_updateVertices(e,_s,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,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),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,ge)){const n=this.app_.world.get(e,ge);n.persistent=t,this.app_.world.insert(e,ge,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,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())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,ge,{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 Vs=mt([Ee(js),Te(Ae)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ns={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,Vs)}};class Gs{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 Gs}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 qs(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,ge);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,_;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,_=p+i.y):(p=h+n.y,_=d+s.y);const g=Math.max(0,m-f),y=Math.max(0,_-p);return{originX:f+r.x*g,originY:p+r.y*y,width:g,height:y,rect:{left:f,bottom:p,right:m,top:_}}}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 _i(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 gi(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),_=Math.round(255*e.color.g),g=Math.round(255*e.color.b),y=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${_}, ${g}, ${y})`,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 Vi(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],_=e[13],g=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*_-d*m,T=h*g-f*m,E=h*y-p*m,C=d*g-f*_,R=d*y-p*_,A=f*y-p*g;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]=(_*M-g*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]=(g*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-_*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]=(_*x-m*b-g*w)*I,n[15]=(h*b-d*x+f*w)*I),n}function Ni(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 Gi(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 qi(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=qi(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-n,p=t-s,m=f*d-p*h+n,_=f*h+p*d+s;return m>=n-i*r&&m<=n+i*(1-r)&&_>=s-o*a&&_<=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,_=c*(1-f),g=-u*p,y=u*(1-p),w=qi(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-g*v,d+m*v+g*x],[h+_*x-g*v,d+_*v+g*x],[h+_*x-y*v,d+_*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 _o(e){ho=e}function go(){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&&(Vi(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()&&!go())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=Ni(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),_=e.isMouseButtonReleased(0);n.uiHitTest_update(s,d.x,d.y,p,m,_);const g=n.uiHitTest_getHitEntity(),y=4294967295===g?null:g;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(_&&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()&&!go())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 _=()=>{l||null===m()||v()},g=()=>{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",_),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",_),p.removeEventListener("compositionstart",g),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 _=Math.ceil(1.2*l.fontSize),g=l.padding;if(l.multiline){const e=vi(o,p,u-2*g);let t=g;for(const n of e)o.fillText(n,g,t),t+=_}else{const e=(h-l.fontSize)/2;o.fillText(p,g,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*g);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=g+o.measureText(c).width,n=g+r*_,s=_}else t=g+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()||go()){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()&&!go())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=qi(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 Vo(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 No(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 Go=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()&&!go(),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),_=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=Vo(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=Vo(l.scrollY,0,_,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=Vo(l.scrollY,0,_,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Vo(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>_;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=No(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:_,t=No(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,_)),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,_+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"]})}},qo=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=qi(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,_=-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-_)/a:0;case ci.TopToBottom:return a>0?1-(p-_)/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()||go()){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()&&!go())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()&&!go();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,_e,{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,_e,{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()&&!go(),p=t.getEntitiesWithComponents([cr]);for(const m of p){const p=t.get(m,cr);let _=n.get(m);if(_||(_={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,_)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Ci(t,m,no,{enabled:!0,blockRaycast:!0});const g=t.has(m,so)?t.get(m,so):null;if(g?.justPressed&&(p.isOpen?r(m,p,_):o(m,p,_)),p.isOpen){for(let e=0;e<_.optionEntities.length;e++){const n=_.optionEntities[e];if(!t.valid(n)||!t.has(n,so))continue;if(t.get(n,so).justPressed){a(m,p,_,e,c);break}}let n=-1;for(let e=0;e<_.optionEntities.length;e++){const s=_.optionEntities[e];if(!t.valid(s)||!t.has(s,so))continue;if(t.get(s,so).hovered){n=e;break}}n>=0&&n!==_.highlightIndex&&(_.highlightIndex=n,h(_)),e.isKeyPressed("ArrowDown")?(_.highlightIndex>=p.options.length-1?_.highlightIndex=0:_.highlightIndex++,h(_)):e.isKeyPressed("ArrowUp")?(_.highlightIndex<=0?_.highlightIndex=p.options.length-1:_.highlightIndex--,h(_)):e.isKeyPressed("Enter")&&_.highlightIndex>=0?a(m,p,_,_.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,_),e.isMouseButtonPressed(0)&&(g?.hovered||d(_)||r(m,p,_))}}},{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?(_=-l*r+u.left+d+p*i,g=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)):(_=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,g=(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=_,y.position.y=g,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 _r{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(dt.PostUpdate,mt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const gr=new _r;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,_=a*f,g=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(g+w))*i,(m+b)*i,(_-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(_+v)*r,(y-x)*r,(1-(p+g))*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,ge,{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],_=new Float32Array(n.HEAPF32.buffer,c,8*i),g=new Uint16Array(n.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(g),t.renderer_submitTriangles(y,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 Vr(e,t,n){Wr.warn(e,t,n)}function Nr(e,t,n){Wr.error(e,t,n)}const Gr={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},qr={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??Gr.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_=Math.max(0,Math.min(1,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.activeCount_=0,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,this.activeCount_++,t}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0,this.activeCount_--}}get activeCount(){return this.activeCount_}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:{const e=i-s;if(e<=0)return 1;return 1-(Math.min(Math.max(r,s),i)-s)/e}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}),_a=Y("AudioListener",{enabled:!0});class ga{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}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,this.resumeHandler_=null}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),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}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);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new ga(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),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(),n=this.config_;t instanceof ya?t.initialize({initialPoolSize:n.initialPoolSize}):t.initialize();let s=null;t instanceof ya&&(s=t.mixer),tn.init(t,s),s&&(void 0!==n.masterVolume&&(s.master.volume=n.masterVolume),void 0!==n.musicVolume&&(s.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(s.sfx.volume=n.sfxVolume));const i=new Map;e.addSystemToSchedule(dt.PreUpdate,mt([Te(Ae)],n=>{const s=e.world;let o=0,r=0;const a=s.getEntitiesWithComponents([_a,ae]);for(const e of a){if(s.get(e,_a).enabled){const t=s.get(e,ae);o=t.position.x,r=t.position.y;break}}const l=s.getEntitiesWithComponents([ma,ae]),c=new Set;for(const e of l){const n=s.get(e,ma);if(!n.enabled||!n.clip)continue;c.add(e);const a=s.get(e,ae);if(n.playOnAwake&&!i.has(e)){const s=tn.getBufferHandle(n.clip);if(s){const o=t.play(s,{bus:n.bus,volume:n.volume,loop:n.loop,playbackRate:n.pitch,priority:n.priority});i.set(e,o)}else console.warn(`[AudioPlugin] playOnAwake: clip "${n.clip}" not preloaded`)}if(n.spatial&&i.has(e)){const t=i.get(e);if(!t.isPlaying){i.delete(e);continue}const s=a.position.x-o,l=a.position.y-r,c=fa(Math.sqrt(s*s+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)}}for(const[e,t]of i)c.has(e)&&t.isPlaying||i.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){tn.dispose()}}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)),qs(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;gn(t.world,h),t.run()}const Ea=[Wi,to,co,Fo,Wo,vo,jo,Go,er,Uo,Eo,tr,ir,lr,ur,mr,gr],Ca=[...Ea,aa];function Ra(e,t){return function(e,t){const n=Gs.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(Ns),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ca,...t})}e=p;export{Ve as Added,ra as AnimationPlugin,Gs 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,_a 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,Ne as Changed,fe as Children,ve as CircleCollider,se as ClearFlags,nt as Commands,it as CommandsInstance,_ 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,g 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,Gr 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,_e as Name,de as Parent,Tr as Physics,xr as PhysicsEvents,Mr as PhysicsPlugin,Es as PostProcess,Nn as PrefabServer,Gn as Prefabs,qn 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,ge as SceneOwner,dt as Schedule,Yo as ScrollView,Xt as ShaderSources,Ko as Slider,qo 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,qr 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,_r as UIRenderOrderPlugin,he as Velocity,Br as WebAssetProvider,Xe as World,ae as WorldTransform,yt as addStartupSystem,gt 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,G as clearUserComponents,L as color,mi as computeFillAnchors,gi as computeFillSize,_i 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,V as defineTag,Nr as error,Vt as extractAnimClipTexturePaths,yn as findEntityByName,qs 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,N 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,Vi as invertMatrix4,J as isBuiltinComponent,Bn as isCustomExtension,po as isEditor,Cn as isKnownAssetExtension,n as isPlatformInitialized,go as isPlayMode,mo as isRuntime,Et as isTextureRef,i as isWeChat,o as isWeb,_n as loadComponent,wr as loadPhysicsModule,kr as loadRuntimeScene,fn as loadSceneData,pn as loadSceneWithAssets,An as looksLikeAssetPath,Nt as parseAnimClipData,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Ji as pointInOBB,Gi as pointInWorldRect,Kn as prefabsPlugin,Wo as progressBarPlugin,O as quat,qt as registerAnimClip,Z as registerComponent,sn as registerComponentAssetFields,cn as registerComponentEntityFields,hs as registerDrawCallback,Wn as registerEmbeddedAssets,Ht as registerMaterialCallback,hn as remapEntityFields,Ns as sceneManagerPlugin,Ni as screenToWorld,fo as setEditorMode,ar as setListViewRenderer,Xr as setLogLevel,_o 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,gr as uiRenderOrderPlugin,Kt as unregisterAnimClip,q as unregisterComponent,ds as unregisterDrawCallback,gn as updateCameraAspectRatio,U as vec2,$ as vec3,D as vec4,Vr as warn,Ys 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 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}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,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 p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(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 p(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 g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,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,this.activeCount_++,t}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,e.priority=0,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class _{constructor(e,t,n,s,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=n,this.poolNode_=s,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new g(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),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}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);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new _(l,i,n,s,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.context_?.close(),this.context_=null}}const w=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)}},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",o),n.addEventListener("mousedown",r),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",o),n.removeEventListener("mousedown",r),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)}createAudioBackend(){return new y}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},P="Arial",T=24,E=1.2,C=.5,R=1/60,A={x:0,y:-9.81},I=1/60,k="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function U(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.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&&(F.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight)}const $=0,D=4294967295,L=4294967295,O=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),X=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),j=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Y=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function V(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(V);const t={};for(const n in e)t[n]=V(e[n]);return t}let N=0;function G(e,t){const n=++N,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?{...V(t),...e}:V(t):e?{...t,...e}:{...t}}}function q(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const n=se.get(e)??q().get(e);if(n)return n;const s=G(e,t);return q().set(e,s),se.set(e,s),te(e,t,!1),s}function J(e){const t=se.get(e)??q().get(e);if(t)return t;const n=G(e,{});return q().set(e,n),se.set(e,n),te(e,{},!0),n}function Q(e){return q().get(e)}function Z(){const e=q();for(const t of e.keys())se.delete(t);e.clear()}function ee(e){q().delete(e),se.delete(e)}function te(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ne(e){return!0===e._builtin}const se=new Map;function ie(e,t){se.set(e,t)}function oe(e){return se.get(e)??Q(e)}function re(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return se.set(e,n),n}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},de=re("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}}),he=de,ue=de,fe=re("Sprite",{texture:D,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}),pe=re("Camera",{projectionType:ae.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:le.ColorAndDepth}),me=re("Canvas",{designResolution:{x:x,y:v},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ge=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),_e=re("Parent",{entity:0}),ye=re("Children",{entities:[]}),we=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:L,enabled:!0}),xe=re("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=K("Name",{value:""}),be=K("SceneOwner",{scene:"",persistent:!1});function Se(e){const t=oe(e);return t?V(t._default):null}const Me=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Pe=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Te=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ce={Static:0,Kinematic:1,Dynamic:2};let Re=0;function Ae(e,t){const n=++Re;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Ie(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Fe{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 Be{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 Fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const ze=Ae({delta:0,elapsed:0,frameCount:0},"Time");function Ue(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=$e(t[e]),o=$e(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(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 Le=null;function Oe(e){Le=e}function We(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(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 Xe=1;const je=new WeakMap;function Ye(e){let t=je.get(e);return void 0===t&&(t=Xe++,je.set(e,t)),t}const Ve=[];function Ne(e,t=[],n=[]){Ve.length=0;for(const t of e)Ve.push(Ye(t));Ve.sort((e,t)=>e-t);let s=Ve.join(",");if(t.length>0){Ve.length=0;for(const e of t)Ve.push(Ye(e));Ve.sort((e,t)=>e-t),s+="|+"+Ve.join(",")}if(n.length>0){Ve.length=0;for(const e of n)Ve.push(Ye(e));Ve.sort((e,t)=>e-t),s+="|-"+Ve.join(",")}return s}class Ge{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 We(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){We(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){We(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){We(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ne(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ne(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(n))}catch(n){We(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 ne(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ne(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ne(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return We(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.");ne(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=Ue(t._name,t._default,s);if(e.length>0)throw new Error(De(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,He(i))}catch(n){We(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 We(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 We(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){We(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=Ue(t._name,t._default,e);if(i.length>0)throw new Error(De(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 se)if(ne(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=q();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??Ne(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(!ne(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 qe(e){return{_type:"mut",_component:e}}function Ke(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Je(e){return{_filterType:"added",_component:e}}function Qe(e){return{_filterType:"changed",_component:e}}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Ke(e)||Ze(e)||et(e)?e._component:e}function nt(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Ke(e)&&s.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>nt(e,[...t,...s],n),without:(...s)=>nt(e,t,[...n,...s])}}function st(...e){return nt(e)}class it{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(tt),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_=Ne(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 d of n)if(!o||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)}r[0]=d;for(let e=0;e<s;e++)r[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=d}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 ot(e){return{_type:"removed",_component:e}}class rt{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 at(){return{_type:"commands"}}class lt{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=ne(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 ct{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new lt(this,null);return this.spawned_.push(e),e}entity(e){return new lt(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 dt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class ht{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 ut{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new ht)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new ht,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function ft(e){return{_type:"event_writer",_event:e}}function pt(e){return{_type:"event_reader",_event:e}}class mt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class gt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var _t;function yt(){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"}(_t||(_t={}));let wt=0;function xt(e,t,n){const s=++wt;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 bt(e){vt().push({schedule:_t.Update,system:e})}function St(e){vt().push({schedule:_t.Startup,system:e})}function Mt(e,t){vt().push({schedule:e,system:t})}class Pt{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}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]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof ct&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(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 ct(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 mt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new gt(n)}case"removed":{const t=e;return new rt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Tt{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 Et=Ae(new Tt,"Input");class Ct{constructor(e){this.target_=e??null}build(e){const n=new Tt;e.insertResource(Et,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(_t.Last,xt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Rt=new Ct,At=Ae({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 It;function kt(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"}(It||(It={}));let Ft=null,Bt=null,zt=1;const Ut=new Map;function $t(e){Ft=e,Bt=e.getResourceManager(),Nt()}function Dt(){0!==Ht&&Ft&&(Ft._free(Ht),Ht=0),Ut.clear(),zt=1,Wt=!1,jt.clear(),Yt=null,Bt=null,Ft=null}function Lt(){if(!Bt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Bt}const Ot={createShader:(e,t)=>Lt().createShader(e,t),releaseShader(e){e>0&&Lt().releaseShader(e)},create(e){const t=zt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??It.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 Ut.set(t,n),t},get:e=>Ut.get(e),setUniform(e,t,n){const s=Ut.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Ft?.invalidateMaterialCache(e))},getUniform(e,t){const n=Ut.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ut.get(e);n&&(n.blendMode=t,Ft?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ut.get(e);return t?.blendMode??It.Normal},setDepthTest(e,t){const n=Ut.get(e);n&&(n.depthTest=t,Ft?.invalidateMaterialCache(e))},getShader(e){const t=Ut.get(e);return t?.shader??0},release(e){Ut.delete(e),Ft?.invalidateMaterialCache(e)},isValid:e=>Ut.has(e),releaseAll(){Ut.clear(),Ft?.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??It.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ut.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=zt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ut.set(n,s),n},toAssetData(e,t){const n=Ut.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=Ut.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Wt=!1,Ht=0;const Xt=16384,jt=new Map;let Yt=null;function Vt(e){const t=(0===Ht&&Ft&&(Ht=Ft._malloc(Xt)),Ht);if(0===t||!Ft)return{ptr:0,count:0};let n=0,s=0;const i=Ft.HEAPU8,o=Ft.HEAPU32,r=Ft.HEAPF32;for(const[a,l]of e){if(kt(l))continue;let e=jt.get(a);e||(Yt||(Yt=new TextEncoder),e=Yt.encode(a),jt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>Xt){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Xt} bytes), skipping remaining uniforms`);break}o[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]);o[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Nt(){if(!Ft||Wt)return;Ft.materialDataProvider=(e,t,n,s,i)=>{const o=Ut.get(e);if(!o)return Ft.HEAPU32[t>>2]=0,Ft.HEAPU32[n>>2]=0,Ft.HEAPU32[s>>2]=0,void(Ft.HEAPU32[i>>2]=0);Ft.HEAPU32[t>>2]=o.shader,Ft.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Vt(o.uniforms);Ft.HEAPU32[s>>2]=r,Ft.HEAPU32[i>>2]=a},Wt=!0}const Gt={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 qt{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 Kt{constructor(e,t=""){this.cache_=new qt,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&&(Ot.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ot.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:Ot.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function Jt(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Qt(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 Zt=new Map;function en(e){Zt.set(e.name,e)}function tn(e){Zt.delete(e)}function nn(e){return Zt.get(e)}function sn(){Zt.clear()}const on=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function rn(e,t){const n=e.getEntitiesWithComponents([on]);for(const s of n){const n=e.get(s,on);if(!n.enabled||!n.playing||!n.clip)continue;const i=Zt.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,fe)){const t=i.frames[n.currentFrame],o=e.get(s,fe);o.texture=t.texture,e.insert(s,fe,o)}a&&e.insert(s,on,n)}}class an{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}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})}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),this.createPendingHandle())}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,this.bgmVolume_):this.bgmHandle_&&this.bgmHandle_.stop();const n=t?.volume??1;this.bgmVolume_=n;const s=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:s?0:n,loop:!0}),s&&this.fadeIn(this.bgmHandle_,s,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else 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 dispose(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}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?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createPendingHandle(){return{id:-1,stop(){},pause(){},resume(){},setVolume(){},setPan(){},setLoop(){},setPlaybackRate(){},isPlaying:!1,currentTime:0,duration:0}}}an.mixer_=null,an.bufferCache_=new Map,an.bgmHandle_=null,an.bgmVolume_=1,an.fadeAnimId_=0;const ln=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 cn(e,t){ln.set(e,t)}function dn(e){const t=ln.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 hn(e){return ln.get(e)?.fields??[]}function un(e){return ln.get(e)?.spine??null}const fn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function pn(e,t){fn.set(e,t)}function mn(e){return fn.get(e)}function gn(e,t){const n=fn.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 _n(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)gn(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 yn(e,t){return _n(e,t)}async function wn(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 xn.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=ln.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=[...xn.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),d=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,...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=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=ln.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=_n(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 xn=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=Jt(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);en(Qt(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 an.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=oe(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 bn(e,t){const n=e.getEntitiesWithComponents([pe]);for(const s of n){const n=e.get(s,pe);n&&(n.aspectRatio=t,e.insert(s,pe,n))}}function Sn(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}const Mn=[{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}],Pn={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"},Tn=new Map,En=new Set;for(const e of Mn)for(const t of e.extensions)Tn.set(t,e),En.add(t);function Cn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Rn(e){return Tn.get(Cn(e))}function An(e){return Rn(e)?.editorType??"unknown"}function In(e){return Rn(e)?.addressableType??null}function kn(e){for(const t of Mn)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Fn(e){return En.has(e.toLowerCase())}function Bn(){return En}function zn(e){return"string"==typeof e&&(!!e.includes("/")&&Fn(Cn(e)))}function Un(){const e=[];for(const t of Mn)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function $n(){return Un().map(e=>({type:"suffix",value:e}))}function Dn(e){return Pn[e.toLowerCase()]}function Ln(e){const t=Rn(e);return t?.wechatPackInclude??!1}function On(e){const t=Rn(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 Wn{constructor(e){this.textureCache_=new qt,this.shaderCache_=new qt,this.jsonCache_=new qt,this.textCache_=new qt,this.binaryCache_=new qt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new qt,this.prefabCache_=new qt,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(F.textCanvasSize,F.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 Kt(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(),Ot.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),d="binary"===Rn(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,o,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=Rn(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 dn(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=un(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 wn(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 Ot.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 Ot.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(On(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 Hn=Ae(null,"Assets");class Xn{build(e){const t=e.wasmModule;t?e.insertResource(Hn,new Wn(t)):console.warn("AssetPlugin: No WASM module available")}}const jn=new Xn;class Yn{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 Vn(e,t){const n=e.getResource(Hn);n&&n.registerEmbeddedAssets(t)}async function Nn(e,t,n){const{entities:s,rootId:i}=await qn(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 wn(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 Gn=10;async function qn(e,t,n,s,i,o=0){if(o>Gn)throw new Error(`Prefab nesting depth exceeded ${Gn}. 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 qn(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),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?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};Kn(h.components,r),Jn(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 Kn(e,t){for(const n of e){const e=mn(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 Jn(e,t){for(const n of t)if(n.prefabEntityId===e.prefabEntityId)switch(n.type){case"property":if(n.componentType&&void 0!==n.propertyName){const t=e.components.find(e=>e.type===n.componentType);t&&(t.data[n.propertyName]=n.value)}break;case"name":"string"==typeof n.value&&(e.name=n.value);break;case"visibility":"boolean"==typeof n.value&&(e.visible=n.value);break;case"component_added":if(n.componentData){e.components.some(e=>e.type===n.componentData.type)||e.components.push({type:n.componentData.type,data:JSON.parse(JSON.stringify(n.componentData.data))})}break;case"component_removed":n.componentType&&(e.components=e.components.filter(e=>e.type!==n.componentType))}}class Qn{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 Nn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Zn=Ae(null,"Prefabs");class es{constructor(){this.name="PrefabsPlugin",this.dependencies=[Hn]}build(e){const t=e.getResource(Hn);e.insertResource(Zn,new Qn(e.world,t))}}const ts=new es;let ns=null,ss=0,is=0,os=0;const rs=new Float32Array(256);function as(e){ns=e,ss=ns._malloc(64),is=ns._malloc(64),os=ns._malloc(1024)}function ls(){ns&&(ss&&(ns._free(ss),ss=0),is&&(ns._free(is),is=0),os&&(ns._free(os),os=0)),ns=null}function cs(){if(!ns)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ns}const ds={r:1,g:1,b:1,a:1},hs={begin(e){const t=cs();try{t.HEAPF32.set(e,ss/4),t.draw_begin(ss)}catch(e){We(e,"Draw.begin")}},end(){try{cs().draw_end()}catch(e){We(e,"Draw.end")}},line(e,t,n,s=1){try{cs().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){We(e,"Draw.line")}},rect(e,t,n,s=!0){try{cs().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){We(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{cs().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){We(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{cs().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){We(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{cs().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){We(e,"Draw.circleOutline")}},texture(e,t,n,s=ds){try{cs().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){We(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ds){try{cs().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){We(e,"Draw.textureRotated")}},setLayer(e){cs().draw_setLayer(e)},setDepth(e){cs().draw_setDepth(e)},getDrawCallCount:()=>ns?ns.draw_getDrawCallCount():0,getPrimitiveCount:()=>ns?ns.draw_getPrimitiveCount():0,setBlendMode(e){cs().draw_setBlendMode(e)},setDepthTest(e){cs().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=cs();s.HEAPF32.set(n,is/4),s.draw_mesh(e,t,is)}catch(n){We(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=cs(),i=Ot.get(t);if(!i)return;if(hs.setBlendMode(i.blendMode),hs.setDepthTest(i.depthTest),0===i.uniforms.size)return void hs.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,is/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ps(t);if(!(s<0)){if(kt(n))rs[o++]=10,rs[o++]=s,rs[o++]=n.slot??e++,rs[o++]=n.textureId;else if("number"==typeof n)rs[o++]=1,rs[o++]=s,rs[o++]=n;else if(Array.isArray(n)){rs[o++]=n.length,rs[o++]=s;for(let e=0;e<n.length;e++)rs[o++]=n[e]}else"w"in n?(rs[o++]=4,rs[o++]=s,rs[o++]=n.x,rs[o++]=n.y,rs[o++]=n.z,rs[o++]=n.w):"z"in n?(rs[o++]=3,rs[o++]=s,rs[o++]=n.x,rs[o++]=n.y,rs[o++]=n.z):(rs[o++]=2,rs[o++]=s,rs[o++]=n.x,rs[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(rs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,is);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),os/4),s.draw_meshWithUniforms(e,i.shader,is,os,o)}catch(n){We(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},us={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},fs=new Set;function ps(e){const t=us[e];return void 0!==t?t:(fs.has(e)||(fs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(us).join(", ")}`)),-1)}const ms=new Map;function gs(e,t,n){ms.set(e,{fn:t,scene:n??""})}function _s(e){ms.delete(e)}function ys(){ms.clear()}var ws;!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"}(ws||(ws={}));let xs=null,vs=0,bs=0,Ss=0;function Ms(e){xs=e,vs=xs._malloc(262144),bs=xs._malloc(65536),Ss=xs._malloc(256)}function Ps(){xs&&(vs&&xs._free(vs),bs&&xs._free(bs),Ss&&xs._free(Ss),vs=0,bs=0,Ss=0),xs=null}function Ts(){if(!xs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return xs}const Es={create(e){const t=Ts(),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,vs/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,Ss,i).set(o),t.geometry_init(n,vs,s,Ss,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,bs,s).set(e.indices),t.geometry_setIndices16(n,bs,s)}else{new Uint32Array(t.HEAPU8.buffer,bs,s).set(e.indices),t.geometry_setIndices32(n,bs,s)}}return n},updateVertices(e,t,n=0){const s=Ts(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,vs/4),s.geometry_updateVertices(e,vs,i,n)},release(e){e>0&&Ts().geometry_release(e)},isValid:e=>!(!xs||e<=0)&&xs.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Es.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:ws.Float2},{name:"a_texCoord",type:ws.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 Es.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ws.Float2},{name:"a_texCoord",type:ws.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 Es.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:ws.Float2},{name:"a_texCoord",type:ws.Float2}],indices:new Uint16Array(r)})}};let Cs=null;function Rs(e){Cs=e}function As(){Cs&&ks.isInitialized()&&ks.shutdown(),Cs=null}function Is(){if(!Cs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Cs}const ks={init(e,t){try{return Is().postprocess_init(e,t)}catch(n){return We(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Is().postprocess_shutdown()}catch(e){We(e,"PostProcess.shutdown")}},resize(e,t){try{Is().postprocess_resize(e,t)}catch(n){We(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Is().postprocess_addPass(e,t)}catch(t){return We(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Is().postprocess_removePass(e)}catch(t){We(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Is().postprocess_setPassEnabled(e,t)}catch(t){We(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Is().postprocess_isPassEnabled(e)}catch(t){return We(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Is().postprocess_setUniformFloat(e,t,n)}catch(n){We(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Is().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){We(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Is().postprocess_begin()}catch(e){We(e,"PostProcess.begin")}},end(){try{Is().postprocess_end()}catch(e){We(e,"PostProcess.end")}},getPassCount(){try{return Is().postprocess_getPassCount()}catch(e){return We(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Cs)return!1;try{return Cs.postprocess_isInitialized()}catch(e){return We(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Is().postprocess_setBypass(e)}catch(e){We(e,"PostProcess.setBypass")}},isBypassed(){if(!Cs)return!0;try{return Cs.postprocess_isBypassed()}catch(e){return We(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ot.createShader(Fs,"#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:()=>Ot.createShader(Fs,"#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:()=>Ot.createShader(Fs,"#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:()=>Ot.createShader(Fs,"#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")},Fs="#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 Bs;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Bs||(Bs={}));let zs=null,Us=0;function $s(e){zs=e,Us=zs._malloc(64)}function Ds(){zs&&Us&&(zs._free(Us),Us=0),zs=null}const Ls={init(e,t){zs?.renderer_init(e,t)},resize(e,t){zs?.renderer_resize(e,t)},begin(e,t){if(zs&&Us)try{zs.HEAPF32.set(e,Us/4),zs.renderer_begin(Us,t??0)}catch(e){We(e,"Renderer.begin")}},flush(){try{zs?.renderer_flush()}catch(e){We(e,"Renderer.flush")}},end(){try{zs?.renderer_end()}catch(e){We(e,"Renderer.end")}},submitSprites(e){if(zs)try{zs.renderer_submitSprites(e._cpp)}catch(e){We(e,"Renderer.submitSprites")}},submitBitmapText(e){if(zs)try{zs.renderer_submitBitmapText(e._cpp)}catch(e){We(e,"Renderer.submitBitmapText")}},submitSpine(e){if(zs)try{zs.renderer_submitSpine?.(e._cpp)}catch(e){We(e,"Renderer.submitSpine")}},setStage(e){zs?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>zs?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){zs?.renderer_releaseTarget(e)},getTargetTexture:e=>zs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>zs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){zs?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){zs?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){zs?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){zs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>zs?zs.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>zs?{drawCalls:zs.renderer_getDrawCalls(),triangles:zs.renderer_getTriangles(),sprites:zs.renderer_getSprites(),text:zs.renderer_getText(),spine:zs.renderer_getSpine?.()??0,meshes:zs.renderer_getMeshes(),culled:zs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Os=null;function Ws(e){Os=e}function Hs(){Os=null}const Xs={enable(){Os?.gl_enableErrorCheck(!0)},disable(){Os?.gl_enableErrorCheck(!1)},check:e=>Os?.gl_checkErrors(e)??0,diagnose(){Os?.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:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(Ls.resize(s,i),ks.isInitialized()&&ks.getPassCount()>0&&ks.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Ls.setViewport(0,0,s,i),Ls.clearBuffers(3),Ls.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Ls.submitSprites(t),Ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ls.submitSpine(t),Ls.flush(),this.executeDrawCallbacks(n,o),Ls.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o}=e;Ls.setViewport(s.x,s.y,s.w,s.h),Ls.setScissor(s.x,s.y,s.w,s.h,!0),Ls.clearBuffers(i),Ls.setScissor(0,0,0,0,!1),Ls.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Ls.submitSprites(t),Ls.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ls.submitSpine(t),Ls.flush(),this.executeDrawCallbacks(n,o),Ls.end()}executeDrawCallbacks(e,t){const n=ms;if(n.size>0){hs.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)}hs.end();for(const e of s)_s(e)}}}const Ys="__scene_transition_overlay__";class Vs{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 Ns{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,be,{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),gs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=ks.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){ks.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,be)){const n=this.app_.world.get(e,be);n.persistent=t,this.app_.world.insert(e,be,n)}}}class Gs{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??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},gs(Ys,()=>{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;hs.setLayer(9999),hs.setDepth(9999),hs.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,_s(Ys),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,_s(Ys),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 Vs(t);this.scenes_.set(e,n);const s=new Ns(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Hn)?this.app_.getResource(Hn):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 Vs(t);this.scenes_.set(e,n);const s=new Ns(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Hn)?this.app_.getResource(Hn):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,be)){if(this.app_.world.get(e,be).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())_s(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{ks.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(Hn)&&(i.assetServer=this.app_.getResource(Hn));const o=await wn(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,be,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Ks(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(Hn)?this.app_.getResource(Hn):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)Ot.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,fe)){const t=n.get(e,fe);s.sprite=t.color.a,t.color.a=0,n.insert(e,fe,t),i=!0}if(n.has(e,xe)){const t=n.get(e,xe);s.spine=t.color.a,t.color.a=0,n.insert(e,xe,t),i=!0}if(n.has(e,we)){const t=n.get(e,we);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,we,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,fe)){const t=n.get(e,fe);t.color.a=s.sprite,n.insert(e,fe,t)}if(void 0!==s.spine&&n.has(e,xe)){const t=n.get(e,xe);t.color.a=s.spine,n.insert(e,xe,t)}if(void 0!==s.bitmapText&&n.has(e,we)){const t=n.get(e,we);t.color.a=s.bitmapText,n.insert(e,we,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{ks.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 qs=Ae(null,"SceneManager");function Ks(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(qs).getSceneStatus(t)&&n._fn(...s)}}}const Js=xt([ke(qs),Ie(ze)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Qs={name:"SceneManager",build(e){const t=new Gs(e);e.insertResource(qs,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(qs),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(_t.Startup,n),e.addSystemToSchedule(_t.Last,Js)}};class Zs{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 ut,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,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(_t.Last);else{this.runSchedule(_t.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(_t.FixedPreUpdate),this.runSchedule(_t.FixedUpdate),this.runSchedule(_t.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(_t.PreUpdate),this.runSchedule(_t.Update),this.runSchedule(_t.PostUpdate),this.runSchedule(_t.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ge,this.resources_=new Be;for(const e of Object.values(_t))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Zs}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(_t.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(_t.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 Oe(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_}enableStats(){return this.statsEnabled_=!0,this}getSystemTimings(){return this.runner_?.getTimings()??null}getEntityCount(){return this.world_.entityCount()}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(qs).register(e),this}setInitialScene(e){return this.getResource(qs).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(ze)||this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(_t.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(_t.Last);else{this.runSchedule(_t.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(_t.FixedPreUpdate),this.runSchedule(_t.FixedUpdate),this.runSchedule(_t.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(_t.PreUpdate),this.runSchedule(_t.Update),this.runSchedule(_t.PostUpdate),this.runSchedule(_t.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Pt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(ze,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(_t.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,ys();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=[Hs,Ds,As,Ps,Dt,ls];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(ze);t.delta=e,t.elapsed+=e,t.frameCount++}}function ei(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 ti=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ni(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case ce.FixedWidth:return o;case ce.FixedHeight:return r;case ce.Expand:return Math.max(o,r);case ce.Shrink:return Math.min(o,r);case ce.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const si=[];function ii(e){if(e<si.length)return si[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 si.push(t),t}function oi(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,be);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,d=0,h=0;if(i.projectionType===ae.Orthographic){if(h=i.orthoSize,l){h=ni(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}d=h*r,a=ai(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=ci(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const u=hi(o.position.x,o.position.y,o.position.z),f=ii(c.length);f.entity=e,f.viewProjection.set(fi(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=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ri=new Float32Array(16);function ai(e,t,n,s,i,o){const r=ri;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 li=new Float32Array(16);function ci(e,t,n,s){const i=li;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 di=new Float32Array(16);function hi(e,t,n){const s=di;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 ui=new Float32Array(16);function fi(e,t){const n=ui;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 pi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function mi(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,d=o.left+t.x*a,h=o.bottom+e.y*l,u=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=d+s.x),e.y===t.y?(p=h+n.y-i.y*r.y,g=p+i.y):(p=h+n.y,g=u+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 gi=re("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 _i=null,yi=null;function wi(e,t){e.has(t,fe)||e.insert(t,fe,{texture:D,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 xi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case pi.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 vi(e,t){switch(e){case pi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case pi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case pi.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 bi(e,t,n,s){switch(e){case pi.BottomToTop:case pi.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Si(e,t,n,s){if(!e.has(t,gi))return;const i=e.get(t,gi),o=xi(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,gi,i)}function Mi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Pi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ti(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(Pi(r.charCodeAt(0))&&s.length>0&&Pi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Pi(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 Ei(e){let t=1;for(;t<e;)t*=2;return t}function Ci(e,t){let n=0,s=t;for(;e.has(s,_e);){const t=e.get(s,_e).entity;if(!e.valid(t))break;n++,s=t}return n}function Ri(e,t){if(_i&&yi){const e=_i.getUIRectComputedWidth(yi,t);if(e>0)return e}return e.size.x}function Ai(e,t){if(_i&&yi){const e=_i.getUIRectComputedHeight(yi,t);if(e>0)return e}return e.size.y}function Ii(e,t,n,s,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(n){case pi.BottomToTop:case pi.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,fe,r))}function ki(e,t,n){let s=t;for(;e.has(s,_e);){const t=e.get(s,_e).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Fi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Bi(e,t,n,s,i){if(!e.has(t,gi))return;const o=e.get(t,gi),r=mi(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,fe)){const n=e.get(t,fe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,fe,n))}if(e.has(t,de)){const n=e.get(t,de);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,de,n)}}function zi(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 Ui=.1,$i=30,Di={r:.3,g:.5,b:.8,a:1},Li={Left:0,Center:1,Right:2},Oi={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Hi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Li.Left,verticalAlign:Oi.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Xi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(F.textCanvasSize,F.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,Ei(this.frameMaxW_)),e.height=Math.max(e.height,Ei(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ei(this.frameMaxW_),e.height=Ei(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=Ti(n,e.content,a?o: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(o):h+2*d,p=i?Math.ceil(r):u+2*d;if(i&&e.overflow===Wi.Ellipsis&&u>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,Ei(f)),s.height=Math.max(s.height,Ei(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===Wi.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 Oi.Top:x=d;break;case Oi.Middle:x=d+(p-2*d-w)/2;break;case Oi.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 Li.Left:s=d;break;case Li.Center:s=f/2;break;case Li.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Wi.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 Li.Left:return"left";case Li.Center:return"center";case Li.Right:return"right"}}}const ji=zi({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?Ri(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ai(e.uiRect,e.entity):0});class Yi{build(e){ie("Text",Hi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Xi(t),s=e.world,i=new Map;e.addSystemToSchedule(_t.PreUpdate,xt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Hi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Hi)){if(s.valid(e)&&s.has(e,fe)){const t=s.get(e,fe);s.insert(e,fe,{texture:D,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([Hi]);for(const t of e){const e=s.get(t,Hi),o=s.has(t,gi)?s.get(t,gi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ji.changed(a,r)){if(s.has(t,fe)&&s.get(t,fe).texture!==D)continue}wi(s,t);const l=o?{size:{x:Ri(o,t),y:Ai(o,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,fe);s.insert(t,fe,{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,ji.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Vi=new Yi,Ni=0,Gi=1,qi=re("UIMask",{enabled:!0,mode:Ni});function Ki(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 Ji(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],d=e[7],h=e[8],u=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*d-r*a,b=i*c-o*l,S=i*d-r*l,M=o*d-r*c,P=h*g-u*m,T=h*_-f*m,E=h*y-p*m,C=u*_-f*g,R=u*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+d*C)*I,n[1]=(o*R-i*A-r*C)*I,n[2]=(g*M-_*S+y*b)*I,n[3]=(f*S-u*M-p*b)*I,n[4]=(c*E-a*A-d*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+d*P)*I,n[9]=(i*E-s*R-r*P)*I,n[10]=(m*S-g*v+y*w)*I,n[11]=(u*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-u*x+f*w)*I),n}function Qi(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],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 Zi(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 eo(e,t){return 2*Math.atan2(e,t)}function to(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 no(e,t,n,s,i,o,r,a,l,c){const d=eo(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,m=f*u-p*h+n,g=f*h+p*u+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function so(e,t,n,s,i,o,r){if(!e.has(t,gi)||!e.has(t,de))return null;const a=e.get(t,gi),l=e.get(t,de),c=Ri(a,t)*l.worldScale.x,d=Ai(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-d*p,y=d*(1-p),w=eo(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-_*v,u+m*v+_*x],[h+g*x-_*v,u+g*v+_*x],[h+g*x-y*v,u+g*v+y*x],[h+m*x-y*v,u+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]=to(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 io(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([qi]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,qi);n.enabled&&(h.add(e),n.mode===Gi?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const d=[];for(const e of s){let n=!0;ki(t,e,e=>{if(i.has(e)){if(t.get(e,qi).mode===Ni)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,qi).mode===Ni){const e=so(t,n,o,r,a,l,c);e&&(s=Ki(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=so(t,e,o,r,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,o,r,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;ki(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),d(t,s)}function d(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),d(t,s)}for(const e of o){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 oo{build(e){if(ie("UIMask",qi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(io(e.wasmModule,e.world))}}const ro=new oo,ao=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),lo=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),co={Normal:0,Hovered:1,Pressed:2,Disabled:3},ho=K("Button",{state:co.Normal,transition:null});class uo{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 fo=Ae(new uo,"UIEvents");class po{build(e){ie("UIRect",gi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){_i=e,yi=t}(n,s);e.addSystemToSchedule(_t.PreUpdate,xt([Ie(At)],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(_t.PostUpdate,xt([Ie(At)],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(_t.PostUpdate,xt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const mo=new po;let go=!1,_o=!1;function yo(e){go=e}function wo(){return go}function xo(){return!go}function vo(e){_o=e}function bo(){return _o}const So=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&&(Ji(t,e),n=!1),e)}}();function Mo(e,t,n,s){t.emit(n,s,n),ki(e,n,i=>{if(!e.has(i,ao))return!1;const o=e.get(i,ao);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Po{build(e){ie("Interactable",ao),ie("Button",ho);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new uo;e.insertResource(fo,i);let o=null,r=null;e.addSystemToSchedule(_t.PreUpdate,xt([Ie(Et),Ie(At)],(e,a)=>{if(i.drain(),wo()&&!bo())return;const l=t.getEntitiesWithComponents([lo]);for(const e of l){const n=t.get(e,lo);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,lo,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;So.update(a.viewProjection);const u=Qi(d,h,So.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.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,lo)){const e=t.get(o,lo);e.hovered=!1,t.insert(o,lo,e),i.emit(o,"hover_exit")}if(null!==y){Fi(t,y,lo);const e=t.get(y,lo);e.hovered=!0,t.insert(y,lo,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,lo);e.pressed=!0,e.justPressed=!0,t.insert(y,lo,e),r=y,Mo(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,lo)){const e=t.get(r,lo);e.pressed=!1,e.justReleased=!0,t.insert(r,lo,e),Mo(t,i,r,"release"),r===o&&Mo(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(_t.Update,xt([],()=>{const e=t.getEntitiesWithComponents([ho]);for(const n of e){if(Fi(t,n,ao,{enabled:!0}),!t.has(n,lo))continue;const e=t.get(n,lo),s=t.get(n,ho),i=t.get(n,ao),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=co.Pressed:e.hovered?s.state=co.Hovered:s.state=co.Normal:s.state=co.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,fe)){const o=t.get(n,fe);o.color=Mi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,fe,o)}}},{name:"ButtonSystem"}))}}const To=new Po,Eo=K("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}),Co=K("Focusable",{tabIndex:0,isFocused:!1});class Ro{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 Ao=Ae(new Ro,"FocusManager");class Io{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Eo),wo()&&!bo())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(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=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 m(){const t=e.getResource(Ao);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Eo)?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,Eo);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(fo).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,Eo);s.focused=!1,s.dirty=!0;e.getResource(Ao).blur()}};function v(){const t=m();if(null===t)return;const s=n.get(t,Eo);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(fo).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,Eo);e.focused=!1,e.dirty=!0}e.getResource(Ao).blur(),p.blur()}function S(){c=!0,d=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,d,h){(i.width<d||i.height<h)&&(i.width=Ei(Math.max(i.width,d)),i.height=Ei(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,d,h),o.save(),o.beginPath(),o.rect(l.padding,0,d-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=Ti(o,p,d-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=Ti(o,l.value,d-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,d,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(d,h,r,w.length,1,!0);s.set(e,b);const S=n.get(e,fe);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,fe,S)}e.addSystemToSchedule(_t.Update,xt([Ie(Ao)],e=>{const t=n.getEntitiesWithComponents([Eo]);for(const e of t)Fi(n,e,Co,{tabIndex:0,isFocused:!1}),Fi(n,e,ao,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Eo)){const e=n.get(M,Eo);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Eo);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(_t.PreUpdate,xt([],()=>{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 o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(o,Eo).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Eo)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Eo,gi]);for(const e of a){const t=n.get(e,Eo);if(!t.dirty)continue;const s=n.get(e,gi),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(wi(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const ko=new Io,Fo={Simple:0,Sliced:1,Tiled:2,Filled:3},Bo={Horizontal:0,Vertical:1},zo={Left:0,Right:1,Bottom:2,Top:3},Uo=K("Image",{texture:D,color:{r:1,g:1,b:1,a:1},imageType:Fo.Simple,fillMethod:Bo.Horizontal,fillOrigin:zo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),$o=zi({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?Ri(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ai(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Do=new class{build(e){ie("Image",Uo);const t=e.world,n=new Map;e.addSystemToSchedule(_t.PreUpdate,xt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Uo)||n.delete(e);const e=t.getEntitiesWithComponents([Uo]);for(const s of e){const e=t.get(s,Uo),i=t.has(s,gi)?t.get(s,gi):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!$o.changed(r,o))continue;wi(t,s);const a=t.get(s,fe);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=Ri(i,s),a.size.y=Ai(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Fo.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Bo.Horizontal?e.fillOrigin===zo.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===zo.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===Fo.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,fe,a),n.set(s,$o.take(o))}else a.color.a=0,t.insert(s,fe,a),n.set(s,$o.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Lo=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Oo=K("ToggleGroup",{allowSwitchOff:!1});const Wo=new class{build(e){ie("Toggle",Lo),ie("ToggleGroup",Oo);const t=e.world,n=new Set;e.addSystemToSchedule(_t.Update,xt([Ie(fo)],e=>{const s=t.getEntitiesWithComponents([Lo]);if(!wo()||bo()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Lo);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Lo,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,Lo);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(Fi(t,n,ao,{enabled:!0}),!t.has(n,lo))continue;const s=t.get(n,lo),i=t.get(n,Lo),r=t.get(n,ao);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,Oo);if(i.isOn&&r){if(!t.get(s,Oo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Lo,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,Lo);i.isOn&&(i.isOn=!1,t.insert(s,Lo,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,fe)){const e=t.get(n,fe);e.color=Mi(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,fe,e)}}}for(const e of s){const n=t.get(e,Lo);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,fe)){const e=t.get(n.graphicEntity,fe);e.enabled=n.isOn,t.insert(n.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Ho=pi,Xo=K("ProgressBar",{value:0,fillEntity:0,direction:pi.LeftToRight});function jo(e,t,n,s){if(!e.has(t,gi))return;const i=e.get(t,gi),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=mi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const n=e.get(t,fe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,fe,n))}if(e.has(t,de)){const n=e.get(t,de),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,de,n))}}class Yo{build(e){ie("ProgressBar",Xo);const t=e.world;e.addSystemToSchedule(_t.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([Xo,gi]);for(const n of e){const e=t.get(n,Xo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,gi),i=Math.max(0,Math.min(1,e.value));Si(t,e.fillEntity,e.direction,i);const o=Ri(s,n),r=Ai(s,n);jo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Vo=new Yo,No=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Go=K("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 qo=new class{build(e){ie("Draggable",No),ie("DragState",Go);const t=e.world,n=e.getResource(fo);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(_t.PreUpdate,xt([Ie(Et),Ie(At)],(e,r)=>{if(wo()&&!bo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([No,lo]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,No).enabled)continue;if(t.get(s,lo).hovered){let e=0;t.has(s,fe)&&(e=t.get(s,fe).layer);const i=Ci(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,Go)||t.insert(n,Go);const e=t.get(n,Go),o=t.get(n,de);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,Go)){t.get(s,Go).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),d=t.get(s,No);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=d.dragThreshold){o=s,s=null;t.get(o,Go).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Go))return void(o=null);const s=t.get(o,Go),i=t.get(o,No),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,d=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,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(o,de)){const e=function(e,t,n,s){if(!e.has(t,_e))return{x:n,y:s};const i=e.get(t,_e).entity;if(!e.valid(i)||!e.has(i,de))return{x:n,y:s};const o=e.get(i,de),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=eo(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/r,y:(n*c+s*d)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,de);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,de,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Ko=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Jo(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 Qo(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,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-o*c)*a}}const Zo=new class{build(e){ie("ScrollView",Ko);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(_t.PostUpdate,xt([Ie(Et),Ie(At),Ie(ze)],(e,i,o)=>{const r=wo()&&!bo(),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([Ko,gi]);for(const o of l){Fi(t,o,qi,{enabled:!0,mode:Ni});const l=t.get(o,Ko),c=t.get(o,gi);let d=n.get(o);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,d));const h=Ri(c,o),u=Ai(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,ye)){const e=t.get(l.contentEntity,ye).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,de))continue;const e=t.get(r,de);let a=0,l=0,c=.5,d=.5;if(t.has(r,gi)){const e=t.get(r,gi);a=Ri(e,r)||e.size.x,l=Ai(e,r)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);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>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-u);if(!r&&i.valid){Fi(t,o,ao,{enabled:!0,blockRaycast:!0});const n=t.has(o,lo)?t.get(o,lo):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=Jo(l.scrollX,0,m,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=Jo(l.scrollY,0,g,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=Jo(l.scrollY,0,g,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Jo(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.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=Qo(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)<Ui&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ui?(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:g,t=Qo(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)<Ui&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ui?(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,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),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,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,de)){const e=t.get(l.contentEntity,de),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,de,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},er=pi,tr=K("Slider",{value:0,minValue:0,maxValue:1,direction:pi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function nr(e,t,n,s,i,o){const r=Ri(s,i)*n.worldScale.x,a=Ai(s,i)*n.worldScale.y,l=eo(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,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case pi.LeftToRight:return r>0?(f-m)/r:0;case pi.RightToLeft:return r>0?1-(f-m)/r:0;case pi.BottomToTop:return a>0?(p-g)/a:0;case pi.TopToBottom:return a>0?1-(p-g)/a:0}}function sr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case pi.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case pi.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case pi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case pi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class ir{build(e){ie("Slider",tr);const t=e.world;let n=null;e.addSystemToSchedule(_t.PreUpdate,xt([Ie(Et),Ie(At),Ie(fo)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([tr,gi]);for(const r of o){const o=t.get(r,tr),a=t.get(r,gi);if(!wo()||bo()){if(t.has(r,de)){Fi(t,r,ao,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Fi(t,o.handleEntity,ao,{enabled:!0,blockRaycast:!1});const l=t.get(r,de),c=t.has(r,lo)?t.get(r,lo):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,lo)&&(d=t.get(o.handleEntity,lo).justPressed),d&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=nr(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,tr,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,d=Ri(a,r),h=Ai(a,r),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Si(t,o.fillEntity,o.direction,c),Bi(t,o.fillEntity,u,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,gi)){const e=t.get(o.handleEntity,gi);sr(e,o.direction,c),t.insert(o.handleEntity,gi,e),Bi(t,o.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const or=new ir;const rr=new class{build(e){ie("Focusable",Co);const t=e.world,n=new Ro;e.insertResource(Ao,n),e.addSystemToSchedule(_t.Update,xt([Ie(Et),Ie(fo)],(e,s)=>{if(wo()&&!bo())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Co]);for(const e of i){if(!t.has(e,lo))continue;t.get(e,lo).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,ao)){if(!t.get(n,ao).enabled)continue}const s=t.get(n,Co);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,Co)){t.get(i,Co).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Co).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},ar=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function lr(){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 cr=new class{build(e){ie("SafeArea",ar);const t=e.world;let n=lr(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=lr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=lr(),s=!0});e.addSystemToSchedule(_t.PreUpdate,xt([Ie(At)],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,d=t.getEntitiesWithComponents([ar,gi]);for(const e of d){const s=t.get(e,ar),i=t.get(e,gi),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 d=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},d=!0),d&&t.insert(e,gi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},dr=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let hr=null;function ur(e,t){if(!hr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=hr.get(e);n?n.renderer=t:hr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const fr=new class{build(e){ie("ListView",dr);const t=e.world,n=new Map;hr=n,e.addSystemToSchedule(_t.PostUpdate,xt([Ie(Et)],e=>{const s=wo()&&!bo();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([dr,gi]);for(const o of i){Fi(t,o,ao,{enabled:!0,blockRaycast:!0}),Fi(t,o,qi,{enabled:!0,mode:Ni});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,dr),a=t.get(o,gi),l=Ai(a,o),c=Ri(a,o);if(!s){const n=t.has(o,lo)?t.get(o,lo):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const d=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,d));const h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),u=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.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,ve,{value:`ListItem_${e}`}),t.insert(n,gi,{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,de)){const s=t.get(n,de);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,de,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},pr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const mr=new class{build(e){ie("Dropdown",pr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,de))return;const n=t.get(e,de);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,de,{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,fe)){const n=t.get(e,fe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,fe,{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;d(i,!0),c(s);const o=t.get(e,fe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*$i;t.insert(i,gi,{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,de,{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,fe,{texture:D,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)*$i;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,gi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*$i},offsetMax:{x:0,y:0},size:{x:r,y:$i},pivot:{x:.5,y:.5}}),t.insert(o,de,{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,fe,{texture:D,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:$i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ao,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,de,{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,Hi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Li.Left,verticalAlign:Oi.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,gi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:$i},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),d(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,Hi))return;const s=t.get(n,Hi);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,Hi,{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 d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,ao)&&t.insert(e,ao,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const s=t.get(e,fe);t.insert(e,fe,{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,fe))continue;const i=n===e.highlightIndex?{...Di}:{r:.95,g:.95,b:.95,a:1};t.insert(s,fe,{texture:D,color:i,size:{x:e.ddWidth,y:$i},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,lo))continue;if(t.get(n,lo).hovered)return!0}return!1}e.addSystemToSchedule(_t.Update,xt([Ie(Et),Ie(fo)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=wo()&&!bo(),p=t.getEntitiesWithComponents([pr]);for(const m of p){const p=t.get(m,pr);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||d(p.listEntity,!1),l(p),f)continue;Fi(t,m,ao,{enabled:!0,blockRaycast:!0});const _=t.has(m,lo)?t.get(m,lo):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,lo))continue;if(t.get(n,lo).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,lo))continue;if(t.get(s,lo).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||u(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},gr=0,_r=0,yr=2,wr=K("LayoutGroup",{direction:gr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:_r,reverseOrder:!1});const xr=new class{build(e){ie("LayoutGroup",wr);const t=e.world;e.addSystemToSchedule(_t.PreUpdate,xt([],()=>{const e=t.getEntitiesWithComponents([wr,gi,ye]);for(const n of e){const e=t.get(n,wr),s=t.get(n,gi),i=t.get(n,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,gi)&&t.has(e,de)&&o.push({entity:e,rect:t.get(e,gi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Ri(s,n),a=Ai(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===gr;let u=0;for(let n=0;n<o.length;n++){const s=o[n],i=Ri(s.rect,s.entity),f=Ai(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,_;h?(g=-l*r+d.left+u+p*i,_=e.childAlignment===_r?(1-c)*a-d.top-(1-m)*f:e.childAlignment===yr?-c*a+d.bottom+m*f:(.5-c)*a+.5*(d.bottom-d.top)+(m-.5)*f,u+=i,n<o.length-1&&(u+=e.spacing)):(g=e.childAlignment===_r?-l*r+d.left+p*i:e.childAlignment===yr?(1-l)*r-d.right-(1-p)*i:(.5-l)*r+.5*(d.left-d.right)+(p-.5)*i,_=(1-c)*a-d.top-u-(1-m)*f,u+=f,n<o.length-1&&(u+=e.spacing));const y=t.get(s.entity,de);y.position.x=g,y.position.y=_,t.insert(s.entity,de,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};re("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),re("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class vr{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(_t.PostUpdate,xt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const br=new vr;async function Sr(e,t,n){const s=e.getResource(qs);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Mr(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 Pr=Ae({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Tr=Ae(null,"PhysicsAPI");function Er(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Cr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Rr{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(Pr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Mr(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([me]);for(const n of t){const t=e.world.get(n,me);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(_t.PostUpdate,xt([Ie(ze)],a=>{const l=r.getEntitiesWithComponents([Me,de]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,de);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=Er(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),Ar(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===Ce.Kinematic){const e=Er(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 d=e.world.get(r,de);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(r,_e)){const t=e.world.get(r,_e);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,de)){const n=e.world.get(t.entity,de),s=Er(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),d=Math.sin(-s);h=(i*r-o*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=Cr(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(r,de,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 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=[],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(Pr,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(Tr,Ir._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Ar(e,t,n){const s=e.world;if(s.has(n,Pe)){const e=s.get(n,Pe);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,Te)){const e=s.get(n,Te);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,Ee)){const e=s.get(n,Ee);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 Ir{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(Ir.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 kr={nearest:0,linear:1},Fr={repeat:0,clamp:1,mirror:2};function Br(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=kr[s.filterMode??"linear"]??1,a=Fr[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 zr(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 Ur(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,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,m=a*u,g=a*f,_=l*u,y=l*f,w=c*f,x=d*h,v=d*u,b=d*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 $r(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=hn(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]=Br(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 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 o={};for(const r of s.entities)for(const s of r.components){const r=un(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),d=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===Rn(c)?.contentType;let h,u;if(r){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,r);if(t._free(h),f<0)continue;o[a]=f;const p=zr(s),m=d.substring(0,d.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=Br(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??{...A},fixedTimestep:r?.fixedTimestep??I,subStepCount:r?.subStepCount??4};new Rr("",t,()=>Promise.resolve(o)).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=hn(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=Rn(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),d=Br(e,c,!1),h=e.getResourceManager();s[o]=h.loadBitmapFont(t,d,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=hn(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=Ot.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Ot.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=hn(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=yn(e.world,n);if(l&&e.hasResource(qs))for(const t of p.values())e.world.insert(t,be,{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=un(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,d,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=R);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,xe)?c.get(o,xe):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(r,l*h);let u=0;if(c.has(o,de)){const e=Ur(c.get(o,de),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>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),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,d,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,d,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,u),t._free(y),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(Hn);t&&t.setAddressableManifest(a)}}function Dr(e,t,n){return{name:e,async setup(){await $r(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Lr{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=un(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===Rn(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=hn(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=Rn(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 Or="__preview__";class Wr{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(qs);t.register({name:Or,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Or),this.loadPromise_=t.load(Or).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 Lr(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await $r(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Or)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([pe]);for(const s of n){if(e.get(s,pe).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([me]);for(const i of s){const s=e.get(i,me);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(qs).getScene(Or),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,de,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(o,pe,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(qs);await e.switchTo(Or),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 Hr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Ls.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Ls.getTargetTexture(n),width:e.width,height:e.height}},release(e){Ls.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Ls.releaseRenderTarget(e._handle),Hr.create({width:t,height:n,depth:!0})),begin(e,t){Ls.begin(t,e._handle)},end(){Ls.end()},getDepthTexture:e=>Ls.getTargetDepthTexture(e._handle)};var Xr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Xr||(Xr={}));class jr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Xr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Xr.Debug:console.debug(t,n);break;case Xr.Info:console.log(t,n);break;case Xr.Warn:console.warn(t,n);break;case Xr.Error:console.error(t,n)}}}class Yr{constructor(){this.handlers_=[],this.minLevel_=Xr.Info,this.addHandler(new jr)}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(Xr.Debug,e,t,n)}info(e,t,n){this.log(Xr.Info,e,t,n)}warn(e,t,n){this.log(Xr.Warn,e,t,n)}error(e,t,n){this.log(Xr.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 Vr=new Yr;function Nr(){return Vr}function Gr(e){Vr.setMinLevel(e)}function qr(e,t,n){Vr.debug(e,t,n)}function Kr(e,t,n){Vr.info(e,t,n)}function Jr(e,t,n){Vr.warn(e,t,n)}function Qr(e,t,n){Vr.error(e,t,n)}const Zr={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},ea={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},ta={Running:0,Paused:1,Completed:2,Cancelled:3},na={None:0,Restart:1,PingPong:2};class sa{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 ia=null,oa=null;function ra(e,t){ia=e,oa=t}function aa(){ia=null,oa=null}function la(){if(!ia)throw new Error("Tween API not initialized");return ia}function ca(){if(!oa)throw new Error("Tween API not initialized");return oa}const da={to(e,t,n,s,i,o){const r=la(),a=ca(),l=o?.easing??Zr.Linear,c=o?.delay??0,d=o?.loop??na.None,h=o?.loopCount??0,u=r._anim_createTween(a,e,t,n,s,i,l,c,d,h);return new sa(r,a,u)},cancel(e){la()._anim_cancelTween(ca(),e.entity)},cancelAll(e){la()._anim_cancelAllTweens(ca(),e)},update(e){la()._anim_updateTweens(ca(),e)}};class ha{constructor(){this.name="AnimationPlugin"}build(e){ra(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(_t.Update,xt([Ie(ze)],e=>{da.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(_t.Update,xt([Ie(ze)],e=>{rn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){aa()}}const ua=new ha;var fa;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(fa||(fa={}));const pa={model:fa.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function ma(e,t=pa){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);switch(n){case fa.Linear:{const e=i-s;if(e<=0)return 1;return 1-(Math.min(Math.max(r,s),i)-s)/e}case fa.Inverse:return s/Math.max(r,s);case fa.Exponential:return Math.pow(Math.max(r,s)/s,-o);default:return 1}}function ga(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const _a=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:fa.Inverse,rolloff:1,priority:0,enabled:!0}),ya=K("AudioListener",{enabled:!0});class wa{constructor(e={}){this.name="AudioPlugin",this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize});const i=n.mixer;an.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;e.addSystemToSchedule(_t.PreUpdate,xt([Ie(ze)],t=>{const s=e.world;let i=0,r=0;const a=s.getEntitiesWithComponents([ya,ue]);for(const e of a){if(s.get(e,ya).enabled){const t=s.get(e,ue);i=t.position.x,r=t.position.y;break}}const l=s.getEntitiesWithComponents([_a,ue]),c=new Set;for(const e of l){const t=s.get(e,_a);if(!t.enabled||!t.clip)continue;c.add(e);const a=s.get(e,ue);if(t.playOnAwake&&!o.has(e)){const s=an.getBufferHandle(t.clip);if(s){const i=n.play(s,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch,priority:t.priority});o.set(e,i)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(e)){const n=o.get(e);if(!n.isPlaying){o.delete(e);continue}const s=a.position.x-i,l=a.position.y-r,c=ma(Math.sqrt(s*s+l*l),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),d=ga(a.position.x,a.position.y,i,0,t.maxDistance);n.setVolume(t.volume*c),n.setPan(d)}}for(const[e,t]of o)c.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}cleanup(){an.dispose()}}const xa=new wa;function va(e,t){return e.toFixed(t)}class ba{constructor(e,t="bottom-left"){this.visible_=!0,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${va(e.fps,1)}</span> Frame: <span style="color:#d19a66">${va(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of n){s+=`<div>${(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${va(t,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.el_.parentElement?.removeChild(this.el_)}}function Sa(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const Ma=Ae(Sa(),"Stats");class Pa{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60)}getFps(){return 0===this.count_||0===this.sum_?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||0===this.sum_?0:this.sum_/this.count_*1e3}}class Ta{constructor(e){this.name="Stats",this.collector_=new Pa,this.overlay_=null,this.options_=e??{}}build(e){e.enableStats(),e.insertResource(Ma,Sa());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new ba(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=xt([Ie(ze),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(Ma);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();o.systemTimings=r?new Map(r):new Map;const a=Ls.getStats();o.drawCalls=a.drawCalls,o.triangles=a.triangles,o.sprites=a.sprites,o.text=a.text,o.spine=a.spine,o.meshes=a.meshes,o.culled=a.culled,n?.update(o)},{name:"StatsCollect"});e.addSystemToSchedule(_t.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Ea=new Ta;class Ca{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 Ra(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 Aa(e){const{app:t,module:n,assets:s,sceneData:i,sceneName:o}=e,r=t.getResource(Hn);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0)),ei(t);const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Ra(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 Ra(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=Dr(o,i,{app:t,module:n,provider:new Ca(s),spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest}),d=t.getResource(qs);d.register(c),d.setInitial(o),await d.load(o);const h=e.canvas.width/e.canvas.height;bn(t.world,h),t.run()}const Ia=[Vi,ro,mo,Do,Vo,To,qo,Zo,or,Wo,ko,rr,cr,fr,mr,xr,br],ka=[...Ia,ua];function Fa(e,t){return function(e,t){const n=Zs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),as(e),$t(e),Ms(e),Rs(e),$s(e),Ws(e);const i=new js;n.setPipeline(i);let o=u();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=oi(e,s,t,i));const r=n.getResource(At);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(At,{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;Ls.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-o)/1e3;let h;if(Ls.resize(t,l),ks.isInitialized()&&ks.getPassCount()>0&&!ks.isBypassed()&&ks.resize(t,l),n.hasResource(qs)){const e=n.getResource(qs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=oi(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:ti,width:t,height:l,elapsed:d});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:d})}Ls.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(_t.First,l),n.addSystemToSchedule(_t.Last,c),n.addPlugin(jn),n.addPlugin(ts),n.addPlugin(Rt),n.addPlugin(Qs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:ka,...t})}e=w;export{Je as Added,ha as AnimationPlugin,Zs as App,Xn as AssetPlugin,Yn as AssetRefCounter,Wn as AssetServer,Hn as Assets,qt as AsyncCache,fa as AttenuationModel,an as Audio,p as AudioBus,ya as AudioListener,m as AudioMixer,wa as AudioPlugin,g as AudioPool,_a as AudioSource,we as BitmapText,It as BlendMode,Ce as BodyType,Pe as BoxCollider,ho as Button,co as ButtonState,pe as Camera,me as Canvas,Ee as CapsuleCollider,Qe as Changed,ye as Children,Te as CircleCollider,le as ClearFlags,at as Commands,ct as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,R as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,A as DEFAULT_GRAVITY,E as DEFAULT_LINE_HEIGHT,C as DEFAULT_MAX_DELTA_TIME,b as DEFAULT_PIXELS_PER_UNIT,k as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,ws as DataType,Go as DragState,No as Draggable,hs as Draw,pr as Dropdown,Zr as EasingType,lt as EntityCommands,pt as EventReader,gt as EventReaderInstance,ut as EventRegistry,ft as EventWriter,mt as EventWriterInstance,pi as FillDirection,Bo as FillMethod,zo as FillOrigin,Ao as FocusManager,Ro as FocusManagerState,Co as Focusable,Xs as GLDebug,Es as Geometry,yt as GetWorld,$ as INVALID_ENTITY,L as INVALID_FONT,O as INVALID_MATERIAL,D as INVALID_TEXTURE,Uo as Image,Fo as ImageType,Et as Input,Ct as InputPlugin,Tt as InputState,ao as Interactable,dr as ListView,he as LocalTransform,Xr as LogLevel,Yr as Logger,na as LoopMode,Ot as Material,Kt as MaterialLoader,qe as Mut,ve as Name,_e as Parent,Ir as Physics,Pr as PhysicsEvents,Rr as PhysicsPlugin,ks as PostProcess,Qn as PrefabServer,Zn as Prefabs,es as PrefabsPlugin,Wr as PreviewPlugin,Xo as ProgressBar,Ho as ProgressBarDirection,Yo as ProgressBarPlugin,ae as ProjectionType,st as Query,it as QueryInstance,ot as Removed,rt as RemovedQueryInstance,js as RenderPipeline,Bs as RenderStage,Hr as RenderTexture,Ls as Renderer,Ie as Res,ke as ResMut,Me as RigidBody,F as RuntimeConfig,ar as SafeArea,ce as ScaleMode,qs as SceneManager,Gs as SceneManagerState,be as SceneOwner,_t as Schedule,Ko as ScrollView,Gt as ShaderSources,tr as Slider,er as SliderDirection,ir as SliderPlugin,xe as SpineAnimation,fe as Sprite,on as SpriteAnimator,Ma as Stats,Pa as StatsCollector,ba as StatsOverlay,Ta as StatsPlugin,Pt as SystemRunner,Hi as Text,Li as TextAlign,Eo as TextInput,Io as TextInputPlugin,Wi as TextOverflow,Yi as TextPlugin,Xi as TextRenderer,Oi as TextVerticalAlign,ze as Time,Lo as Toggle,de as Transform,da as Tween,sa as TweenHandle,ta as TweenState,ea as TweenTarget,At as UICameraInfo,uo as UIEventQueue,fo as UIEvents,lo as UIInteraction,Po as UIInteractionPlugin,po as UILayoutPlugin,qi as UIMask,oo as UIMaskPlugin,gi as UIRect,vr as UIRenderOrderPlugin,ge as Velocity,Lr as WebAssetProvider,Ge as World,ue as WorldTransform,St as addStartupSystem,bt as addSystem,Mt as addSystemToSchedule,ua as animationPlugin,U as applyBuildRuntimeConfig,Si as applyDirectionalFill,B as applyRuntimeConfig,jn as assetPlugin,xa as audioPlugin,ma as calculateAttenuation,ga as calculatePanning,sn as clearAnimClips,ys as clearDrawCallbacks,Z as clearUserComponents,j as color,xi as computeFillAnchors,bi as computeFillSize,vi as computeHandleAnchors,mi as computeUIRectLayout,io as createMaskProcessor,Dr as createRuntimeSceneConfig,Fa as createWebApp,qr as debug,Sa as defaultFrameStats,K as defineComponent,dt as defineEvent,Ae as defineResource,xt as defineSystem,J as defineTag,Qr as error,Jt as extractAnimClipTexturePaths,Sn as findEntityByName,ei as flushPendingSystems,In as getAddressableType,kn as getAddressableTypeByEditorType,Bn as getAllAssetExtensions,nn as getAnimClip,Dn as getAssetMimeType,Rn as getAssetTypeEntry,oe as getComponent,hn as getComponentAssetFieldDescriptors,dn as getComponentAssetFields,Se as getComponentDefaults,mn as getComponentEntityFields,un as getComponentSpineFieldDescriptor,Un as getCustomExtensions,An as getEditorType,Nr as getLogger,t as getPlatform,s as getPlatformType,Q as getUserComponent,$n as getWeChatPackOptions,Kr as info,as as initDrawAPI,Ws as initGLDebugAPI,Ms as initGeometryAPI,$t as initMaterialAPI,Aa as initPlayableRuntime,Rs as initPostProcessAPI,$s as initRendererAPI,ra as initTweenAPI,Rt as inputPlugin,Nn as instantiatePrefab,Ki as intersectRects,Ji as invertMatrix4,ne as isBuiltinComponent,Ln as isCustomExtension,wo as isEditor,Fn as isKnownAssetExtension,n as isPlatformInitialized,bo as isPlayMode,xo as isRuntime,kt as isTextureRef,i as isWeChat,o as isWeb,vn as loadComponent,Mr as loadPhysicsModule,$r as loadRuntimeScene,yn as loadSceneData,wn as loadSceneWithAssets,zn as looksLikeAssetPath,Qt as parseAnimClipData,r as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,no as pointInOBB,Zi as pointInWorldRect,ts as prefabsPlugin,Vo as progressBarPlugin,Y as quat,en as registerAnimClip,ie as registerComponent,cn as registerComponentAssetFields,pn as registerComponentEntityFields,gs as registerDrawCallback,Vn as registerEmbeddedAssets,Nt as registerMaterialCallback,gn as remapEntityFields,Qs as sceneManagerPlugin,Qi as screenToWorld,yo as setEditorMode,ur as setListViewRenderer,Gr as setLogLevel,vo as setPlayMode,Oe as setWasmErrorHandler,ls as shutdownDrawAPI,Hs as shutdownGLDebugAPI,Ps as shutdownGeometryAPI,Dt as shutdownMaterialAPI,As as shutdownPostProcessAPI,Ds as shutdownRendererAPI,aa as shutdownTweenAPI,or as sliderPlugin,rn as spriteAnimatorSystemUpdate,Ea as statsPlugin,Ii as syncFillSpriteSize,ko as textInputPlugin,Vi as textPlugin,On as toBuildPath,Sr as transitionTo,To as uiInteractionPlugin,mo as uiLayoutPlugin,ro as uiMaskPlugin,Ia as uiPlugins,br as uiRenderOrderPlugin,tn as unregisterAnimClip,ee as unregisterComponent,_s as unregisterDrawCallback,bn as updateCameraAspectRatio,W as vec2,H as vec3,X as vec4,Jr as warn,Ks as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 23df1a963..b4aa15b65 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -874,6 +874,7 @@ declare class App {
private readonly sortedSystemsCache_;
private error_handler_;
private system_error_handler_;
+ private statsEnabled_;
private frame_paused_;
private user_paused_;
private step_pending_;
@@ -912,6 +913,9 @@ declare class App {
stepFrame(): void;
setPlaySpeed(speed: number): void;
getPlaySpeed(): number;
+ enableStats(): this;
+ getSystemTimings(): ReadonlyMap<string, number> | null;
+ getEntityCount(): number;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 378d1a982..6939b5de4 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -946,6 +946,7 @@ declare class App {
private readonly sortedSystemsCache_;
private error_handler_;
private system_error_handler_;
+ private statsEnabled_;
private frame_paused_;
private user_paused_;
private step_pending_;
@@ -984,6 +985,9 @@ declare class App {
stepFrame(): void;
setPlaySpeed(speed: number): void;
getPlaySpeed(): number;
+ enableStats(): this;
+ getSystemTimings(): ReadonlyMap<string, number> | null;
+ getEntityCount(): number;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
diff --git a/editor/src/panels/scene-view/SceneViewPanel.ts b/editor/src/panels/scene-view/SceneViewPanel.ts
index 157c23290..92246afa1 100644
--- a/editor/src/panels/scene-view/SceneViewPanel.ts
+++ b/editor/src/panels/scene-view/SceneViewPanel.ts
@@ -1,5 +1,5 @@
import type { Entity, App } from 'esengine';
-import { Renderer, computeUIRectLayout, DEFAULT_SPRITE_SIZE } from 'esengine';
+import { Renderer, computeUIRectLayout, DEFAULT_SPRITE_SIZE, StatsCollector } from 'esengine';
import type { SpineModuleController } from 'esengine/spine';
import type { EditorStore } from '../../store/EditorStore';
import type { EditorBridge } from '../../bridge/EditorBridge';
@@ -68,6 +68,9 @@ export class SceneViewPanel {
private dropHandler_: EntityDropHandler;
private input_: SceneViewInput;
+ private fpsCollector_ = new StatsCollector();
+ private lastFrameTime_ = 0;
+
private static readonly MAX_CACHE_SIZE = 100;
private textureCache_: Map<string, HTMLImageElement | null> = new Map();
private loadingTextures_: Set<string> = new Set();
@@ -654,6 +657,12 @@ export class SceneViewPanel {
ctx.restore();
+ const now = performance.now();
+ if (this.lastFrameTime_ > 0) {
+ this.fpsCollector_.pushFrame((now - this.lastFrameTime_) / 1000);
+ }
+ this.lastFrameTime_ = now;
+
this.drawStats(ctx, w, h);
this.drawViewportPreview(ctx, w, h);
@@ -980,18 +989,21 @@ export class SceneViewPanel {
const stats = Renderer.getStats();
const spineCount = this.sceneRenderer_?.spineInstanceCount ?? stats.spine;
+ const fps = this.fpsCollector_.getFps();
+ const entityCount = this.store_.scene.entities.length;
const lines = [
`DC: ${stats.drawCalls} Tri: ${stats.triangles}`,
`Sprite: ${stats.sprites} Spine: ${spineCount}`,
`Text: ${stats.text} Mesh: ${stats.meshes}`,
`Culled: ${stats.culled}`,
+ `FPS: ${Math.round(fps)} Entities: ${entityCount}`,
];
const fontSize = 12;
const lineHeight = 18;
const padding = 8;
- const panelW = 180;
+ const panelW = 200;
const panelH = lines.length * lineHeight + padding * 2;
const x0 = 12;
const y0 = canvasHeight - panelH - 12;
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 0eefcdbec..3e09d5460 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -84,6 +84,7 @@ export class App {
private readonly sortedSystemsCache_ = new Map<Schedule, SystemEntry[]>();
private error_handler_: ((error: unknown, systemName: string) => void) | null = null;
private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;
+ private statsEnabled_ = false;
private frame_paused_ = false;
private user_paused_ = false;
private step_pending_ = false;
@@ -296,6 +297,23 @@ export class App {
return this.play_speed_;
}
+ // =========================================================================
+ // Stats
+ // =========================================================================
+
+ enableStats(): this {
+ this.statsEnabled_ = true;
+ return this;
+ }
+
+ getSystemTimings(): ReadonlyMap<string, number> | null {
+ return this.runner_?.getTimings() ?? null;
+ }
+
+ getEntityCount(): number {
+ return this.world_.entityCount();
+ }
+
// =========================================================================
// Resource Access
// =========================================================================
@@ -334,6 +352,9 @@ export class App {
tick(delta: number): void {
if (!this.runner_) {
this.runner_ = new SystemRunner(this.world_, this.resources_, this.eventRegistry_);
+ if (this.statsEnabled_) {
+ this.runner_.setTimingEnabled(true);
+ }
if (!this.resources_.has(Time)) {
this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
}
@@ -386,6 +407,9 @@ export class App {
this.running_ = true;
this.runner_ = new SystemRunner(this.world_, this.resources_, this.eventRegistry_);
+ if (this.statsEnabled_) {
+ this.runner_.setTimingEnabled(true);
+ }
this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 894303d0c..2c512dd52 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -666,7 +666,6 @@ export {
AudioBus,
AudioMixer,
AudioPool,
- createAudioBackend,
AttenuationModel,
calculateAttenuation,
calculatePanning,
@@ -674,6 +673,7 @@ export {
type AudioBufferHandle,
type PlayConfig,
type PlatformAudioBackend,
+ type AudioBackendInitOptions,
type AudioPluginConfig,
type AudioBusConfig,
type AudioMixerConfig,
@@ -681,9 +681,24 @@ export {
type AudioSourceData,
type AudioListenerData,
type PooledAudioNode,
- type WebAudioBackendOptions,
} from './audio';
+// =============================================================================
+// Stats
+// =============================================================================
+
+export {
+ Stats,
+ StatsPlugin,
+ statsPlugin,
+ StatsCollector,
+ defaultFrameStats,
+ type FrameStats,
+ type StatsPluginOptions,
+} from './stats';
+
+export { StatsOverlay, type StatsPosition } from './stats-overlay';
+
// =============================================================================
// Playable Runtime
// =============================================================================
diff --git a/sdk/src/stats-overlay.ts b/sdk/src/stats-overlay.ts
new file mode 100644
index 000000000..b8e58ace7
--- /dev/null
+++ b/sdk/src/stats-overlay.ts
@@ -0,0 +1,97 @@
+import type { FrameStats } from './stats';
+
+export type StatsPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';
+
+const TOP_SYSTEMS_COUNT = 5;
+
+const PANEL_STYLES = `
+position: fixed;
+z-index: 99999;
+pointer-events: none;
+background: rgba(30, 30, 30, 0.85);
+border: 1px solid rgba(60, 60, 60, 0.8);
+border-radius: 4px;
+padding: 6px 10px;
+font: 11px monospace;
+color: #cccccc;
+line-height: 1.6;
+min-width: 200px;
+`;
+
+function positionStyle(position: StatsPosition): string {
+ switch (position) {
+ case 'top-left': return 'top: 12px; left: 12px;';
+ case 'top-right': return 'top: 12px; right: 12px;';
+ case 'bottom-left': return 'bottom: 12px; left: 12px;';
+ case 'bottom-right': return 'bottom: 12px; right: 12px;';
+ }
+}
+
+function formatNumber(n: number, decimals: number): string {
+ return n.toFixed(decimals);
+}
+
+export class StatsOverlay {
+ private el_: HTMLDivElement;
+ private visible_ = true;
+
+ constructor(container: HTMLElement, position: StatsPosition = 'bottom-left') {
+ this.el_ = document.createElement('div');
+ this.el_.style.cssText = PANEL_STYLES + positionStyle(position);
+ container.appendChild(this.el_);
+ }
+
+ update(stats: FrameStats): void {
+ if (!this.visible_) return;
+
+ const sections: string[] = [];
+
+ sections.push(
+ '<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div>' +
+ `<div>FPS: <span style="color:#d19a66">${formatNumber(stats.fps, 1)}</span>` +
+ ` Frame: <span style="color:#d19a66">${formatNumber(stats.frameTimeMs, 1)}ms</span></div>`
+ );
+
+ sections.push(
+ '<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div>' +
+ `<div>DC: <span style="color:#d19a66">${stats.drawCalls}</span>` +
+ ` Tri: <span style="color:#d19a66">${stats.triangles}</span></div>` +
+ `<div>Sprites: <span style="color:#d19a66">${stats.sprites}</span>` +
+ ` Culled: <span style="color:#d19a66">${stats.culled}</span></div>`
+ );
+
+ sections.push(
+ '<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div>' +
+ `<div>Entities: <span style="color:#d19a66">${stats.entityCount}</span></div>`
+ );
+
+ if (stats.systemTimings.size > 0) {
+ const sorted = [...stats.systemTimings.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, TOP_SYSTEMS_COUNT);
+
+ let systemsHtml = '<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';
+ for (const [name, ms] of sorted) {
+ const displayName = name.length > 20 ? name.slice(0, 20) + '...' : name;
+ systemsHtml += `<div>${displayName.padEnd(22)}<span style="color:#d19a66">${formatNumber(ms, 1)}ms</span></div>`;
+ }
+ sections.push(systemsHtml);
+ }
+
+ this.el_.innerHTML = sections.join('');
+ }
+
+ show(): void {
+ this.visible_ = true;
+ this.el_.style.display = '';
+ }
+
+ hide(): void {
+ this.visible_ = false;
+ this.el_.style.display = 'none';
+ }
+
+ dispose(): void {
+ this.el_.parentElement?.removeChild(this.el_);
+ }
+}
diff --git a/sdk/src/stats.ts b/sdk/src/stats.ts
new file mode 100644
index 000000000..a642d8a88
--- /dev/null
+++ b/sdk/src/stats.ts
@@ -0,0 +1,136 @@
+import { Renderer } from './renderer';
+import { defineResource, Res, Time } from './resource';
+import { defineSystem, GetWorld, Schedule } from './system';
+import type { App, Plugin } from './app';
+import { StatsOverlay, type StatsPosition } from './stats-overlay';
+
+export interface FrameStats {
+ fps: number;
+ frameTimeMs: number;
+ entityCount: number;
+ systemTimings: Map<string, number>;
+ drawCalls: number;
+ triangles: number;
+ sprites: number;
+ text: number;
+ spine: number;
+ meshes: number;
+ culled: number;
+}
+
+export function defaultFrameStats(): FrameStats {
+ return {
+ fps: 0,
+ frameTimeMs: 0,
+ entityCount: 0,
+ systemTimings: new Map(),
+ drawCalls: 0,
+ triangles: 0,
+ sprites: 0,
+ text: 0,
+ spine: 0,
+ meshes: 0,
+ culled: 0,
+ };
+}
+
+export const Stats = defineResource<FrameStats>(defaultFrameStats(), 'Stats');
+
+const SLIDING_WINDOW_SIZE = 60;
+
+export class StatsCollector {
+ private deltas_: number[] = [];
+ private cursor_ = 0;
+ private count_ = 0;
+ private sum_ = 0;
+
+ pushFrame(deltaSeconds: number): void {
+ if (this.count_ < SLIDING_WINDOW_SIZE) {
+ this.deltas_.push(deltaSeconds);
+ this.sum_ += deltaSeconds;
+ this.count_++;
+ } else {
+ this.sum_ -= this.deltas_[this.cursor_];
+ this.deltas_[this.cursor_] = deltaSeconds;
+ this.sum_ += deltaSeconds;
+ this.cursor_ = (this.cursor_ + 1) % SLIDING_WINDOW_SIZE;
+ }
+ }
+
+ getFps(): number {
+ if (this.count_ === 0 || this.sum_ === 0) return 0;
+ return this.count_ / this.sum_;
+ }
+
+ getFrameTimeMs(): number {
+ if (this.count_ === 0 || this.sum_ === 0) return 0;
+ return (this.sum_ / this.count_) * 1000;
+ }
+}
+
+export interface StatsPluginOptions {
+ overlay?: boolean;
+ position?: StatsPosition;
+ container?: HTMLElement;
+}
+
+export class StatsPlugin implements Plugin {
+ readonly name = 'Stats';
+ private collector_ = new StatsCollector();
+ private overlay_: StatsOverlay | null = null;
+ private options_: StatsPluginOptions;
+
+ constructor(options?: StatsPluginOptions) {
+ this.options_ = options ?? {};
+ }
+
+ build(app: App): void {
+ app.enableStats();
+ app.insertResource(Stats, defaultFrameStats());
+
+ const showOverlay = this.options_.overlay !== false;
+ if (showOverlay && typeof document !== 'undefined') {
+ const container = this.options_.container ?? document.body;
+ this.overlay_ = new StatsOverlay(container, this.options_.position);
+ }
+
+ const collector = this.collector_;
+ const overlay = this.overlay_;
+
+ const statsCollectSystem = defineSystem(
+ [Res(Time), GetWorld()],
+ (time, world) => {
+ collector.pushFrame(time.delta);
+
+ const stats = app.getResource(Stats);
+ stats.fps = collector.getFps();
+ stats.frameTimeMs = collector.getFrameTimeMs();
+ stats.entityCount = world.entityCount();
+
+ const timings = app.getSystemTimings();
+ stats.systemTimings = timings ? new Map(timings) : new Map();
+
+ const renderStats = Renderer.getStats();
+ stats.drawCalls = renderStats.drawCalls;
+ stats.triangles = renderStats.triangles;
+ stats.sprites = renderStats.sprites;
+ stats.text = renderStats.text;
+ stats.spine = renderStats.spine;
+ stats.meshes = renderStats.meshes;
+ stats.culled = renderStats.culled;
+
+ overlay?.update(stats);
+ },
+ { name: 'StatsCollect' }
+ );
+
+ app.addSystemToSchedule(Schedule.Last, statsCollectSystem);
+ }
+
+ cleanup(): void {
+ this.overlay_?.dispose();
+ this.overlay_ = null;
+ }
+}
+
+export const statsPlugin = new StatsPlugin();
diff --git a/sdk/src/system.ts b/sdk/src/system.ts
index 2ac57b05f..f121d4e1e 100644
--- a/sdk/src/system.ts
+++ b/sdk/src/system.ts
@@ -143,6 +143,7 @@ export class SystemRunner {
private readonly argsCache_ = new Map<symbol, unknown[]>();
private readonly systemTicks_ = new Map<symbol, number>();
private currentLastRunTick_ = -1;
+ private timings_: Map<string, number> | null = null;
constructor(world: World, resources: ResourceStorage, eventRegistry?: EventRegistry) {
this.world_ = world;
@@ -150,6 +151,14 @@ export class SystemRunner {
this.eventRegistry_ = eventRegistry ?? null;
}
+ setTimingEnabled(enabled: boolean): void {
+ this.timings_ = enabled ? new Map() : null;
+ }
+
+ getTimings(): ReadonlyMap<string, number> | null {
+ return this.timings_;
+ }
+
run(system: SystemDef): void {
let args = this.argsCache_.get(system._id);
if (!args) {
@@ -163,6 +172,7 @@ export class SystemRunner {
args[i] = this.resolveParam(system._params[i]);
}
+ const t0 = this.timings_ ? performance.now() : 0;
try {
(system._fn as (...args: unknown[]) => void)(...args);
@@ -172,6 +182,9 @@ export class SystemRunner {
}
}
} finally {
+ if (this.timings_) {
+ this.timings_.set(system._name, performance.now() - t0);
+ }
this.world_.resetIterationDepth();
this.systemTicks_.set(system._id, this.world_.getWorldTick());
}
diff --git a/sdk/tests/stats.test.ts b/sdk/tests/stats.test.ts
new file mode 100644
index 000000000..df5388200
--- /dev/null
+++ b/sdk/tests/stats.test.ts
@@ -0,0 +1,723 @@
+import { describe, it, expect, vi } from 'vitest';
+import { StatsCollector, defaultFrameStats, Stats, StatsPlugin, statsPlugin, type FrameStats } from '../src/stats';
+import { StatsOverlay } from '../src/stats-overlay';
+import { App } from '../src/app';
+import { Schedule, defineSystem, SystemRunner } from '../src/system';
+import { World } from '../src/world';
+import { ResourceStorage } from '../src/resource';
+import * as rendererModule from '../src/renderer';
+
+// ============================================================================
+// StatsCollector
+// ============================================================================
+
+describe('StatsCollector', () => {
+ it('should start with 0 FPS and 0 frame time', () => {
+ const collector = new StatsCollector();
+ expect(collector.getFps()).toBe(0);
+ expect(collector.getFrameTimeMs()).toBe(0);
+ });
+
+ it('should calculate FPS from delta seconds', () => {
+ const collector = new StatsCollector();
+ for (let i = 0; i < 10; i++) {
+ collector.pushFrame(1 / 60);
+ }
+ expect(collector.getFps()).toBeCloseTo(60, 0);
+ });
+
+ it('should calculate frame time in milliseconds', () => {
+ const collector = new StatsCollector();
+ for (let i = 0; i < 10; i++) {
+ collector.pushFrame(1 / 60);
+ }
+ expect(collector.getFrameTimeMs()).toBeCloseTo(16.67, 0);
+ });
+
+ it('should use sliding window of 60 frames', () => {
+ const collector = new StatsCollector();
+
+ for (let i = 0; i < 60; i++) {
+ collector.pushFrame(1 / 30);
+ }
+ expect(collector.getFps()).toBeCloseTo(30, 0);
+
+ for (let i = 0; i < 60; i++) {
+ collector.pushFrame(1 / 120);
+ }
+ expect(collector.getFps()).toBeCloseTo(120, 0);
+ });
+
+ it('should handle zero delta gracefully', () => {
+ const collector = new StatsCollector();
+ collector.pushFrame(0);
+ expect(collector.getFps()).toBe(0);
+ expect(collector.getFrameTimeMs()).toBe(0);
+ });
+
+ it('should handle very large delta', () => {
+ const collector = new StatsCollector();
+ collector.pushFrame(1);
+ expect(collector.getFps()).toBeCloseTo(1, 0);
+ expect(collector.getFrameTimeMs()).toBeCloseTo(1000, 0);
+ });
+
+ it('should average across partial window', () => {
+ const collector = new StatsCollector();
+ collector.pushFrame(1 / 60);
+ collector.pushFrame(1 / 60);
+ collector.pushFrame(1 / 60);
+ expect(collector.getFps()).toBeCloseTo(60, 0);
+ });
+
+ it('should converge to new rate after window fills', () => {
+ const collector = new StatsCollector();
+ for (let i = 0; i < 60; i++) collector.pushFrame(1 / 60);
+ expect(collector.getFps()).toBeCloseTo(60, 0);
+
+ for (let i = 0; i < 30; i++) collector.pushFrame(1 / 30);
+ const fps = collector.getFps();
+ expect(fps).toBeLessThan(60);
+ expect(fps).toBeGreaterThan(30);
+ });
+
+ it('should maintain accuracy with > 100 frames pushed', () => {
+ const collector = new StatsCollector();
+ for (let i = 0; i < 200; i++) {
+ collector.pushFrame(1 / 144);
+ }
+ expect(collector.getFps()).toBeCloseTo(144, 0);
+ expect(collector.getFrameTimeMs()).toBeCloseTo(1000 / 144, 0);
+ });
+});
+
+// ============================================================================
+// defaultFrameStats
+// ============================================================================
+
+describe('defaultFrameStats', () => {
+ it('should initialize all numeric fields to 0', () => {
+ const stats = defaultFrameStats();
+ expect(stats.fps).toBe(0);
+ expect(stats.frameTimeMs).toBe(0);
+ expect(stats.entityCount).toBe(0);
+ expect(stats.drawCalls).toBe(0);
+ expect(stats.triangles).toBe(0);
+ expect(stats.sprites).toBe(0);
+ expect(stats.text).toBe(0);
+ expect(stats.spine).toBe(0);
+ expect(stats.meshes).toBe(0);
+ expect(stats.culled).toBe(0);
+ });
+
+ it('should initialize systemTimings as empty Map', () => {
+ const stats = defaultFrameStats();
+ expect(stats.systemTimings).toBeInstanceOf(Map);
+ expect(stats.systemTimings.size).toBe(0);
+ });
+
+ it('should return independent instances', () => {
+ const a = defaultFrameStats();
+ const b = defaultFrameStats();
+ a.fps = 60;
+ a.systemTimings.set('x', 1);
+ expect(b.fps).toBe(0);
+ expect(b.systemTimings.size).toBe(0);
+ });
+});
+
+// ============================================================================
+// App stats API
+// ============================================================================
+
+describe('App stats API', () => {
+ it('should return null timings before enableStats', () => {
+ const app = App.new();
+ expect(app.getSystemTimings()).toBeNull();
+ });
+
+ it('should return timings map after enableStats + tick', () => {
+ const app = App.new();
+ app.enableStats();
+ app.tick(1 / 60);
+ expect(app.getSystemTimings()).toBeInstanceOf(Map);
+ });
+
+ it('should record named system timings after enableStats', () => {
+ const app = App.new();
+ app.enableStats();
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [], () => {}, { name: 'MySystem' }
+ ));
+
+ app.tick(1 / 60);
+
+ const timings = app.getSystemTimings()!;
+ expect(timings.has('MySystem')).toBe(true);
+ expect(typeof timings.get('MySystem')).toBe('number');
+ });
+
+ it('should return entity count', () => {
+ const app = App.new();
+ expect(app.getEntityCount()).toBe(0);
+
+ app.world.spawn();
+ app.world.spawn();
+ expect(app.getEntityCount()).toBe(2);
+ });
+
+ it('should chain enableStats', () => {
+ const app = App.new();
+ expect(app.enableStats()).toBe(app);
+ });
+
+ it('should track entity count after despawn', () => {
+ const app = App.new();
+ const e1 = app.world.spawn();
+ app.world.spawn();
+ expect(app.getEntityCount()).toBe(2);
+
+ app.world.despawn(e1);
+ expect(app.getEntityCount()).toBe(1);
+ });
+});
+
+// ============================================================================
+// SystemRunner timing
+// ============================================================================
+
+describe('SystemRunner timing', () => {
+ function createRunner() {
+ const world = new World();
+ const resources = new ResourceStorage();
+ const runner = new SystemRunner(world, resources);
+ return { world, resources, runner };
+ }
+
+ it('should have timing disabled by default', () => {
+ const { runner } = createRunner();
+ expect(runner.getTimings()).toBeNull();
+ });
+
+ it('should enable timing and return empty map', () => {
+ const { runner } = createRunner();
+ runner.setTimingEnabled(true);
+ expect(runner.getTimings()).toBeInstanceOf(Map);
+ expect(runner.getTimings()!.size).toBe(0);
+ });
+
+ it('should record system execution time when enabled', () => {
+ const { runner } = createRunner();
+ runner.setTimingEnabled(true);
+
+ const system = defineSystem([], () => {
+ let sum = 0;
+ for (let i = 0; i < 1000; i++) sum += i;
+ }, { name: 'TestSystem' });
+
+ runner.run(system);
+
+ const timings = runner.getTimings()!;
+ expect(timings.has('TestSystem')).toBe(true);
+ expect(timings.get('TestSystem')).toBeGreaterThanOrEqual(0);
+ });
+
+ it('should not record timing when disabled', () => {
+ const { runner } = createRunner();
+
+ const system = defineSystem([], () => {}, { name: 'NoTimingSystem' });
+ runner.run(system);
+
+ expect(runner.getTimings()).toBeNull();
+ });
+
+ it('should record timings for multiple systems', () => {
+ const { runner } = createRunner();
+ runner.setTimingEnabled(true);
+
+ const systemA = defineSystem([], () => {}, { name: 'SystemA' });
+ const systemB = defineSystem([], () => {}, { name: 'SystemB' });
+
+ runner.run(systemA);
+ runner.run(systemB);
+
+ const timings = runner.getTimings()!;
+ expect(timings.has('SystemA')).toBe(true);
+ expect(timings.has('SystemB')).toBe(true);
+ });
+
+ it('should overwrite previous timing on re-run', () => {
+ const { runner } = createRunner();
+ runner.setTimingEnabled(true);
+
+ const system = defineSystem([], () => {}, { name: 'RerunSystem' });
+
+ runner.run(system);
+ runner.run(system);
+
+ expect(runner.getTimings()!.has('RerunSystem')).toBe(true);
+ expect(typeof runner.getTimings()!.get('RerunSystem')).toBe('number');
+ });
+
+ it('should disable timing and clear data', () => {
+ const { runner } = createRunner();
+ runner.setTimingEnabled(true);
+
+ const system = defineSystem([], () => {}, { name: 'ClearSystem' });
+ runner.run(system);
+ expect(runner.getTimings()!.size).toBeGreaterThan(0);
+
+ runner.setTimingEnabled(false);
+ expect(runner.getTimings()).toBeNull();
+ });
+
+ it('should still record timing when system throws', () => {
+ const { runner } = createRunner();
+ runner.setTimingEnabled(true);
+
+ const system = defineSystem([], () => {
+ throw new Error('boom');
+ }, { name: 'ThrowSystem' });
+
+ expect(() => runner.run(system)).toThrow('boom');
+ expect(runner.getTimings()!.has('ThrowSystem')).toBe(true);
+ });
+});
+
+// ============================================================================
+// StatsPlugin integration
+// ============================================================================
+
+describe('StatsPlugin', () => {
+ it('should register Stats resource on build', () => {
+ const app = App.new();
+ app.addPlugin(statsPlugin);
+ expect(app.hasResource(Stats)).toBe(true);
+ });
+
+ it('should enable system timings on the app', () => {
+ const app = App.new();
+ app.addPlugin(statsPlugin);
+ app.tick(1 / 60);
+ expect(app.getSystemTimings()).not.toBeNull();
+ });
+
+ it('should have name "Stats"', () => {
+ expect(statsPlugin.name).toBe('Stats');
+ });
+
+ describe('fps & frameTimeMs', () => {
+ it('should compute fps from delta', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ for (let i = 0; i < 10; i++) app.tick(1 / 60);
+
+ const stats = app.getResource(Stats);
+ expect(stats.fps).toBeCloseTo(60, 0);
+ });
+
+ it('should compute frameTimeMs from delta', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ for (let i = 0; i < 5; i++) app.tick(1 / 60);
+
+ const stats = app.getResource(Stats);
+ expect(stats.frameTimeMs).toBeCloseTo(16.67, 0);
+ });
+
+ it('should track changing frame rate', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+
+ for (let i = 0; i < 60; i++) app.tick(1 / 30);
+ expect(app.getResource(Stats).fps).toBeCloseTo(30, 0);
+
+ for (let i = 0; i < 60; i++) app.tick(1 / 120);
+ expect(app.getResource(Stats).fps).toBeCloseTo(120, 0);
+ });
+ });
+
+ describe('entityCount', () => {
+ it('should reflect current entity count', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+
+ app.world.spawn();
+ app.world.spawn();
+ app.world.spawn();
+ app.tick(1 / 60);
+ expect(app.getResource(Stats).entityCount).toBe(3);
+ });
+
+ it('should update after spawn/despawn between ticks', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+
+ const e1 = app.world.spawn();
+ const e2 = app.world.spawn();
+ app.tick(1 / 60);
+ expect(app.getResource(Stats).entityCount).toBe(2);
+
+ app.world.despawn(e1);
+ app.tick(1 / 60);
+ expect(app.getResource(Stats).entityCount).toBe(1);
+
+ app.world.spawn();
+ app.world.spawn();
+ app.tick(1 / 60);
+ expect(app.getResource(Stats).entityCount).toBe(3);
+ });
+
+ it('should be 0 with no entities', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ app.tick(1 / 60);
+ expect(app.getResource(Stats).entityCount).toBe(0);
+ });
+ });
+
+ describe('systemTimings', () => {
+ it('should contain named user systems', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [], () => {}, { name: 'PhysicsSystem' }
+ ));
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [], () => {}, { name: 'AnimationSystem' }
+ ));
+
+ app.tick(1 / 60);
+
+ const timings = app.getResource(Stats).systemTimings;
+ expect(timings.has('PhysicsSystem')).toBe(true);
+ expect(timings.has('AnimationSystem')).toBe(true);
+ });
+
+ it('should not include StatsCollect own timing (measured after snapshot)', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ app.tick(1 / 60);
+
+ const timings = app.getResource(Stats).systemTimings;
+ expect(timings.has('StatsCollect')).toBe(false);
+ });
+
+ it('should record numeric timing values', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [], () => { let s = 0; for (let i = 0; i < 100; i++) s += i; },
+ { name: 'WorkSystem' }
+ ));
+
+ app.tick(1 / 60);
+
+ const ms = app.getResource(Stats).systemTimings.get('WorkSystem');
+ expect(typeof ms).toBe('number');
+ expect(ms).toBeGreaterThanOrEqual(0);
+ });
+
+ it('should be a fresh Map copy (not shared reference)', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ app.tick(1 / 60);
+
+ const stats = app.getResource(Stats);
+ const ref1 = stats.systemTimings;
+ app.tick(1 / 60);
+ const ref2 = stats.systemTimings;
+
+ expect(ref1).not.toBe(ref2);
+ });
+ });
+
+ describe('render stats from Renderer.getStats()', () => {
+ it('should copy all render stats fields', () => {
+ const mockStats: rendererModule.RenderStats = {
+ drawCalls: 42,
+ triangles: 8400,
+ sprites: 100,
+ text: 12,
+ spine: 3,
+ meshes: 5,
+ culled: 7,
+ };
+
+ vi.spyOn(rendererModule.Renderer, 'getStats').mockReturnValue(mockStats);
+
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ app.tick(1 / 60);
+
+ const stats = app.getResource(Stats);
+ expect(stats.drawCalls).toBe(42);
+ expect(stats.triangles).toBe(8400);
+ expect(stats.sprites).toBe(100);
+ expect(stats.text).toBe(12);
+ expect(stats.spine).toBe(3);
+ expect(stats.meshes).toBe(5);
+ expect(stats.culled).toBe(7);
+
+ vi.restoreAllMocks();
+ });
+
+ it('should update render stats each tick', () => {
+ const tick1: rendererModule.RenderStats = {
+ drawCalls: 10, triangles: 2000, sprites: 50,
+ text: 5, spine: 1, meshes: 2, culled: 3,
+ };
+ const tick2: rendererModule.RenderStats = {
+ drawCalls: 20, triangles: 4000, sprites: 80,
+ text: 8, spine: 2, meshes: 4, culled: 6,
+ };
+
+ const spy = vi.spyOn(rendererModule.Renderer, 'getStats');
+ spy.mockReturnValue(tick1);
+
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ app.tick(1 / 60);
+
+ let stats = app.getResource(Stats);
+ expect(stats.drawCalls).toBe(10);
+ expect(stats.sprites).toBe(50);
+
+ spy.mockReturnValue(tick2);
+ app.tick(1 / 60);
+
+ stats = app.getResource(Stats);
+ expect(stats.drawCalls).toBe(20);
+ expect(stats.triangles).toBe(4000);
+ expect(stats.sprites).toBe(80);
+ expect(stats.text).toBe(8);
+ expect(stats.spine).toBe(2);
+ expect(stats.meshes).toBe(4);
+ expect(stats.culled).toBe(6);
+
+ vi.restoreAllMocks();
+ });
+
+ it('should default to zeros when no WASM module', () => {
+ const app = App.new();
+ app.addPlugin(new StatsPlugin());
+ app.tick(1 / 60);
+
+ const stats = app.getResource(Stats);
+ expect(stats.drawCalls).toBe(0);
+ expect(stats.triangles).toBe(0);
+ expect(stats.sprites).toBe(0);
+ expect(stats.text).toBe(0);
+ expect(stats.spine).toBe(0);
+ expect(stats.meshes).toBe(0);
+ expect(stats.culled).toBe(0);
+ });
+ });
+
+ describe('StatsPluginOptions', () => {
+ it('should accept overlay: false without creating DOM', () => {
+ const plugin = new StatsPlugin({ overlay: false });
+ const app = App.new();
+ app.addPlugin(plugin);
+ app.tick(1 / 60);
+
+ const stats = app.getResource(Stats);
+ expect(stats.fps).toBeGreaterThan(0);
+ });
+
+ it('should accept custom position', () => {
+ const plugin = new StatsPlugin({ overlay: false, position: 'top-right' });
+ const app = App.new();
+ app.addPlugin(plugin);
+ app.tick(1 / 60);
+ expect(app.hasResource(Stats)).toBe(true);
+ });
+ });
+
+ describe('cleanup', () => {
+ it('should be callable without error', () => {
+ const plugin = new StatsPlugin({ overlay: false });
+ const app = App.new();
+ app.addPlugin(plugin);
+ app.tick(1 / 60);
+ expect(() => plugin.cleanup()).not.toThrow();
+ });
+ });
+});
+
+// ============================================================================
+// StatsOverlay
+// ============================================================================
+
+describe('StatsOverlay', () => {
+ function makeStats(overrides: Partial<FrameStats> = {}): FrameStats {
+ return {
+ fps: 0, frameTimeMs: 0, entityCount: 0,
+ systemTimings: new Map(),
+ drawCalls: 0, triangles: 0, sprites: 0,
+ text: 0, spine: 0, meshes: 0, culled: 0,
+ ...overrides,
+ };
+ }
+
+ it('should create a DOM element in the container', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ expect(container.children.length).toBe(1);
+ overlay.dispose();
+ });
+
+ it('should position bottom-left by default', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ const el = container.firstElementChild as HTMLElement;
+ expect(el.style.cssText).toContain('bottom');
+ expect(el.style.cssText).toContain('left');
+ overlay.dispose();
+ });
+
+ it('should position top-right when specified', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container, 'top-right');
+ const el = container.firstElementChild as HTMLElement;
+ expect(el.style.cssText).toContain('top');
+ expect(el.style.cssText).toContain('right');
+ overlay.dispose();
+ });
+
+ it('should display FPS value in update', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({ fps: 59.8 }));
+ expect(container.innerHTML).toContain('59.8');
+ overlay.dispose();
+ });
+
+ it('should display frameTimeMs value', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({ frameTimeMs: 16.7 }));
+ expect(container.innerHTML).toContain('16.7');
+ overlay.dispose();
+ });
+
+ it('should display drawCalls', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({ drawCalls: 42 }));
+ expect(container.innerHTML).toContain('42');
+ overlay.dispose();
+ });
+
+ it('should display triangles', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({ triangles: 8400 }));
+ expect(container.innerHTML).toContain('8400');
+ overlay.dispose();
+ });
+
+ it('should display sprites and culled', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({ sprites: 100, culled: 7 }));
+ const html = container.innerHTML;
+ expect(html).toContain('100');
+ expect(html).toContain('7');
+ overlay.dispose();
+ });
+
+ it('should display entityCount', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({ entityCount: 256 }));
+ expect(container.innerHTML).toContain('256');
+ overlay.dispose();
+ });
+
+ it('should display system timings sorted by cost', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({
+ systemTimings: new Map([
+ ['Fast', 0.1],
+ ['Slow', 5.0],
+ ['Medium', 1.5],
+ ]),
+ }));
+
+ const html = container.innerHTML;
+ expect(html).toContain('Slow');
+ expect(html).toContain('Medium');
+ expect(html).toContain('Fast');
+ const slowIdx = html.indexOf('Slow');
+ const medIdx = html.indexOf('Medium');
+ const fastIdx = html.indexOf('Fast');
+ expect(slowIdx).toBeLessThan(medIdx);
+ expect(medIdx).toBeLessThan(fastIdx);
+ overlay.dispose();
+ });
+
+ it('should limit to top 5 systems', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ const timings = new Map<string, number>();
+ for (let i = 0; i < 8; i++) {
+ timings.set(`System${i}`, i);
+ }
+ overlay.update(makeStats({ systemTimings: timings }));
+ const html = container.innerHTML;
+ expect(html).toContain('System7');
+ expect(html).toContain('System3');
+ expect(html).not.toContain('System2');
+ overlay.dispose();
+ });
+
+ it('should not render system section when empty', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats());
+ expect(container.innerHTML).not.toContain('Systems');
+ overlay.dispose();
+ });
+
+ it('should hide and show', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ const el = container.firstElementChild as HTMLElement;
+
+ overlay.hide();
+ expect(el.style.display).toBe('none');
+
+ overlay.update(makeStats({ fps: 60 }));
+ expect(el.innerHTML).toBe('');
+
+ overlay.show();
+ overlay.update(makeStats({ fps: 60 }));
+ expect(el.innerHTML).toContain('60');
+ overlay.dispose();
+ });
+
+ it('should remove element on dispose', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ expect(container.children.length).toBe(1);
+ overlay.dispose();
+ expect(container.children.length).toBe(0);
+ });
+
+ it('should truncate long system names', () => {
+ const container = document.createElement('div');
+ const overlay = new StatsOverlay(container);
+ overlay.update(makeStats({
+ systemTimings: new Map([
+ ['VeryLongSystemNameThatExceedsTwenty', 1.0],
+ ]),
+ }));
+ expect(container.innerHTML).toContain('...');
+ overlay.dispose();
+ });
+});