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 GetWorld() system parameter and split UI docs into sub-pages

esenginedb1328192c3b
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 5b18804ec..b4e6ae6e3 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}function a(e,s){return t().createCanvas(e,s)}function l(){return t().now()}function c(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function d(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function u(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 h=[{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}],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",bmfont:"application/json",fnt:"text/plain"},p=new Map,g=new Set;for(const e of h)for(const t of e.extensions)p.set(t,e),g.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function m(e){return p.get(y(e))}function _(e){return g.has(e.toLowerCase())}function x(){const e=[];for(const t of h)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function w(e){const t=m(e);return t?.wechatPackInclude??!1}let v=null;function b(){return v||(v=wx.getFileSystemManager()),v}function S(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(w(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 P(e){return new Promise((t,s)=>{b().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(S(e,t.errMsg)))}})})}function M(e,t="utf-8"){return new Promise((s,n)=>{b().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(S(e,t.errMsg)))}})})}function T(e){return new Promise(t=>{b().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function E(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let R=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return d(e,t)}async readFile(e){return P(e)}async readTextFile(e){return M(e)}async fileExists(e){return T(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return u(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},I=1920,F=1080,k=1/60,B={x:0,y:-9.81},D=1/60,U={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const L=4294967295,z=4294967295;function W(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(W);const t={};for(const s in e)t[s]=W(e[s]);return t}let $=0;function O(e,t){const s=++$,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?{...W(t),...e}:W(t):e?{...t,...e}:{...t}}}const H=new Map;function X(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const s=G.get(e)??X().get(e);if(s)return s;const n=O(e,t);return X().set(e,n),G.set(e,n),N(e,t,!1),n}function Y(e){return X().get(e)}function N(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function V(e){return!0===e._builtin}const G=new Map;function q(e,t){G.set(e,t)}function K(e){return G.get(e)??Y(e)}function J(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return G.set(e,s),s}const Q={Perspective:0,Orthographic:1},Z={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ee={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},te=J("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}}),se=te,ne=te,re=J("Sprite",{texture:L,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=J("Camera",{projectionType:Q.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:Z.ColorAndDepth}),ie=J("Canvas",{designResolution:{x:I,y:F},pixelsPerUnit:100,scaleMode:ee.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ae=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),le=J("Parent",{entity:0}),ce=J("Children",{entities:[]}),de=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:z,enabled:!0}),ue=J("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}),he=j("Name",{value:""}),fe=j("SceneOwner",{scene:"",persistent:!1});const pe=J("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ge=J("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ye=J("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),me=J("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e={Static:0,Kinematic:1,Dynamic:2};let xe=0;function we(e,t){const s=++xe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ve(e){return{_type:"res",_resource:e}}function be(e){return{_type:"res_mut",_resource:e}}class Se{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 Pe{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 Se(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Me=we({delta:0,elapsed:0,frameCount:0},"Time");function Te(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ee(t[e]),o=Ee(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function Ee(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ce(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 Re=null;function Ae(e){Re=e}function Ie(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Re&&Re(e,t)}function Fe(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 ke=1;const Be=new WeakMap;function De(e){let t=Be.get(e);return void 0===t&&(t=ke++,Be.set(e,t)),t}const Ue=[];function Le(e,t=[],s=[]){Ue.length=0;for(const t of e)Ue.push(De(t));Ue.sort((e,t)=>e-t);let n=Ue.join(",");if(t.length>0){Ue.length=0;for(const e of t)Ue.push(De(e));Ue.sort((e,t)=>e-t),n+="|+"+Ue.join(",")}if(s.length>0){Ue.length=0;for(const e of s)Ue.push(De(e));Ue.sort((e,t)=>e-t),n+="|-"+Ue.join(",")}return n}class ze{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.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 Ie(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_;return this.entities_.set(e,t),this.worldVersion_++,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){Ie(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)}}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){Ie(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ie(t,`removeParent(entity=${e})`)}}insert(e,t,s){return V(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(V(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Fe(s))}catch(s){Ie(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 V(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return V(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(V(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ie(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.");V(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:r.bind(s),has:o.bind(s),remove:i.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Te(t._name,t._default,n);if(e.length>0)throw new Error(Ce(t._name,e))}const r={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Fe(r))}catch(s){Ie(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const r=t[n];if(null!=r&&"object"==typeof r&&!Array.isArray(r)&&"r"in r&&"g"in r&&"b"in r&&"a"in r){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const r=e[s],o=t[s];if(null==r||"object"!=typeof r||Array.isArray(r)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=r;else{const e=r,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:r}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ie(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 Ie(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ie(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Te(t._name,t._default,e);if(r.length>0)throw new Error(Ce(t._name,r));n=e}const r=t.create(n),o=this.getStorage(t),i=!o.has(e);o.set(e,r);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),i&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of G)if(V(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=X();for(const n of s)for(const[s,r]of e)if(r._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const r=n??Le(e,t,s),o=this.queryCache_.get(r);if(o&&o.version===this.worldVersion_)return o.result;let i=null,a=1/0;for(const t of e)if(!V(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=i?i.keys():this.entities_.keys();for(const n of c){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}if(r)for(const e of t)if(!this.has(n,e)){r=!1;break}if(r)for(const e of s)if(this.has(n,e)){r=!1;break}r&&l.push(n)}return this.queryCache_.set(r,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function We(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function $e(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Oe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function He(e){return We(e)||$e(e)||Oe(e)?e._component:e}function Xe(e,t=[],s=[]){const n=[],r=[],o=[];return e.forEach((e,t)=>{We(e)&&n.push(t),$e(e)?r.push({index:t,component:e._component}):Oe(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:r,_changedFilters:o,with:(...n)=>Xe(e,[...t,...n],s),without:(...n)=>Xe(e,t,[...s,...n])}}class je{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(He),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_=Le(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,r=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,i=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}i[0]=d;for(let e=0;e<n;e++)i[e+1]=this.world_.get(d,t[e]);if(r){for(let t=0;t<l;t++)a[t].data=i[e[t]+1];c=d}yield i}}finally{if(this.world_.endIteration(),null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class 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 Ne{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=V(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 Ve{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ne(this,null);return this.spawned_.push(e),e}entity(e){return new Ne(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class Ge{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 qe{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ge)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ge,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Ke{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Je{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Qe;exports.Schedule=void 0,(Qe=exports.Schedule||(exports.Schedule={}))[Qe.Startup=0]="Startup",Qe[Qe.First=1]="First",Qe[Qe.PreUpdate=2]="PreUpdate",Qe[Qe.Update=3]="Update",Qe[Qe.PostUpdate=4]="PostUpdate",Qe[Qe.Last=5]="Last",Qe[Qe.FixedPreUpdate=10]="FixedPreUpdate",Qe[Qe.FixedUpdate=11]="FixedUpdate",Qe[Qe.FixedPostUpdate=12]="FixedPostUpdate";let Ze=0;function et(e,t,s){const n=++Ze;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function tt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class st{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 Ve&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new je(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 Ve(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 Ke(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Je(s)}case"removed":{const t=e;return new Ye(this.world_,t._component,this.currentLastRunTick_)}default:throw new Error("Unknown system parameter type")}}}class nt{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=we(new nt,"Input");class ot{constructor(e){this.target_=e??null}build(e){const s=new nt;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,et([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const it=new ot,at=we({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 lt;function ct(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(lt=exports.BlendMode||(exports.BlendMode={}))[lt.Normal=0]="Normal",lt[lt.Additive=1]="Additive",lt[lt.Multiply=2]="Multiply",lt[lt.Screen=3]="Screen",lt[lt.PremultipliedAlpha=4]="PremultipliedAlpha";let dt=null,ut=null,ht=1;const ft=new Map;function pt(e){dt=e,ut=e.getResourceManager(),Pt()}function gt(){0!==xt&&dt&&(dt._free(xt),xt=0),ft.clear(),ht=1,_t=!1,vt.clear(),bt=null,ut=null,dt=null}function yt(){if(!ut)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ut}const mt={createShader:(e,t)=>yt().createShader(e,t),releaseShader(e){e>0&&yt().releaseShader(e)},create(e){const t=ht++,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 ft.set(t,s),t},get:e=>ft.get(e),setUniform(e,t,s){const n=ft.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,dt?.invalidateMaterialCache(e))},getUniform(e,t){const s=ft.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=ft.get(e);s&&(s.blendMode=t,dt?.invalidateMaterialCache(e))},getBlendMode(e){const t=ft.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=ft.get(e);s&&(s.depthTest=t,dt?.invalidateMaterialCache(e))},getShader(e){const t=ft.get(e);return t?.shader??0},release(e){ft.delete(e),dt?.invalidateMaterialCache(e)},isValid:e=>ft.has(e),releaseAll(){ft.clear(),dt?.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=ft.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ht++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return ft.set(s,n),s},toAssetData(e,t){const s=ft.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=ft.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let _t=!1,xt=0;const wt=16384,vt=new Map;let bt=null;function St(e){const t=(0===xt&&dt&&(xt=dt._malloc(wt)),xt);if(0===t||!dt)return{ptr:0,count:0};let s=0,n=0;const r=dt.HEAPU8,o=dt.HEAPU32,i=dt.HEAPF32;for(const[a,l]of e){if(ct(l))continue;let e=vt.get(a);e||(bt||(bt=new TextEncoder),e=bt.encode(a),vt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>wt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${wt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Pt(){if(!dt||_t)return;dt.materialDataProvider=(e,t,s,n,r)=>{const o=ft.get(e);if(!o)return dt.HEAPU32[t>>2]=0,dt.HEAPU32[s>>2]=0,dt.HEAPU32[n>>2]=0,void(dt.HEAPU32[r>>2]=0);dt.HEAPU32[t>>2]=o.shader,dt.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=St(o.uniforms);dt.HEAPU32[n>>2]=i,dt.HEAPU32[r>>2]=a},_t=!0}const Mt={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 Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Et{constructor(e,t=""){this.cache_=new Tt,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&&(mt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())mt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:mt.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}}const Ct=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"}]}]]);function Rt(e){return Ct.get(e)?.fields??[]}function At(e){return Ct.get(e)?.spine??null}const It=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ft(e){return It.get(e)}function kt(e,t){const s=It.get(e.type);if(!s)return;const n=e.data;for(const r of s){const s=n[r];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${r} references entity ${s} which does not exist`),n[r]=void 0!==o?o:0}}}function Bt(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,he,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)kt(r,s),zt(e,t,r,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}function Dt(e,t){return Bt(e,t)}async function Ut(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl,o=new Map;n&&await async function(e,t,s,n,r){e=JSON.parse(JSON.stringify(e));const o=new Map;for(const e of Lt.keys())o.set(e,new Set);const i=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),i.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Lt.entries()].map(async([e,r])=>{const i=await r.load(o.get(e),t,s,n);l.set(e,i)}),d=i.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),r){for(const e of n.values())r.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&r.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)r.fontPaths.add(e);for(const e of a)r.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&(s[e.field]=l.get(e.type)?.get(t)??0)}}}(t,n,r,o,s?.collectAssets);const i=Bt(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return i}const Lt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}]]);function zt(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const r=K(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class Wt{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Tt,this.prefabCache_=new Tt,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.module_=e,this.canvas_=a(U.textCanvasSize,U.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 Et(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),mt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===m(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=m(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(r,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const 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.embedded_.get(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.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const $t=we(null,"Assets");class Ot{build(e){const t=e.wasmModule;t?e.insertResource($t,new Wt(t)):console.warn("AssetPlugin: No WASM module available")}}const Ht=new Ot;async function Xt(e,t,s){const{entities:n,rootId:r}=await Yt(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const jt=10;async function Yt(e,t,s,n,r,o=0){if(o>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Yt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u.components,i),Vt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Nt(e,t){for(const s of e){const e=Ft(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const r=t.get(e);void 0!==r&&(s.data[n]=r)}}}}function Vt(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 Gt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Xt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const qt=we(null,"Prefabs");class Kt{constructor(){this.name="PrefabsPlugin",this.dependencies=[$t]}build(e){const t=e.getResource($t);e.insertResource(qt,new Gt(e.world,t))}}const Jt=new Kt;let Qt=null,Zt=0,es=0,ts=0;const ss=new Float32Array(256);function ns(e){Qt=e,Zt=Qt._malloc(64),es=Qt._malloc(64),ts=Qt._malloc(1024)}function rs(){Qt&&(Zt&&(Qt._free(Zt),Zt=0),es&&(Qt._free(es),es=0),ts&&(Qt._free(ts),ts=0)),Qt=null}function os(){if(!Qt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Qt}const is={r:1,g:1,b:1,a:1},as={begin(e){const t=os();try{t.HEAPF32.set(e,Zt/4),t.draw_begin(Zt)}catch(e){Ie(e,"Draw.begin")}},end(){try{os().draw_end()}catch(e){Ie(e,"Draw.end")}},line(e,t,s,n=1){try{os().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.line")}},rect(e,t,s,n=!0){try{os().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{os().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{os().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{os().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circleOutline")}},texture(e,t,s,n=is){try{os().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ie(e,"Draw.texture")}},textureRotated(e,t,s,n,r=is){try{os().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ie(e,"Draw.textureRotated")}},setLayer(e){os().draw_setLayer(e)},setDepth(e){os().draw_setDepth(e)},getDrawCallCount:()=>Qt?Qt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Qt?Qt.draw_getPrimitiveCount():0,setBlendMode(e){os().draw_setBlendMode(e)},setDepthTest(e){os().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=os();n.HEAPF32.set(s,es/4),n.draw_mesh(e,t,es)}catch(s){Ie(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=os(),r=mt.get(t);if(!r)return;if(as.setBlendMode(r.blendMode),as.setDepthTest(r.depthTest),0===r.uniforms.size)return void as.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,es/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ds(t);if(!(n<0)){if(ct(s))ss[o++]=10,ss[o++]=n,ss[o++]=s.slot??e++,ss[o++]=s.textureId;else if("number"==typeof s)ss[o++]=1,ss[o++]=n,ss[o++]=s;else if(Array.isArray(s)){ss[o++]=s.length,ss[o++]=n;for(let e=0;e<s.length;e++)ss[o++]=s[e]}else"w"in s?(ss[o++]=4,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y,ss[o++]=s.z,ss[o++]=s.w):"z"in s?(ss[o++]=3,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y,ss[o++]=s.z):(ss[o++]=2,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(ss.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,es);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),ts/4),n.draw_meshWithUniforms(e,r.shader,es,ts,o)}catch(s){Ie(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ls={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},cs=new Set;function ds(e){const t=ls[e];return void 0!==t?t:(cs.has(e)||(cs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ls).join(", ")}`)),-1)}const us=new Map;function hs(e,t,s){us.set(e,{fn:t,scene:s??""})}function fs(e){us.delete(e)}function ps(){us.clear()}var gs;exports.DataType=void 0,(gs=exports.DataType||(exports.DataType={}))[gs.Float=1]="Float",gs[gs.Float2=2]="Float2",gs[gs.Float3=3]="Float3",gs[gs.Float4=4]="Float4",gs[gs.Int=5]="Int",gs[gs.Int2=6]="Int2",gs[gs.Int3=7]="Int3",gs[gs.Int4=8]="Int4";let ys=null,ms=0,_s=0,xs=0;function ws(e){ys=e,ms=ys._malloc(262144),_s=ys._malloc(65536),xs=ys._malloc(256)}function vs(){ys&&(ms&&ys._free(ms),_s&&ys._free(_s),xs&&ys._free(xs),ms=0,_s=0,xs=0),ys=null}function bs(){if(!ys)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ys}const Ss={create(e){const t=bs(),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,ms/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,xs,r).set(o),t.geometry_init(s,ms,n,xs,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=bs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ms/4),n.geometry_updateVertices(e,ms,r,s)},release(e){e>0&&bs().geometry_release(e)},isValid:e=>!(!ys||e<=0)&&ys.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ss.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ss.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Ss.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Ps=null;function Ms(e){Ps=e}function Ts(){Ps&&Cs.isInitialized()&&Cs.shutdown(),Ps=null}function Es(){if(!Ps)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ps}const Cs={init(e,t){try{return Es().postprocess_init(e,t)}catch(s){return Ie(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Es().postprocess_shutdown()}catch(e){Ie(e,"PostProcess.shutdown")}},resize(e,t){try{Es().postprocess_resize(e,t)}catch(s){Ie(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Es().postprocess_addPass(e,t)}catch(t){return Ie(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Es().postprocess_removePass(e)}catch(t){Ie(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Es().postprocess_setPassEnabled(e,t)}catch(t){Ie(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Es().postprocess_isPassEnabled(e)}catch(t){return Ie(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Es().postprocess_setUniformFloat(e,t,s)}catch(s){Ie(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ie(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Es().postprocess_begin()}catch(e){Ie(e,"PostProcess.begin")}},end(){try{Es().postprocess_end()}catch(e){Ie(e,"PostProcess.end")}},getPassCount(){try{return Es().postprocess_getPassCount()}catch(e){return Ie(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ps)return!1;try{return Ps.postprocess_isInitialized()}catch(e){return Ie(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Es().postprocess_setBypass(e)}catch(e){Ie(e,"PostProcess.setBypass")}},isBypassed(){if(!Ps)return!0;try{return Ps.postprocess_isBypassed()}catch(e){return Ie(e,"PostProcess.isBypassed"),!0}},createBlur:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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")},Rs="#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 As;exports.RenderStage=void 0,(As=exports.RenderStage||(exports.RenderStage={}))[As.Background=0]="Background",As[As.Opaque=1]="Opaque",As[As.Transparent=2]="Transparent",As[As.Overlay=3]="Overlay";let Is=null,Fs=0;function ks(e){Is=e,Fs=Is._malloc(64)}function Bs(){Is&&Fs&&(Is._free(Fs),Fs=0),Is=null}const Ds={init(e,t){Is?.renderer_init(e,t)},resize(e,t){Is?.renderer_resize(e,t)},begin(e,t){if(Is&&Fs)try{Is.HEAPF32.set(e,Fs/4),Is.renderer_begin(Fs,t??0)}catch(e){Ie(e,"Renderer.begin")}},flush(){try{Is?.renderer_flush()}catch(e){Ie(e,"Renderer.flush")}},end(){try{Is?.renderer_end()}catch(e){Ie(e,"Renderer.end")}},submitSprites(e){if(Is)try{Is.renderer_submitSprites(e._cpp)}catch(e){Ie(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Is)try{Is.renderer_submitBitmapText(e._cpp)}catch(e){Ie(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Is)try{Is.renderer_submitSpine?.(e._cpp)}catch(e){Ie(e,"Renderer.submitSpine")}},setStage(e){Is?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Is?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Is?.renderer_releaseTarget(e)},getTargetTexture:e=>Is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Is?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Is?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Is?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Is?Is.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Is?{drawCalls:Is.renderer_getDrawCalls(),triangles:Is.renderer_getTriangles(),sprites:Is.renderer_getSprites(),text:Is.renderer_getText(),spine:Is.renderer_getSpine?.()??0,meshes:Is.renderer_getMeshes(),culled:Is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Us=null;function Ls(e){Us=e}function zs(){Us=null}const Ws={enable(){Us?.gl_enableErrorCheck(!0)},disable(){Us?.gl_enableErrorCheck(!1)},check:e=>Us?.gl_checkErrors(e)??0,diagnose(){Us?.renderer_diagnose()}};class $s{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ds.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ds.setViewport(0,0,n,r),Ds.clearBuffers(3),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ds.setViewport(n.x,n.y,n.w,n.h),Ds.setScissor(n.x,n.y,n.w,n.h,!0),Ds.clearBuffers(r),Ds.setScissor(0,0,0,0,!1),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}executeDrawCallbacks(e,t){const s=us;if(s.size>0){as.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}as.end();for(const e of n)fs(e)}}}const Os="__scene_transition_overlay__";class Hs{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 Xs{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,fe,{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 s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.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,fe)){const s=this.app_.world.get(e,fe);s.persistent=t,this.app_.world.insert(e,fe,s)}}}class js{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??U.sceneTransitionDuration,r=t.color??{...U.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},hs(Os,()=>{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;as.setLayer(9999),as.setDepth(9999),as.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,fs(Os),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,fs(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 s=new Hs(t);this.scenes_.set(e,s);const n=new Xs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource($t)?this.app_.getResource($t):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Hs(t);this.scenes_.set(e,s);const n=new Xs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource($t)?this.app_.getResource($t):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,fe)){if(this.app_.world.get(e,fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())fs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:s};this.app_.hasResource($t)&&(r.assetServer=this.app_.getResource($t));const o=await Ut(this.app_.world,n,r);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,fe,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Ns(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const r=this.contexts_.get(t);s.setup&&await s.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource($t)?this.app_.getResource($t):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)mt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let r=!1;if(s.has(e,re)){const t=s.get(e,re);n.sprite=t.color.a,t.color.a=0,s.insert(e,re,t),r=!0}if(s.has(e,ue)){const t=s.get(e,ue);n.spine=t.color.a,t.color.a=0,s.insert(e,ue,t),r=!0}if(s.has(e,de)){const t=s.get(e,de);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,de,t),r=!0}r&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,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,ue)){const t=s.get(e,ue);t.color.a=n.spine,s.insert(e,ue,t)}if(void 0!==n.bitmapText&&s.has(e,de)){const t=s.get(e,de);t.color.a=n.bitmapText,s.insert(e,de,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.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 Ys=we(null,"SceneManager");function Ns(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ys).getSceneStatus(t)&&s._fn(...n)}}}const Vs=et([be(Ys),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Gs={name:"SceneManager",build(e){const t=new js(e);e.insertResource(Ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ys),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,Vs)}};class qs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new qe,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=l(),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 ze,this.resources_=new Pe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qs}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,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)}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 Ae(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(Ys).register(e),this}setInitialScene(e){return this.getResource(Ys).setInitial(e),this}tick(e){this.runner_||(this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Me)||this.resources_.insert(Me,{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.runSchedule(exports.Schedule.First),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=l(),this.mainLoop())}quit(){this.running_=!1,ps();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[zs,Bs,Ts,vs,gt,rs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Me);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ks=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Js(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case ee.FixedWidth:return o;case ee.FixedHeight:return i;case ee.Expand:return Math.max(o,i);case ee.Shrink:return Math.min(o,i);case ee.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}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 en(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,fe);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getTransform(e),i=r.viewportW*s/(r.viewportH*n);let a,d=0,u=0;if(r.projectionType===Q.Orthographic){if(u=r.orthoSize,l){u=Js(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,i,l.scaleMode,l.matchWidthOrHeight)}d=u*i,a=sn(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=rn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=an(o.position.x,o.position.y,o.position.z),f=Zs(c.length);f.entity=e,f.viewProjection.set(cn(a,h)),f.viewportRect.x=r.viewportX,f.viewportRect.y=r.viewportY,f.viewportRect.w=r.viewportW,f.viewportRect.h=r.viewportH,f.clearFlags=r.clearFlags,f.priority=r.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const tn=new Float32Array(16);function sn(e,t,s,n,r,o){const i=tn;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const nn=new Float32Array(16);function rn(e,t,s,n){const r=nn;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const on=new Float32Array(16);function an(e,t,s){const n=on;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 ln=new Float32Array(16);function cn(e,t){const s=ln;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const dn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function un(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+s.x-r.x*i.x,g=f+r.x):(f=c+s.x,g=d+n.x),e.y===t.y?(p=u+s.y-r.y*i.y,y=p+r.y):(p=u+s.y,y=h+n.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const hn=J("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 fn=null,pn=null;function gn(e,t){e.has(t,re)||e.insert(t,re,{texture:L,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 yn(e,t){switch(e){case dn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case dn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case dn.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 mn(e,t,s,n){if(!e.has(t,hn))return;const r=e.get(t,hn),o=yn(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,hn,r)}function _n(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function xn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function wn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(xn(i.charCodeAt(0))&&n.length>0&&xn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!xn(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function vn(e){let t=1;for(;t<e;)t*=2;return t}function bn(e,t){let s=0,n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;s++,n=t}return s}function Sn(e,t){if(fn&&pn){const e=fn.getUIRectComputedWidth(pn,t);if(e>0)return e}return e.size.x}function Pn(e,t){if(fn&&pn){const e=fn.getUIRectComputedHeight(pn,t);if(e>0)return e}return e.size.y}function Mn(e,t,s){let n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Tn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function En(e,t,s,n,r){if(!e.has(t,hn))return;const o=e.get(t,hn),i=un(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(e.has(t,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,te)){const s=e.get(t,te);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,te,s)}}function Cn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const Rn=.1,An=30,In={r:.3,g:.5,b:.8,a:1},Fn={Left:0,Center:1,Right:2},kn={Top:0,Middle:1,Bottom:2},Bn={Visible:0,Clip:1,Ellipsis:2},Dn=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Fn.Left,verticalAlign:kn.Top,wordWrap:!0,overflow:Bn.Visible,lineHeight:1.2});class Un{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=a(U.textCanvasSize,U.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,vn(this.frameMaxW_)),e.height=Math.max(e.height,vn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=vn(this.frameMaxW_),e.height=vn(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=wn(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),f=r?Math.ceil(o):u+2*d,p=r?Math.ceil(i):h+2*d;if(r&&e.overflow===Bn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,vn(f)),n.height=Math.max(n.height,vn(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Bn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case kn.Top:w=d;break;case kn.Middle:w=d+(p-2*d-x)/2;break;case kn.Bottom:w=p-x-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case Fn.Left:n=d;break;case Fn.Center:n=f/2;break;case Fn.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Bn.Clip&&s.restore();const b=s.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 s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Fn.Left:return"left";case Fn.Center:return"center";case Fn.Right:return"right"}}}const Ln=Cn({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?Sn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Pn(e.uiRect,e.entity):0});class zn{build(e){q("Text",Dn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Un(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Dn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,Dn)){if(n.valid(e)&&n.has(e,re)){const t=n.get(e,re);n.insert(e,re,{texture:L,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}r.delete(e)}const e=n.getEntitiesWithComponents([Dn]);for(const t of e){const e=n.get(t,Dn),o=n.has(t,hn)?n.get(t,hn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!Ln.changed(a,i)){if(n.has(t,re)&&n.get(t,re).texture!==L)continue}gn(n,t);const l=o?{size:{x:Sn(o,t),y:Pn(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,re);n.insert(t,re,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),r.set(t,Ln.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Wn=new zn,$n=0,On=1,Hn=J("UIMask",{enabled:!0,mode:$n});function Xn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function jn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,M=u*y-h*g,T=u*m-f*g,E=u*_-p*g,C=h*m-f*y,R=h*_-p*y,A=f*_-p*m;let I=x*A-w*R+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*A-c*R+d*C)*I,s[1]=(o*R-r*A-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(c*E-a*A-d*T)*I,s[5]=(n*A-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-f*v+p*w)*I,s[8]=(a*R-l*E+d*M)*I,s[9]=(r*E-n*R-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-p*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+f*x)*I),s}function Yn(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function Nn(e,t){return 2*Math.atan2(e,t)}function Vn(e,t,s,n,r,o,i){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function Gn(e,t,s,n,r,o,i){if(!e.has(t,hn)||!e.has(t,te))return null;const a=e.get(t,hn),l=e.get(t,te),c=Sn(a,t)*l.worldScale.x,d=Pn(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),x=Nn(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+g*w-m*v,h+g*v+m*w],[u+y*w-m*v,h+y*v+m*w],[u+y*w-_*v,h+y*v+_*w],[u+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Vn(e,t,s,n,r,o,i);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function qn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Hn]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Hn);s.enabled&&(u.add(e),s.mode===On?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0;Mn(t,e,e=>{if(r.has(e)){if(t.get(e,Hn).mode===$n)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if(t.get(s,Hn).mode===$n){const e=Gn(t,s,o,i,a,l,c);e&&(n=Xn(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Gn(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Mn(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Kn{build(e){if(q("UIMask",Hn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(qn(e.wasmModule,e.world))}}const Jn=new Kn,Qn=J("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Zn=J("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),er={Normal:0,Hovered:1,Pressed:2,Disabled:3},tr=j("Button",{state:er.Normal,transition:null});class sr{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 nr=we(new sr,"UIEvents");class rr{build(e){q("UIRect",hn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){fn=e,pn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],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,et([ve(at)],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,et([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const or=new rr;let ir=!1,ar=!1;function lr(){return ir}function cr(){return ar}const dr=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&&(jn(t,e),s=!1),e)}}();function ur(e,t,s,n){t.emit(s,n,s),Mn(e,s,r=>{if(!e.has(r,Qn))return!1;const o=e.get(r,Qn);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class hr{build(e){q("Interactable",Qn),q("Button",tr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new sr;e.insertResource(nr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,a)=>{if(r.drain(),lr()&&!cr())return;const l=t.getEntitiesWithComponents([Zn]);for(const e of l){const s=t.get(e,Zn);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Zn,s))}if(!a.valid)return;const d=c(),u=e.mouseX*d,h=a.screenH-e.mouseY*d;dr.update(a.viewProjection);const f=Yn(u,h,dr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=f.x,a.worldMouseY=f.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);s.uiHitTest_update(n,f.x,f.y,p,g,y);const m=s.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Zn)){const e=t.get(o,Zn);e.hovered=!1,t.insert(o,Zn,e),r.emit(o,"hover_exit")}if(null!==_){Tn(t,_,Zn);const e=t.get(_,Zn);e.hovered=!0,t.insert(_,Zn,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,Zn);e.pressed=!0,e.justPressed=!0,t.insert(_,Zn,e),i=_,ur(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,Zn)){const e=t.get(i,Zn);e.pressed=!1,e.justReleased=!0,t.insert(i,Zn,e),ur(t,r,i,"release"),i===o&&ur(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([],()=>{const e=t.getEntitiesWithComponents([tr]);for(const s of e){if(Tn(t,s,Qn,{enabled:!0}),!t.has(s,Zn))continue;const e=t.get(s,Zn),n=t.get(s,tr),r=t.get(s,Qn),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=er.Pressed:e.hovered?n.state=er.Hovered:n.state=er.Normal:n.state=er.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=_n(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const fr=new hr,pr=j("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}),gr=j("Focusable",{tabIndex:0,isFocused:!1});class yr{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 mr=we(new yr,"FocusManager");class _r{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(q("TextInput",pr),lr()&&!cr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=a(U.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=0,l=0,c=!1,d=!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 g(){const t=e.getResource(mr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,pr)?n:null}const y=()=>{c||null===g()||v()},m=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=g();if(null===n)return;if("Escape"===t.key)return void b();const r=s.get(n,pr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(nr).emit(n,"submit"),void b()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,r.dirty=!0,S())},w=()=>{const t=g();if(null!==t){const n=s.get(t,pr);n.focused=!1,n.dirty=!0;e.getResource(mr).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,pr);if(n.readOnly)return;let r=p.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),p.value=r),r!==n.value){n.value=r;e.getResource(nr).emit(t,"change")}n.cursorPos=p.selectionStart??r.length,n.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=s.get(t,pr);e.focused=!1,e.dirty=!0}e.getResource(mr).blur(),p.blur()}function S(){d=!0,u=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",x),p.addEventListener("blur",w),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",x),p.removeEventListener("blur",w),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==i&&(t._free(i),i=0,l=0)};let P=null;function M(e,a,c,u){(r.width<c||r.height<u)&&(r.width=vn(Math.max(r.width,c)),r.height=vn(Math.max(r.height,u))),o.clearRect(0,0,r.width,r.height);const h=a.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(a.padding,0,c-2*a.padding,u),o.clip(),o.font=`${a.fontSize}px ${a.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===a.value.length,p=f?a.placeholder:a.password?"●".repeat(a.value.length):a.value,g=f?a.placeholderColor:a.color;o.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*a.fontSize),m=a.padding;if(a.multiline){const e=wn(o,p,c-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=y}else{const e=(u-a.fontSize)/2;o.fillText(p,m,e)}if(a.focused&&d){const e=a.password?"●".repeat(a.cursorPos):a.value.substring(0,a.cursorPos);let t,s,n;if(a.multiline){const e=wn(o,a.value,c-2*m);let r=0,i=0,l=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=a.cursorPos){i=t,l=a.cursorPos-r;break}r+=s,t<e.length-1&&r<a.value.length&&"\n"===a.value[r]&&r++,i=t+1,l=0}const d=i<e.length?e[i].substring(0,l):"";t=m+o.measureText(d).width,s=m+i*y,n=y}else t=m+o.measureText(e).width,s=(u-a.fontSize)/2,n=a.fontSize;o.fillStyle=`rgba(${Math.round(255*a.color.r)}, ${Math.round(255*a.color.g)}, ${Math.round(255*a.color.b)}, ${a.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>l&&(0!==i&&t._free(i),i=t._malloc(x.length),l=x.length),t.HEAPU8.set(x,i);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,u,i,x.length,1,!0);n.set(e,b);const S=s.get(e,re);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,re,S)}e.addSystemToSchedule(exports.Schedule.Update,et([ve(mr)],e=>{const t=s.getEntitiesWithComponents([pr]);for(const e of t)Tn(s,e,gr,{tabIndex:0,isFocused:!1}),Tn(s,e,Qn,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,pr)){const e=s.get(P,pr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,pr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===h?0:(e-h)/1e3;h=e,r=Math.min(r,.1);const o=g();if(null!==o&&(u+=r,u>=.5)){u-=.5,d=!d;s.get(o,pr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,pr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([pr,hn]);for(const e of a){const t=s.get(e,pr);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(gn(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const xr=new _r,wr={Simple:0,Sliced:1,Tiled:2,Filled:3},vr={Horizontal:0,Vertical:1},br={Left:0,Right:1,Bottom:2,Top:3},Sr=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:wr.Simple,fillMethod:vr.Horizontal,fillOrigin:br.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Pr=Cn({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?Sn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Pn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Mr=new class{build(e){q("Image",Sr);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Sr)||s.delete(e);const e=t.getEntitiesWithComponents([Sr]);for(const n of e){const e=t.get(n,Sr),r=t.has(n,hn)?t.get(n,hn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!Pr.changed(i,o))continue;gn(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,r&&(a.size.x=Sn(r,n),a.size.y=Pn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===wr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===vr.Horizontal?e.fillOrigin===br.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===br.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===wr.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,Pr.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,Pr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Tr=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Er=j("ToggleGroup",{allowSwitchOff:!1});const Cr=new class{build(e){q("Toggle",Tr),q("ToggleGroup",Er);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([ve(nr)],e=>{const n=t.getEntitiesWithComponents([Tr]);if(!lr()||cr()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Tr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Tr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Tr);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(Tn(t,s,Qn,{enabled:!0}),!t.has(s,Zn))continue;const n=t.get(s,Zn),r=t.get(s,Tr),i=t.get(s,Qn);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Er);if(r.isOn&&i){if(!t.get(n,Er).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Tr,r),r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,Tr);r.isOn&&(r.isOn=!1,t.insert(n,Tr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=_n(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,Tr);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"]})}},Rr=dn,Ar=j("ProgressBar",{value:0,fillEntity:0,direction:dn.LeftToRight});function Ir(e,t,s,n){if(!e.has(t,hn))return;const r=e.get(t,hn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=un(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,a,r.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,te)){const s=e.get(t,te),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,te,s))}}class Fr{build(e){q("ProgressBar",Ar);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([Ar,hn]);for(const s of e){const e=t.get(s,Ar);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,hn),r=Math.max(0,Math.min(1,e.value));mn(t,e.fillEntity,e.direction,r);const o=Sn(n,s),i=Pn(n,s);Ir(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const kr=new Fr,Br=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Dr=j("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 Ur=new class{build(e){q("Draggable",Br),q("DragState",Dr);const t=e.world,s=e.getResource(nr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,i)=>{if(lr()&&!cr())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Br,Zn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Br).enabled)continue;if(t.get(n,Zn).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=bn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,Dr)||t.insert(s,Dr);const e=t.get(s,Dr),o=t.get(s,te);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,Dr)){t.get(n,Dr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Br);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Dr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Dr))return void(o=null);const n=t.get(o,Dr),r=t.get(o,Br),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,te)){const e=function(e,t,s,n){if(!e.has(t,le))return{x:s,y:n};const r=e.get(t,le).entity;if(!e.valid(r)||!e.has(r,te))return{x:s,y:n};const o=e.get(r,te),i=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Nn(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,te);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,te,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Lr=j("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function zr(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 Wr(e,t,s,n,r){const o=2/(n=Math.max(1e-4,n)),i=o*r,a=1/(1+i+.48*i*i+.235*i*i*i),l=e-t,c=(s+o*l)*r,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const $r=new class{build(e){q("ScrollView",Lr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt),ve(at),ve(Me)],(e,r,o)=>{const i=lr()&&!cr(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);r.valid&&(n.x=r.worldMouseX,n.y=r.worldMouseY);const l=t.getEntitiesWithComponents([Lr,hn]);for(const o of l){Tn(t,o,Hn,{enabled:!0,mode:$n});const l=t.get(o,Lr),c=t.get(o,hn);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=Sn(c,o),h=Pn(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,ce)){const e=t.get(l.contentEntity,ce).entities;let s=0,n=0,r=0,o=0;for(const i of e){if(!t.valid(i)||!t.has(i,te))continue;const e=t.get(i,te);let a=0,l=0,c=.5,d=.5;if(t.has(i,hn)){const e=t.get(i,hn);a=Sn(e,i)||e.size.x,l=Pn(e,i)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(i,re)){const e=t.get(i,re);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),f<r&&(r=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-r)}const g=Math.max(0,f-u),y=Math.max(0,p-h);if(!i&&r.valid){Tn(t,o,Qn,{enabled:!0,blockRaycast:!0});const s=t.has(o,Zn)?t.get(o,Zn):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=zr(l.scrollX,0,g,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=zr(l.scrollY,0,y,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=zr(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=zr(l.scrollX,0,g,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Wr(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)<Rn&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Rn?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Wr(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)<Rn&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Rn?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,te)){const e=t.get(l.contentEntity,te),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,te,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Or=dn,Hr=j("Slider",{value:0,minValue:0,maxValue:1,direction:dn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Xr(e,t,s,n,r,o){const i=Sn(n,r)*s.worldScale.x,a=Pn(n,r)*s.worldScale.y,l=Nn(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,f=u*d-h*c,p=u*c+h*d,g=-n.pivot.x*i,y=-n.pivot.y*a;switch(o){case dn.LeftToRight:return i>0?(f-g)/i:0;case dn.RightToLeft:return i>0?1-(f-g)/i:0;case dn.BottomToTop:return a>0?(p-y)/a:0;case dn.TopToBottom:return a>0?1-(p-y)/a:0}}function jr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case dn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case dn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case dn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case dn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Yr{build(e){q("Slider",Hr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at),ve(nr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([Hr,hn]);for(const i of o){const o=t.get(i,Hr),a=t.get(i,hn);if(!lr()||cr()){if(t.has(i,te)){Tn(t,i,Qn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Tn(t,o.handleEntity,Qn,{enabled:!0,blockRaycast:!1});const l=t.get(i,te),c=t.has(i,Zn)?t.get(i,Zn):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Zn)&&(d=t.get(o.handleEntity,Zn).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=Xr(n.worldMouseX,n.worldMouseY,l,a,i,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(i,Hr,o),o.value!==c&&r.emit(i,"change")}s===i&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Sn(a,i),u=Pn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(mn(t,o.fillEntity,o.direction,c),En(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,hn)){const e=t.get(o.handleEntity,hn);jr(e,o.direction,c),t.insert(o.handleEntity,hn,e),En(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nr=new Yr;const Vr=new class{build(e){q("Focusable",gr);const t=e.world,s=new yr;e.insertResource(mr,s),e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(nr)],(e,n)=>{if(lr()&&!cr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([gr]);for(const e of r){if(!t.has(e,Zn))continue;t.get(e,Zn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,Qn)){if(!t.get(s,Qn).enabled)continue}const n=t.get(s,gr);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,gr)){t.get(r,gr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,gr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Gr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function qr(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const Kr=new class{build(e){q("SafeArea",Gr);const t=e.world;let n=qr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=qr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=qr(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=c(),d=s()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Gr,hn]);for(const e of u){const s=t.get(e,Gr),r=t.get(e,hn),o=s.applyTop?n.top*d:0,i=s.applyBottom?n.bottom*d:0,a=s.applyLeft?n.left*d:0,l=s.applyRight?n.right*d:0;let c=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},c=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},c=!0),c&&t.insert(e,hn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Jr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Qr=null;const Zr=new class{build(e){q("ListView",Jr);const t=e.world,s=new Map;Qr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt)],e=>{const n=lr()&&!cr();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const r=t.getEntitiesWithComponents([Jr,hn]);for(const o of r){Tn(t,o,Qn,{enabled:!0,blockRaycast:!0}),Tn(t,o,Hn,{enabled:!0,mode:$n});let r=s.get(o);r||(r={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,r));const i=t.get(o,Jr),a=t.get(o,hn),l=Pn(a,o),c=Sn(a,o);if(!n){const s=t.has(o,Zn)?t.get(o,Zn):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}}const d=Math.max(0,i.itemCount*i.itemHeight-l);i.scrollY=Math.max(0,Math.min(i.scrollY,d));const u=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+l)/i.itemHeight)+i.overscan);for(const[e,s]of r.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),r.itemEntities.delete(e));for(let e=u;e<h;e++){let s=r.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,he,{value:`ListItem_${e}`}),t.insert(s,hn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),r.itemEntities.set(e,s),r.renderer&&r.renderer(e,s)),t.has(s,te)){const n=t.get(s,te);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(s,te,n)}}r.visibleStart=u,r.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},eo=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const to=new class{build(e){q("Dropdown",eo);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,te))return;const s=t.get(e,te);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,te,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function r(e){if(t.has(e,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 r=s.listEntity;if(0===r||!t.valid(r))return;d(r,!0),c(n);const o=t.get(e,re),i=o.size.x,a=o.size.y;n.ddWidth=i;const l=s.options.length*An;t.insert(r,hn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:l},pivot:{x:.5,y:.5}}),t.insert(r,te,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,re,{texture:L,color:{r:1,g:1,b:1,a:1},size:{x:i,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*An;t.insert(o,he,{value:`Option_${e}`}),t.insert(o,hn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*An},offsetMax:{x:0,y:0},size:{x:i,y:An},pivot:{x:.5,y:.5}}),t.insert(o,te,{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:L,color:{r:.95,g:.95,b:.95,a:1},size:{x:i,y:An},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Qn,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o);const c=t.spawn();t.insert(c,te,{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,Dn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Fn.Left,verticalAlign:kn.Middle,wordWrap:!1,overflow:Bn.Clip,lineHeight:1.2}),t.insert(c,hn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:An},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function i(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,r){t.selectedIndex=n,i(0,t,s),r.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Dn))return;const n=t.get(s,Dn);let r={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,i=!1;if(1===r.r&&1===r.g&&1===r.b&&1===r.a&&(r={r:0,g:0,b:0,a:1},i=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,i=!0)}i&&t.insert(s,Dn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:r,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,Qn)&&t.insert(e,Qn,{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 u(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 r=s===e.highlightIndex?{...In}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:L,color:r,size:{x:e.ddWidth,y:An},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,Zn))continue;if(t.get(s,Zn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(nr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=lr()&&!cr(),p=t.getEntitiesWithComponents([eo]);for(const g of p){const p=t.get(g,eo);let y=s.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(g,y)),n(p.listEntity),r(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Tn(t,g,Qn,{enabled:!0,blockRaycast:!0});const m=t.has(g,Zn)?t.get(g,Zn):null;if(m?.justPressed&&(p.isOpen?i(g,p,y):o(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,Zn))continue;if(t.get(s,Zn).justPressed){a(g,p,y,e,c);break}}let s=-1;for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,Zn))continue;if(t.get(n,Zn).hovered){s=e;break}}s>=0&&s!==y.highlightIndex&&(y.highlightIndex=s,u(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,u(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,u(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&i(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||h(y)||i(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},so=0,no=0,ro=2,oo=j("LayoutGroup",{direction:so,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:no,reverseOrder:!1});const io=new class{build(e){q("LayoutGroup",oo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([oo,hn,ce]);for(const s of e){const e=t.get(s,oo),n=t.get(s,hn),r=t.get(s,ce);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,hn)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,hn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=Sn(n,s),a=Pn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===so;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=Sn(n.rect,n.entity),f=Pn(n.rect,n.entity),p=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;u?(y=-l*i+d.left+h+p*r,m=e.childAlignment===no?(1-c)*a-d.top-(1-g)*f:e.childAlignment===ro?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===no?-l*i+d.left+p*r:e.childAlignment===ro?(1-l)*i-d.right-(1-p)*r:(.5-l)*i+.5*(d.left-d.right)+(p-.5)*r,m=(1-c)*a-d.top-h-(1-g)*f,h+=f,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,te);_.position.x=y,_.position.y=m,t.insert(n.entity,te,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};J("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),J("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class ao{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,et([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const lo=new ao;async function co(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 uo=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ho=we(null,"PhysicsAPI");function fo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function po(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class go{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(uo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=co(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ie]);for(const s of t){const t=e.world.get(s,ie);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;i.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(Me)],a=>{const l=i.getEntitiesWithComponents([pe,te]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,pe),l=i.get(r,te);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=fo(l.worldRotation);n._physics_createBody(r,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),yo(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===_e.Kinematic){const e=fo(l.worldRotation);n._physics_setBodyTransform(r,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,te);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(i,le)){const t=e.world.get(i,le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,te)){const s=e.world.get(t.entity,te),n=fo(s.worldRotation),r=a-s.worldPosition.x,o=l-s.worldPosition.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(r*d+o*i)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=u,d.position.y=h;const p=po(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(i,te,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(uo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ho,mo._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function yo(e,t,s){const n=e.world;if(n.has(s,ge)){const e=n.get(s,ge);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,ye)){const e=n.get(s,ye);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,me)){const e=n.get(s,me);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 mo{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(mo.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const _o={nearest:0,linear:1},xo={repeat:0,clamp:1,mirror:2};function wo(e,t,s=!0,n){const r=e.getResourceManager(),o=e._malloc(t.pixels.length);let i;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&r.createTextureEx){const e=_o[n.filterMode??"linear"]??1,a=xo[n.wrapMode??"clamp"]??1;i=r.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else i=r.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),i}function vo(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function bo(e,t,s,n){const r=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),i=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,g=a*h,y=a*f,m=l*h,_=l*f,x=c*f,w=d*u,v=d*h,b=d*f;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(p+m))*i,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function So(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={},r=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Rt(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=r?.[o];n[o]=wo(e,await s.loadPixels(o),!0,t)}catch{n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=At(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),d=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===m(c)?.contentType;let u,h;if(i){const e=await r.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,i);if(t._free(u),f<0)continue;o[a]=f;const p=vo(n),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=wo(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){const t={gravity:i?.gravity??{...B},fixedTimestep:i?.fixedTimestep??D,subStepCount:i?.subStepCount??4};new go("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){const r=Rt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=m(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=wo(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),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=Rt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=mt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=mt.createFromAsset(e,i)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Rt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,f);const p=Dt(e.world,s);if(l&&e.hasResource(Ys))for(const t of p.values())e.world.insert(t,fe,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=At(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(u,s,d,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=k);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,ue)?c.get(o,ue):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,te)){const e=bo(c.get(o,te),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,f);const p=s.HEAPU32[u>>2],g=s.HEAPU32[f>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,p,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource($t);t&&t.setAddressableManifest(a)}}class Po{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=At(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===m(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Rt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=m(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Mo="__preview__";const To={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ds.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ds.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ds.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ds.releaseRenderTarget(e._handle),To.create({width:t,height:s,depth:!0})),begin(e,t){Ds.begin(t,e._handle)},end(){Ds.end()},getDepthTexture:e=>Ds.getTargetDepthTexture(e._handle)};var Eo;exports.LogLevel=void 0,(Eo=exports.LogLevel||(exports.LogLevel={}))[Eo.Debug=0]="Debug",Eo[Eo.Info=1]="Info",Eo[Eo.Warn=2]="Warn",Eo[Eo.Error=3]="Error";class Co{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 Ro{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Co)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Ao=new Ro;const Io=[Wn,Jn,or,Mr,kr,fr,Ur,$r,Nr,Cr,xr,Vr,Kr,Zr,to,io,lo];R||(R=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await d(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return u(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=A,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.App=qs,exports.AssetPlugin=Ot,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=Wt,exports.Assets=$t,exports.AsyncCache=Tt,exports.BitmapText=de,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=tr,exports.ButtonState=er,exports.Camera=oe,exports.Canvas=ie,exports.CapsuleCollider=me,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=ce,exports.CircleCollider=ye,exports.ClearFlags=Z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Ve,exports.DEFAULT_DESIGN_HEIGHT=F,exports.DEFAULT_DESIGN_WIDTH=I,exports.DEFAULT_FALLBACK_DT=k,exports.DEFAULT_FIXED_TIMESTEP=D,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=B,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=Dr,exports.Draggable=Br,exports.Draw=as,exports.Dropdown=eo,exports.EntityCommands=Ne,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Je,exports.EventRegistry=qe,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Ke,exports.FillDirection=dn,exports.FillMethod=vr,exports.FillOrigin=br,exports.FocusManager=mr,exports.FocusManagerState=yr,exports.Focusable=gr,exports.GLDebug=Ws,exports.Geometry=Ss,exports.INVALID_ENTITY=0,exports.INVALID_FONT=z,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=Sr,exports.ImageType=wr,exports.Input=rt,exports.InputPlugin=ot,exports.InputState=nt,exports.Interactable=Qn,exports.ListView=Jr,exports.LocalTransform=se,exports.Logger=Ro,exports.Material=mt,exports.MaterialLoader=Et,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=mo,exports.PhysicsEvents=uo,exports.PhysicsPlugin=go,exports.PostProcess=Cs,exports.PrefabServer=Gt,exports.Prefabs=qt,exports.PrefabsPlugin=Kt,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(Ys);t.register({name:Mo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Mo),this.loadPromise_=t.load(Mo).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 Po(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await So(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,Mo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([oe]);for(const n of s){if(e.get(n,oe).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([ie]);for(const r of n){const n=e.get(r,ie);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ys).getScene(Mo),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,te,i);const a={isActive:!0,projectionType:Q.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.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(Ys);await e.switchTo(Mo),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=Ar,exports.ProgressBarDirection=Rr,exports.ProgressBarPlugin=Fr,exports.ProjectionType=Q,exports.Query=function(...e){return Xe(e)},exports.QueryInstance=je,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ye,exports.RenderPipeline=$s,exports.RenderTexture=To,exports.Renderer=Ds,exports.Res=ve,exports.ResMut=be,exports.RigidBody=pe,exports.RuntimeConfig=U,exports.SafeArea=Gr,exports.ScaleMode=ee,exports.SceneManager=Ys,exports.SceneManagerState=js,exports.SceneOwner=fe,exports.ScrollView=Lr,exports.ShaderSources=Mt,exports.Slider=Hr,exports.SliderDirection=Or,exports.SliderPlugin=Yr,exports.SpineAnimation=ue,exports.Sprite=re,exports.SystemRunner=st,exports.Text=Dn,exports.TextAlign=Fn,exports.TextInput=pr,exports.TextInputPlugin=_r,exports.TextOverflow=Bn,exports.TextPlugin=zn,exports.TextRenderer=Un,exports.TextVerticalAlign=kn,exports.Time=Me,exports.Toggle=Tr,exports.Transform=te,exports.UICameraInfo=at,exports.UIEventQueue=sr,exports.UIEvents=nr,exports.UIInteraction=Zn,exports.UIInteractionPlugin=hr,exports.UILayoutPlugin=rr,exports.UIMask=Hn,exports.UIMaskPlugin=Kn,exports.UIRect=hn,exports.UIRenderOrderPlugin=ao,exports.Velocity=ae,exports.WebAssetProvider=Po,exports.World=ze,exports.WorldTransform=ne,exports.addStartupSystem=function(e){tt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){tt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){tt().push({schedule:e,system:t})},exports.applyDirectionalFill=mn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=U.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=U.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=U.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=U.canvasMatchWidthOrHeight)},exports.assetPlugin=Ht,exports.clearDrawCallbacks=ps,exports.clearUserComponents=function(){const e=X();for(const t of e.keys())G.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=yn,exports.computeFillSize=function(e,t,s,n){switch(e){case dn.BottomToTop:case dn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case dn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case dn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case dn.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=un,exports.createMaskProcessor=qn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,async setup(){await So(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=qs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ns(e),pt(e),ws(e),Ms(e),ks(e),Ls(e);const r=new $s;s.setPipeline(r);let o=l();const i=t?.getViewportSize??(()=>{const e=c();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=en(e,n,t,r));const i=s.getResource(at);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(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 d={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;Ds.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(Ds.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ys)){const e=s.getResource(Ys).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=en(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Ks,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Ds.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,d),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Ht),s.addPlugin(Jt),s.addPlugin(it),s.addPlugin(Gs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Io,...t})},exports.debug=function(e,t,s){Ao.debug(e,t,s)},exports.defineComponent=j,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=we,exports.defineSystem=et,exports.defineTag=function(e){const t=G.get(e)??X().get(e);if(t)return t;const s=O(e,{});return X().set(e,s),G.set(e,s),N(e,{},!0),s},exports.error=function(e,t,s){Ao.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([he]);for(const n of s){const s=e.get(n,he);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return m(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of h)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return g},exports.getAssetMimeType=function(e){return f[e.toLowerCase()]},exports.getAssetTypeEntry=m,exports.getComponent=K,exports.getComponentAssetFieldDescriptors=Rt,exports.getComponentAssetFields=function(e){const t=Ct.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},exports.getComponentDefaults=function(e){const t=K(e);return t?W(t._default):null},exports.getComponentEntityFields=Ft,exports.getComponentSpineFieldDescriptor=At,exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Ao},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=Y,exports.getWeChatPackOptions=function(){return x().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Ao.info(e,t,s)},exports.initDrawAPI=ns,exports.initGLDebugAPI=Ls,exports.initGeometryAPI=ws,exports.initMaterialAPI=pt,exports.initPostProcessAPI=Ms,exports.initRendererAPI=ks,exports.inputPlugin=it,exports.instantiatePrefab=Xt,exports.intersectRects=Xn,exports.invertMatrix4=jn,exports.isBuiltinComponent=V,exports.isCustomExtension=w,exports.isEditor=lr,exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=cr,exports.isRuntime=function(){return!ir},exports.isTextureRef=ct,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=zt,exports.loadPhysicsModule=co,exports.loadRuntimeScene=So,exports.loadSceneData=Dt,exports.loadSceneWithAssets=Ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(y(e)))},exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,r,o,i,a,l,c){const d=Nn(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,g=f*h-p*u+s,y=f*u+p*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Jt,exports.progressBarPlugin=kr,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=q,exports.registerComponentAssetFields=function(e,t){Ct.set(e,t)},exports.registerComponentEntityFields=function(e,t){It.set(e,t)},exports.registerDrawCallback=hs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource($t);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Pt,exports.remapEntityFields=kt,exports.sceneManagerPlugin=Gs,exports.screenToWorld=Yn,exports.setEditorMode=function(e){ir=e},exports.setListViewRenderer=function(e,t){if(!Qr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Qr.get(e);s?s.renderer=t:Qr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Ao.setMinLevel(e)},exports.setPlayMode=function(e){ar=e},exports.setWasmErrorHandler=Ae,exports.shutdownDrawAPI=rs,exports.shutdownGLDebugAPI=zs,exports.shutdownGeometryAPI=vs,exports.shutdownMaterialAPI=gt,exports.shutdownPostProcessAPI=Ts,exports.shutdownRendererAPI=Bs,exports.sliderPlugin=Nr,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,re))return;const i=e.get(t,re);let a,l;switch(s){case dn.BottomToTop:case dn.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,re,i))},exports.textInputPlugin=xr,exports.textPlugin=Wn,exports.transitionTo=async function(e,t,s){const n=e.getResource(Ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=fr,exports.uiLayoutPlugin=or,exports.uiMaskPlugin=Jn,exports.uiPlugins=Io,exports.uiRenderOrderPlugin=lo,exports.unregisterComponent=function(e){X().delete(e),G.delete(e)},exports.unregisterDrawCallback=fs,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([oe]);for(const n of s){const s=e.get(n,oe);s&&(s.aspectRatio=t,e.insert(n,oe,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Ao.warn(e,t,s)},exports.wrapSceneSystem=Ns,exports.wxFileExists=T,exports.wxFileExistsSync=function(e){const t=b();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=async function(e){return C(await E(e))},exports.wxReadFile=P,exports.wxReadTextFile=M,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{b().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function r(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function i(e){return t().fileExists(e)}function a(e,s){return t().createCanvas(e,s)}function l(){return t().now()}function c(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}function d(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function u(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 h=[{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}],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",bmfont:"application/json",fnt:"text/plain"},p=new Map,g=new Set;for(const e of h)for(const t of e.extensions)p.set(t,e),g.add(t);function y(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function m(e){return p.get(y(e))}function _(e){return g.has(e.toLowerCase())}function x(){const e=[];for(const t of h)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function w(e){const t=m(e);return t?.wechatPackInclude??!1}let v=null;function b(){return v||(v=wx.getFileSystemManager()),v}function S(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(w(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 P(e){return new Promise((t,s)=>{b().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(S(e,t.errMsg)))}})})}function M(e,t="utf-8"){return new Promise((s,n)=>{b().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(S(e,t.errMsg)))}})})}function T(e){return new Promise(t=>{b().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function E(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let R=!1;const A=new class{constructor(){this.name="wechat"}async fetch(e,t){return d(e,t)}async readFile(e){return P(e)}async readTextFile(e){return M(e)}async fileExists(e){return T(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return u(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)}),wx.onTouchMove(t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},I=1920,F=1080,k=1/60,B={x:0,y:-9.81},D=1/60,U={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const L=4294967295,z=4294967295;function W(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(W);const t={};for(const s in e)t[s]=W(e[s]);return t}let $=0;function O(e,t){const s=++$,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?{...W(t),...e}:W(t):e?{...t,...e}:{...t}}}const H=new Map;function X(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function j(e,t){const s=G.get(e)??X().get(e);if(s)return s;const n=O(e,t);return X().set(e,n),G.set(e,n),N(e,t,!1),n}function Y(e){return X().get(e)}function N(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function V(e){return!0===e._builtin}const G=new Map;function q(e,t){G.set(e,t)}function K(e){return G.get(e)??Y(e)}function J(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return G.set(e,s),s}const Q={Perspective:0,Orthographic:1},Z={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ee={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},te=J("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}}),se=te,ne=te,re=J("Sprite",{texture:L,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=J("Camera",{projectionType:Q.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:Z.ColorAndDepth}),ie=J("Canvas",{designResolution:{x:I,y:F},pixelsPerUnit:100,scaleMode:ee.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ae=J("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),le=J("Parent",{entity:0}),ce=J("Children",{entities:[]}),de=J("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:z,enabled:!0}),ue=J("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}),he=j("Name",{value:""}),fe=j("SceneOwner",{scene:"",persistent:!1});const pe=J("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ge=J("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ye=J("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),me=J("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),_e={Static:0,Kinematic:1,Dynamic:2};let xe=0;function we(e,t){const s=++xe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ve(e){return{_type:"res",_resource:e}}function be(e){return{_type:"res_mut",_resource:e}}class Se{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 Pe{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 Se(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Me=we({delta:0,elapsed:0,frameCount:0},"Time");function Te(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ee(t[e]),o=Ee(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function Ee(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ce(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 Re=null;function Ae(e){Re=e}function Ie(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Re&&Re(e,t)}function Fe(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 ke=1;const Be=new WeakMap;function De(e){let t=Be.get(e);return void 0===t&&(t=ke++,Be.set(e,t)),t}const Ue=[];function Le(e,t=[],s=[]){Ue.length=0;for(const t of e)Ue.push(De(t));Ue.sort((e,t)=>e-t);let n=Ue.join(",");if(t.length>0){Ue.length=0;for(const e of t)Ue.push(De(e));Ue.sort((e,t)=>e-t),n+="|+"+Ue.join(",")}if(s.length>0){Ue.length=0;for(const e of s)Ue.push(De(e));Ue.sort((e,t)=>e-t),n+="|-"+Ue.join(",")}return n}class ze{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.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 Ie(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_;return this.entities_.set(e,t),this.worldVersion_++,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){Ie(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)}}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){Ie(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ie(t,`removeParent(entity=${e})`)}}insert(e,t,s){return V(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(V(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Fe(s))}catch(s){Ie(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 V(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return V(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(V(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ie(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.");V(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],r=s[`get${e}`],o=s[`has${e}`],i=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof r||"function"!=typeof o||"function"!=typeof i)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:r.bind(s),has:o.bind(s),remove:i.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Te(t._name,t._default,n);if(e.length>0)throw new Error(Ce(t._name,e))}const r={...t._default,...n};let o=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);o=!s.has(e),s.add(e,Fe(r))}catch(s){Ie(s,`insertBuiltin(${t._name}, entity=${e})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const r=t[n];if(null!=r&&"object"==typeof r&&!Array.isArray(r)&&"r"in r&&"g"in r&&"b"in r&&"a"in r){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const r=e[s],o=t[s];if(null==r||"object"!=typeof r||Array.isArray(r)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=r;else{const e=r,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:r}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ie(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 Ie(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ie(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Te(t._name,t._default,e);if(r.length>0)throw new Error(Ce(t._name,r));n=e}const r=t.create(n),o=this.getStorage(t),i=!o.has(e);o.set(e,r);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),i&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of G)if(V(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=X();for(const n of s)for(const[s,r]of e)if(r._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const r=n??Le(e,t,s),o=this.queryCache_.get(r);if(o&&o.version===this.worldVersion_)return o.result;let i=null,a=1/0;for(const t of e)if(!V(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=i?i.keys():this.entities_.keys();for(const n of c){let r=!0;for(const t of e)if(!this.has(n,t)){r=!1;break}if(r)for(const e of t)if(!this.has(n,e)){r=!1;break}if(r)for(const e of s)if(this.has(n,e)){r=!1;break}r&&l.push(n)}return this.queryCache_.set(r,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const r=n.get(e);return void 0!==r&&r>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function We(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function $e(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Oe(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function He(e){return We(e)||$e(e)||Oe(e)?e._component:e}function Xe(e,t=[],s=[]){const n=[],r=[],o=[];return e.forEach((e,t)=>{We(e)&&n.push(t),$e(e)?r.push({index:t,component:e._component}):Oe(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:r,_changedFilters:o,with:(...n)=>Xe(e,[...t,...n],s),without:(...n)=>Xe(e,t,[...s,...n])}}class je{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(He),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_=Le(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,r=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,i=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of s)if(!o||this.passesChangeFilters_(d)){if(null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}i[0]=d;for(let e=0;e<n;e++)i[e+1]=this.world_.get(d,t[e]);if(r){for(let t=0;t<l;t++)a[t].data=i[e[t]+1];c=d}yield i}}finally{if(this.world_.endIteration(),null!==c&&r)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class 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 Ne{constructor(e,t){this.components_=[],this.commands_=e,null===t?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:t},this.isNew_=!1)}insert(e,t){let s;return s=V(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 Ve{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ne(this,null);return this.spawned_.push(e),e}entity(e){return new Ne(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class Ge{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 qe{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Ge)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Ge,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class Ke{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Je{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Qe;exports.Schedule=void 0,(Qe=exports.Schedule||(exports.Schedule={}))[Qe.Startup=0]="Startup",Qe[Qe.First=1]="First",Qe[Qe.PreUpdate=2]="PreUpdate",Qe[Qe.Update=3]="Update",Qe[Qe.PostUpdate=4]="PostUpdate",Qe[Qe.Last=5]="Last",Qe[Qe.FixedPreUpdate=10]="FixedPreUpdate",Qe[Qe.FixedUpdate=11]="FixedUpdate",Qe[Qe.FixedPostUpdate=12]="FixedPostUpdate";let Ze=0;function et(e,t,s){const n=++Ze;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function tt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class st{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 Ve&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new je(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 Ve(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 Ke(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Je(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 nt{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=we(new nt,"Input");class ot{constructor(e){this.target_=e??null}build(e){const s=new nt;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,et([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const it=new ot,at=we({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 lt;function ct(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(lt=exports.BlendMode||(exports.BlendMode={}))[lt.Normal=0]="Normal",lt[lt.Additive=1]="Additive",lt[lt.Multiply=2]="Multiply",lt[lt.Screen=3]="Screen",lt[lt.PremultipliedAlpha=4]="PremultipliedAlpha";let dt=null,ut=null,ht=1;const ft=new Map;function pt(e){dt=e,ut=e.getResourceManager(),Pt()}function gt(){0!==xt&&dt&&(dt._free(xt),xt=0),ft.clear(),ht=1,_t=!1,vt.clear(),bt=null,ut=null,dt=null}function yt(){if(!ut)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return ut}const mt={createShader:(e,t)=>yt().createShader(e,t),releaseShader(e){e>0&&yt().releaseShader(e)},create(e){const t=ht++,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 ft.set(t,s),t},get:e=>ft.get(e),setUniform(e,t,s){const n=ft.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,dt?.invalidateMaterialCache(e))},getUniform(e,t){const s=ft.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=ft.get(e);s&&(s.blendMode=t,dt?.invalidateMaterialCache(e))},getBlendMode(e){const t=ft.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=ft.get(e);s&&(s.depthTest=t,dt?.invalidateMaterialCache(e))},getShader(e){const t=ft.get(e);return t?.shader??0},release(e){ft.delete(e),dt?.invalidateMaterialCache(e)},isValid:e=>ft.has(e),releaseAll(){ft.clear(),dt?.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=ft.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=ht++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return ft.set(s,n),s},toAssetData(e,t){const s=ft.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=ft.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let _t=!1,xt=0;const wt=16384,vt=new Map;let bt=null;function St(e){const t=(0===xt&&dt&&(xt=dt._malloc(wt)),xt);if(0===t||!dt)return{ptr:0,count:0};let s=0,n=0;const r=dt.HEAPU8,o=dt.HEAPU32,i=dt.HEAPF32;for(const[a,l]of e){if(ct(l))continue;let e=vt.get(a);e||(bt||(bt=new TextEncoder),e=bt.encode(a),vt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(s+(4+d+4+16)>wt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${wt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,r.set(e,t+s),s+=d;let u=0,h=[0,0,0,0];if("number"==typeof l)u=0,h[0]=l;else if(Array.isArray(l)){u=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(u=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(u=2,h=[l.x,l.y,l.z,0]):"y"in l&&(u=1,h=[l.x,l.y,0,0]);o[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function Pt(){if(!dt||_t)return;dt.materialDataProvider=(e,t,s,n,r)=>{const o=ft.get(e);if(!o)return dt.HEAPU32[t>>2]=0,dt.HEAPU32[s>>2]=0,dt.HEAPU32[n>>2]=0,void(dt.HEAPU32[r>>2]=0);dt.HEAPU32[t>>2]=o.shader,dt.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=St(o.uniforms);dt.HEAPU32[n>>2]=i,dt.HEAPU32[r>>2]=a},_t=!0}const Mt={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 Tt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Et{constructor(e,t=""){this.cache_=new Tt,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&&(mt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())mt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await i(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(r);return{handle:mt.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}}const Ct=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"}]}]]);function Rt(e){return Ct.get(e)?.fields??[]}function At(e){return Ct.get(e)?.spine??null}const It=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ft(e){return It.get(e)}function kt(e,t){const s=It.get(e.type);if(!s)return;const n=e.data;for(const r of s){const s=n[r];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${r} references entity ${s} which does not exist`),n[r]=void 0!==o?o:0}}}function Bt(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,he,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const r of n.components)kt(r,s),zt(e,t,r,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}function Dt(e,t){return Bt(e,t)}async function Ut(e,t,s){const n=s?.assetServer,r=s?.assetBaseUrl,o=new Map;n&&await async function(e,t,s,n,r){e=JSON.parse(JSON.stringify(e));const o=new Map;for(const e of Lt.keys())o.set(e,new Set);const i=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),i.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Lt.entries()].map(async([e,r])=>{const i=await r.load(o.get(e),t,s,n);l.set(e,i)}),d=i.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...d]),r){for(const e of n.values())r.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&r.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)r.fontPaths.add(e);for(const e of a)r.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&(s[e.field]=l.get(e.type)?.get(t)??0)}}}(t,n,r,o,s?.collectAssets);const i=Bt(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return i}const Lt=new Map([["texture",{async load(e,t,s,n){const r=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(o);r.set(e,i.handle),n.set(e,o)}catch(t){console.warn(`Failed to load texture: ${e}`,t),r.set(e,0)}});return await Promise.all(o),r}}],["material",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadMaterial(e,s);n.set(e,r.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}],["font",{async load(e,t,s){const n=new Map,r=[...e].map(async e=>{try{const r=await t.loadBitmapFont(e,s);n.set(e,r)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(r),n}}]]);function zt(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const r=K(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class Wt{constructor(e){this.textureCache_=new Tt,this.shaderCache_=new Tt,this.jsonCache_=new Tt,this.textCache_=new Tt,this.binaryCache_=new Tt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Tt,this.prefabCache_=new Tt,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.module_=e,this.canvas_=a(U.textCanvasSize,U.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 Et(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),mt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),d="binary"===m(e)?.contentType,u=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,o,d);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=l.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=m(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ut(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await i(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:a}=this.parseEsShader(n);if(!r||!a)throw new Error(`Invalid shader format: ${e}`);return mt.createShader(r,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const 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.embedded_.get(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.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const $t=we(null,"Assets");class Ot{build(e){const t=e.wasmModule;t?e.insertResource($t,new Wt(t)):console.warn("AssetPlugin: No WASM module available")}}const Ht=new Ot;async function Xt(e,t,s){const{entities:n,rootId:r}=await Yt(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await Ut(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const jt=10;async function Yt(e,t,s,n,r,o=0){if(o>jt)throw new Error(`Prefab nesting depth exceeded ${jt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Yt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?i.get(n.parent)??null:null),l.push(...t.entities);continue}const c=i.get(n.prefabEntityId),d=n.prefabEntityId===e.rootEntityId,u={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:d?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u.components,i),Vt(u,t),l.push(u)}const c=i.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Nt(e,t){for(const s of e){const e=Ft(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const r=t.get(e);void 0!==r&&(s.data[n]=r)}}}}function Vt(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 Gt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Xt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const qt=we(null,"Prefabs");class Kt{constructor(){this.name="PrefabsPlugin",this.dependencies=[$t]}build(e){const t=e.getResource($t);e.insertResource(qt,new Gt(e.world,t))}}const Jt=new Kt;let Qt=null,Zt=0,es=0,ts=0;const ss=new Float32Array(256);function ns(e){Qt=e,Zt=Qt._malloc(64),es=Qt._malloc(64),ts=Qt._malloc(1024)}function rs(){Qt&&(Zt&&(Qt._free(Zt),Zt=0),es&&(Qt._free(es),es=0),ts&&(Qt._free(ts),ts=0)),Qt=null}function os(){if(!Qt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Qt}const is={r:1,g:1,b:1,a:1},as={begin(e){const t=os();try{t.HEAPF32.set(e,Zt/4),t.draw_begin(Zt)}catch(e){Ie(e,"Draw.begin")}},end(){try{os().draw_end()}catch(e){Ie(e,"Draw.end")}},line(e,t,s,n=1){try{os().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.line")}},rect(e,t,s,n=!0){try{os().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{os().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ie(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{os().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{os().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Ie(e,"Draw.circleOutline")}},texture(e,t,s,n=is){try{os().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ie(e,"Draw.texture")}},textureRotated(e,t,s,n,r=is){try{os().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Ie(e,"Draw.textureRotated")}},setLayer(e){os().draw_setLayer(e)},setDepth(e){os().draw_setDepth(e)},getDrawCallCount:()=>Qt?Qt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Qt?Qt.draw_getPrimitiveCount():0,setBlendMode(e){os().draw_setBlendMode(e)},setDepthTest(e){os().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=os();n.HEAPF32.set(s,es/4),n.draw_mesh(e,t,es)}catch(s){Ie(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=os(),r=mt.get(t);if(!r)return;if(as.setBlendMode(r.blendMode),as.setDepthTest(r.depthTest),0===r.uniforms.size)return void as.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,es/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=ds(t);if(!(n<0)){if(ct(s))ss[o++]=10,ss[o++]=n,ss[o++]=s.slot??e++,ss[o++]=s.textureId;else if("number"==typeof s)ss[o++]=1,ss[o++]=n,ss[o++]=s;else if(Array.isArray(s)){ss[o++]=s.length,ss[o++]=n;for(let e=0;e<s.length;e++)ss[o++]=s[e]}else"w"in s?(ss[o++]=4,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y,ss[o++]=s.z,ss[o++]=s.w):"z"in s?(ss[o++]=3,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y,ss[o++]=s.z):(ss[o++]=2,ss[o++]=n,ss[o++]=s.x,ss[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(ss.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,es);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),ts/4),n.draw_meshWithUniforms(e,r.shader,es,ts,o)}catch(s){Ie(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ls={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},cs=new Set;function ds(e){const t=ls[e];return void 0!==t?t:(cs.has(e)||(cs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ls).join(", ")}`)),-1)}const us=new Map;function hs(e,t,s){us.set(e,{fn:t,scene:s??""})}function fs(e){us.delete(e)}function ps(){us.clear()}var gs;exports.DataType=void 0,(gs=exports.DataType||(exports.DataType={}))[gs.Float=1]="Float",gs[gs.Float2=2]="Float2",gs[gs.Float3=3]="Float3",gs[gs.Float4=4]="Float4",gs[gs.Int=5]="Int",gs[gs.Int2=6]="Int2",gs[gs.Int3=7]="Int3",gs[gs.Int4=8]="Int4";let ys=null,ms=0,_s=0,xs=0;function ws(e){ys=e,ms=ys._malloc(262144),_s=ys._malloc(65536),xs=ys._malloc(256)}function vs(){ys&&(ms&&ys._free(ms),_s&&ys._free(_s),xs&&ys._free(xs),ms=0,_s=0,xs=0),ys=null}function bs(){if(!ys)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ys}const Ss={create(e){const t=bs(),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,ms/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,xs,r).set(o),t.geometry_init(s,ms,n,xs,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=bs(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ms/4),n.geometry_updateVertices(e,ms,r,s)},release(e){e>0&&bs().geometry_release(e)},isValid:e=>!(!ys||e<=0)&&ys.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Ss.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,l=(Math.sin(r)+1)/2;s.push(o,i,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Ss.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Ss.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Ps=null;function Ms(e){Ps=e}function Ts(){Ps&&Cs.isInitialized()&&Cs.shutdown(),Ps=null}function Es(){if(!Ps)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ps}const Cs={init(e,t){try{return Es().postprocess_init(e,t)}catch(s){return Ie(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Es().postprocess_shutdown()}catch(e){Ie(e,"PostProcess.shutdown")}},resize(e,t){try{Es().postprocess_resize(e,t)}catch(s){Ie(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Es().postprocess_addPass(e,t)}catch(t){return Ie(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Es().postprocess_removePass(e)}catch(t){Ie(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Es().postprocess_setPassEnabled(e,t)}catch(t){Ie(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Es().postprocess_isPassEnabled(e)}catch(t){return Ie(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Es().postprocess_setUniformFloat(e,t,s)}catch(s){Ie(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Ie(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Es().postprocess_begin()}catch(e){Ie(e,"PostProcess.begin")}},end(){try{Es().postprocess_end()}catch(e){Ie(e,"PostProcess.end")}},getPassCount(){try{return Es().postprocess_getPassCount()}catch(e){return Ie(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ps)return!1;try{return Ps.postprocess_isInitialized()}catch(e){return Ie(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Es().postprocess_setBypass(e)}catch(e){Ie(e,"PostProcess.setBypass")}},isBypassed(){if(!Ps)return!0;try{return Ps.postprocess_isBypassed()}catch(e){return Ie(e,"PostProcess.isBypassed"),!0}},createBlur:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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:()=>mt.createShader(Rs,"#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")},Rs="#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 As;exports.RenderStage=void 0,(As=exports.RenderStage||(exports.RenderStage={}))[As.Background=0]="Background",As[As.Opaque=1]="Opaque",As[As.Transparent=2]="Transparent",As[As.Overlay=3]="Overlay";let Is=null,Fs=0;function ks(e){Is=e,Fs=Is._malloc(64)}function Bs(){Is&&Fs&&(Is._free(Fs),Fs=0),Is=null}const Ds={init(e,t){Is?.renderer_init(e,t)},resize(e,t){Is?.renderer_resize(e,t)},begin(e,t){if(Is&&Fs)try{Is.HEAPF32.set(e,Fs/4),Is.renderer_begin(Fs,t??0)}catch(e){Ie(e,"Renderer.begin")}},flush(){try{Is?.renderer_flush()}catch(e){Ie(e,"Renderer.flush")}},end(){try{Is?.renderer_end()}catch(e){Ie(e,"Renderer.end")}},submitSprites(e){if(Is)try{Is.renderer_submitSprites(e._cpp)}catch(e){Ie(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Is)try{Is.renderer_submitBitmapText(e._cpp)}catch(e){Ie(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Is)try{Is.renderer_submitSpine?.(e._cpp)}catch(e){Ie(e,"Renderer.submitSpine")}},setStage(e){Is?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Is?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Is?.renderer_releaseTarget(e)},getTargetTexture:e=>Is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Is?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Is?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Is?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Is?Is.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Is?{drawCalls:Is.renderer_getDrawCalls(),triangles:Is.renderer_getTriangles(),sprites:Is.renderer_getSprites(),text:Is.renderer_getText(),spine:Is.renderer_getSpine?.()??0,meshes:Is.renderer_getMeshes(),culled:Is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Us=null;function Ls(e){Us=e}function zs(){Us=null}const Ws={enable(){Us?.gl_enableErrorCheck(!0)},disable(){Us?.gl_enableErrorCheck(!1)},check:e=>Us?.gl_checkErrors(e)??0,diagnose(){Us?.renderer_diagnose()}};class $s{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(Ds.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Ds.setViewport(0,0,n,r),Ds.clearBuffers(3),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;Ds.setViewport(n.x,n.y,n.w,n.h),Ds.setScissor(n.x,n.y,n.w,n.h,!0),Ds.clearBuffers(r),Ds.setScissor(0,0,0,0,!1),Ds.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Ds.submitSprites(t),Ds.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ds.submitSpine(t),Ds.flush(),this.executeDrawCallbacks(s,o),Ds.end()}executeDrawCallbacks(e,t){const s=us;if(s.size>0){as.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}as.end();for(const e of n)fs(e)}}}const Os="__scene_transition_overlay__";class Hs{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 Xs{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,fe,{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 s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.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,fe)){const s=this.app_.world.get(e,fe);s.persistent=t,this.app_.world.insert(e,fe,s)}}}class js{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??U.sceneTransitionDuration,r=t.color??{...U.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},hs(Os,()=>{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;as.setLayer(9999),as.setDepth(9999),as.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,fs(Os),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,fs(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 s=new Hs(t);this.scenes_.set(e,s);const n=new Xs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource($t)?this.app_.getResource($t):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Hs(t);this.scenes_.set(e,s);const n=new Xs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource($t)?this.app_.getResource($t):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}return await this.loadSceneData_(s,e,t,r),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,fe)){if(this.app_.world.get(e,fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())fs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:s};this.app_.hasResource($t)&&(r.assetServer=this.app_.getResource($t));const o=await Ut(this.app_.world,n,r);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,fe,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Ns(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const r=this.contexts_.get(t);s.setup&&await s.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource($t)?this.app_.getResource($t):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)mt.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let r=!1;if(s.has(e,re)){const t=s.get(e,re);n.sprite=t.color.a,t.color.a=0,s.insert(e,re,t),r=!0}if(s.has(e,ue)){const t=s.get(e,ue);n.spine=t.color.a,t.color.a=0,s.insert(e,ue,t),r=!0}if(s.has(e,de)){const t=s.get(e,de);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,de,t),r=!0}r&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,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,ue)){const t=s.get(e,ue);t.color.a=n.spine,s.insert(e,ue,t)}if(void 0!==n.bitmapText&&s.has(e,de)){const t=s.get(e,de);t.color.a=n.bitmapText,s.insert(e,de,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.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 Ys=we(null,"SceneManager");function Ns(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ys).getSceneStatus(t)&&s._fn(...n)}}}const Vs=et([be(Ys),ve(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Gs={name:"SceneManager",build(e){const t=new js(e);e.insertResource(Ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ys),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,Vs)}};class qs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new qe,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=l(),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 ze,this.resources_=new Pe;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qs}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,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)}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 Ae(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(Ys).register(e),this}setInitialScene(e){return this.getResource(Ys).setInitial(e),this}tick(e){this.runner_||(this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Me)||this.resources_.insert(Me,{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.runSchedule(exports.Schedule.First),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new st(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=l(),this.mainLoop())}quit(){this.running_=!1,ps();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[zs,Bs,Ts,vs,gt,rs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Me);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ks=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Js(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case ee.FixedWidth:return o;case ee.FixedHeight:return i;case ee.Expand:return Math.max(o,i);case ee.Shrink:return Math.min(o,i);case ee.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}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 en(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,fe);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const r=t.getCamera(e),o=t.getTransform(e),i=r.viewportW*s/(r.viewportH*n);let a,d=0,u=0;if(r.projectionType===Q.Orthographic){if(u=r.orthoSize,l){u=Js(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,i,l.scaleMode,l.matchWidthOrHeight)}d=u*i,a=sn(-d,d,-u,u,-r.farPlane,r.farPlane)}else a=rn(r.fov*Math.PI/180,i,r.nearPlane,r.farPlane);const h=an(o.position.x,o.position.y,o.position.z),f=Zs(c.length);f.entity=e,f.viewProjection.set(cn(a,h)),f.viewportRect.x=r.viewportX,f.viewportRect.y=r.viewportY,f.viewportRect.w=r.viewportW,f.viewportRect.h=r.viewportH,f.clearFlags=r.clearFlags,f.priority=r.priority,f.halfW=d,f.halfH=u,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const tn=new Float32Array(16);function sn(e,t,s,n,r,o){const i=tn;i.fill(0);const a=t-e,l=n-s,c=o-r;return i[0]=2/a,i[5]=2/l,i[10]=-2/c,i[12]=-(t+e)/a,i[13]=-(n+s)/l,i[14]=-(o+r)/c,i[15]=1,i}const nn=new Float32Array(16);function rn(e,t,s,n){const r=nn;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const on=new Float32Array(16);function an(e,t,s){const n=on;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 ln=new Float32Array(16);function cn(e,t){const s=ln;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}const dn={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function un(e,t,s,n,r,o,i={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,d=o.left+t.x*a,u=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+s.x-r.x*i.x,g=f+r.x):(f=c+s.x,g=d+n.x),e.y===t.y?(p=u+s.y-r.y*i.y,y=p+r.y):(p=u+s.y,y=h+n.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+i.x*m,originY:p+i.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const hn=J("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 fn=null,pn=null;function gn(e,t){e.has(t,re)||e.insert(t,re,{texture:L,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 yn(e,t){switch(e){case dn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case dn.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case dn.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 mn(e,t,s,n){if(!e.has(t,hn))return;const r=e.get(t,hn),o=yn(s,n);r.anchorMin=o.anchorMin,r.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(r.size={...r.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(r.size={...r.size,y:0}),e.insert(t,hn,r)}function _n(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function xn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function wn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(let o=0;o<t.length;o++){const i=t[o],a=n+i;if(e.measureText(a).width>s&&n){if(xn(i.charCodeAt(0))&&n.length>0&&xn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!xn(n.charCodeAt(t))){e=t;break}e>=0?(r.push(n.substring(0,e+1)),n=n.substring(e+1)+i):(r.push(n),n=i)}else r.push(n),n=i}else n=a}n&&r.push(n)}return r.length>0?r:[""]}function vn(e){let t=1;for(;t<e;)t*=2;return t}function bn(e,t){let s=0,n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;s++,n=t}return s}function Sn(e,t){if(fn&&pn){const e=fn.getUIRectComputedWidth(pn,t);if(e>0)return e}return e.size.x}function Pn(e,t){if(fn&&pn){const e=fn.getUIRectComputedHeight(pn,t);if(e>0)return e}return e.size.y}function Mn(e,t,s){let n=t;for(;e.has(n,le);){const t=e.get(n,le).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Tn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function En(e,t,s,n,r){if(!e.has(t,hn))return;const o=e.get(t,hn),i=un(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=i.rect.right-i.rect.left,l=i.rect.top-i.rect.bottom;if(e.has(t,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,te)){const s=e.get(t,te);s.position.x=i.originX-n,s.position.y=i.originY-r,e.insert(t,te,s)}}function Cn(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let r=0;r<t.length;r++)n[t[r]]=s[r](e);return n},changed(e,n){for(let r=0;r<t.length;r++)if(e[t[r]]!==s[r](n))return!0;return!1},update(e,n){for(let r=0;r<t.length;r++)e[t[r]]=s[r](n)}}}const Rn=.1,An=30,In={r:.3,g:.5,b:.8,a:1},Fn={Left:0,Center:1,Right:2},kn={Top:0,Middle:1,Bottom:2},Bn={Visible:0,Clip:1,Ellipsis:2},Dn=j("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Fn.Left,verticalAlign:kn.Top,wordWrap:!0,overflow:Bn.Visible,lineHeight:1.2});class Un{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=a(U.textCanvasSize,U.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,vn(this.frameMaxW_)),e.height=Math.max(e.height,vn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=vn(this.frameMaxW_),e.height=vn(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let l=wn(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),f=r?Math.ceil(o):u+2*d,p=r?Math.ceil(i):h+2*d;if(r&&e.overflow===Bn.Ellipsis&&h>i){const e=Math.floor(i/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,vn(f)),n.height=Math.max(n.height,vn(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,r&&e.overflow===Bn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const x=l.length*c;let w;if(r)switch(e.verticalAlign){case kn.Top:w=d;break;case kn.Middle:w=d+(p-2*d-x)/2;break;case kn.Bottom:w=p-x-d;break;default:w=d}else w=d;let v=w;for(const t of l){let n;switch(e.align){case Fn.Left:n=d;break;case Fn.Center:n=f/2;break;case Fn.Right:n=f-d;break;default:n=d}s.fillText(t,n,v),v+=c}r&&e.overflow===Bn.Clip&&s.restore();const b=s.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 s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Fn.Left:return"left";case Fn.Center:return"center";case Fn.Right:return"right"}}}const Ln=Cn({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?Sn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Pn(e.uiRect,e.entity):0});class zn{build(e){q("Text",Dn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Un(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Dn));for(const e of r.keys())if(!n.valid(e)||!n.has(e,Dn)){if(n.valid(e)&&n.has(e,re)){const t=n.get(e,re);n.insert(e,re,{texture:L,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}r.delete(e)}const e=n.getEntitiesWithComponents([Dn]);for(const t of e){const e=n.get(t,Dn),o=n.has(t,hn)?n.get(t,hn):null,i={text:e,uiRect:o,entity:t},a=r.get(t);if(a&&!Ln.changed(a,i)){if(n.has(t,re)&&n.get(t,re).texture!==L)continue}gn(n,t);const l=o?{size:{x:Sn(o,t),y:Pn(o,t)}}:null,c=s.renderForEntity(t,e,l),d=n.get(t,re);n.insert(t,re,{texture:c.textureHandle,color:{r:d.color.r,g:d.color.g,b:d.color.b,a:d.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:d.layer,flipX:d.flipX,flipY:d.flipY,material:d.material,enabled:d.enabled}),r.set(t,Ln.take(i))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Wn=new zn,$n=0,On=1,Hn=J("UIMask",{enabled:!0,mode:$n});function Xn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function jn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],l=e[5],c=e[6],d=e[7],u=e[8],h=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],x=n*l-r*a,w=n*c-o*a,v=n*d-i*a,b=r*c-o*l,S=r*d-i*l,P=o*d-i*c,M=u*y-h*g,T=u*m-f*g,E=u*_-p*g,C=h*m-f*y,R=h*_-p*y,A=f*_-p*m;let I=x*A-w*R+v*C+b*E-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*A-c*R+d*C)*I,s[1]=(o*R-r*A-i*C)*I,s[2]=(y*P-m*S+_*b)*I,s[3]=(f*S-h*P-p*b)*I,s[4]=(c*E-a*A-d*T)*I,s[5]=(n*A-o*E+i*T)*I,s[6]=(m*v-g*P-_*w)*I,s[7]=(u*P-f*v+p*w)*I,s[8]=(a*R-l*E+d*M)*I,s[9]=(r*E-n*R-i*M)*I,s[10]=(g*S-y*v+_*x)*I,s[11]=(h*v-u*S-p*x)*I,s[12]=(l*T-a*C-c*M)*I,s[13]=(n*C-r*T+o*M)*I,s[14]=(y*w-g*b-m*x)*I,s[15]=(u*b-h*w+f*x)*I),s}function Yn(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,l=(t-r)/i*2-1,c=s[0]*a+s[4]*l+s[12],d=s[1]*a+s[5]*l+s[13],u=s[3]*a+s[7]*l+s[15];return{x:c/u,y:d/u}}function Nn(e,t){return 2*Math.atan2(e,t)}function Vn(e,t,s,n,r,o,i){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,r+(.5*(l/c)+.5)*i]}function Gn(e,t,s,n,r,o,i){if(!e.has(t,hn)||!e.has(t,te))return null;const a=e.get(t,hn),l=e.get(t,te),c=Sn(a,t)*l.worldScale.x,d=Pn(a,t)*l.worldScale.y,u=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),x=Nn(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),b=[[u+g*w-m*v,h+g*v+m*w],[u+y*w-m*v,h+y*v+m*w],[u+y*w-_*v,h+y*v+_*w],[u+g*w-_*v,h+g*v+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Vn(e,t,s,n,r,o,i);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function qn(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Hn]);if(0===l.length)return;const c=[],d=[],u=new Set,h=new Set;for(const e of l){const s=t.get(e,Hn);s.enabled&&(u.add(e),s.mode===On?(d.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,r,o,i,a,l,c){const d=[];for(const e of n){let s=!0;Mn(t,e,e=>{if(r.has(e)){if(t.get(e,Hn).mode===$n)return s=!1,!0}return!1}),s&&d.push(e)}function u(n,d){const h=e.getChildEntities(s,n);for(const s of h){let n=d;if(r.has(s)){if(t.get(s,Hn).mode===$n){const e=Gn(t,s,o,i,a,l,c);e&&(n=Xn(d,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of d){const s=Gn(t,e,o,i,a,l,c);s&&u(e,s)}}(e,t,s,c,u,n,r,o,i,a),d.length>0&&function(e,t,s,n,r){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Mn(t,e,e=>!!r.has(e)&&(s=!1,!0)),s&&o.push(e)}let i=1,a=!1;function l(){return i>255?(a||console.warn("Stencil mask overflow"),a=!0,null):i++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}function d(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(r.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),d(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,d,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Kn{build(e){if(q("UIMask",Hn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(qn(e.wasmModule,e.world))}}const Jn=new Kn,Qn=J("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Zn=J("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),er={Normal:0,Hovered:1,Pressed:2,Disabled:3},tr=j("Button",{state:er.Normal,transition:null});class sr{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 nr=we(new sr,"UIEvents");class rr{build(e){q("UIRect",hn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){fn=e,pn=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],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,et([ve(at)],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,et([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const or=new rr;let ir=!1,ar=!1;function lr(){return ir}function cr(){return ar}const dr=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&&(jn(t,e),s=!1),e)}}();function ur(e,t,s,n){t.emit(s,n,s),Mn(e,s,r=>{if(!e.has(r,Qn))return!1;const o=e.get(r,Qn);return o.enabled&&t.emit(r,n,s),o.blockRaycast})}class hr{build(e){q("Interactable",Qn),q("Button",tr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),r=new sr;e.insertResource(nr,r);let o=null,i=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,a)=>{if(r.drain(),lr()&&!cr())return;const l=t.getEntitiesWithComponents([Zn]);for(const e of l){const s=t.get(e,Zn);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Zn,s))}if(!a.valid)return;const d=c(),u=e.mouseX*d,h=a.screenH-e.mouseY*d;dr.update(a.viewProjection);const f=Yn(u,h,dr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=f.x,a.worldMouseY=f.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);s.uiHitTest_update(n,f.x,f.y,p,g,y);const m=s.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Zn)){const e=t.get(o,Zn);e.hovered=!1,t.insert(o,Zn,e),r.emit(o,"hover_exit")}if(null!==_){Tn(t,_,Zn);const e=t.get(_,Zn);e.hovered=!0,t.insert(_,Zn,e),r.emit(_,"hover_enter")}o=_}if(g&&null!==_){const e=t.get(_,Zn);e.pressed=!0,e.justPressed=!0,t.insert(_,Zn,e),i=_,ur(t,r,_,"press")}if(y&&null!==i){if(t.valid(i)&&t.has(i,Zn)){const e=t.get(i,Zn);e.pressed=!1,e.justReleased=!0,t.insert(i,Zn,e),ur(t,r,i,"release"),i===o&&ur(t,r,i,"click")}i=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([],()=>{const e=t.getEntitiesWithComponents([tr]);for(const s of e){if(Tn(t,s,Qn,{enabled:!0}),!t.has(s,Zn))continue;const e=t.get(s,Zn),n=t.get(s,tr),r=t.get(s,Qn),o=!a.has(s),i=n.state;if(r.enabled?e.pressed?n.state=er.Pressed:e.hovered?n.state=er.Hovered:n.state=er.Normal:n.state=er.Disabled,o&&a.add(s),(o||i!==n.state)&&n.transition&&t.has(s,re)){const o=t.get(s,re);o.color=_n(n.transition,r.enabled,e.pressed,e.hovered),t.insert(s,re,o)}}},{name:"ButtonSystem"}))}}const fr=new hr,pr=j("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}),gr=j("Focusable",{tabIndex:0,isFocused:!1});class yr{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 mr=we(new yr,"FocusManager");class _r{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(q("TextInput",pr),lr()&&!cr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=a(U.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let i=0,l=0,c=!1,d=!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 g(){const t=e.getResource(mr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,pr)?n:null}const y=()=>{c||null===g()||v()},m=()=>{c=!0},_=()=>{c=!1,v()},x=t=>{const n=g();if(null===n)return;if("Escape"===t.key)return void b();const r=s.get(n,pr);if("Enter"===t.key&&!r.multiline){t.preventDefault();return e.getResource(nr).emit(n,"submit"),void b()}let o=r.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,r.cursorPos-1):"ArrowRight"===t.key?o=Math.min(r.value.length,r.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=r.value.length),o!==r.cursorPos&&(r.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,r.dirty=!0,S())},w=()=>{const t=g();if(null!==t){const n=s.get(t,pr);n.focused=!1,n.dirty=!0;e.getResource(mr).blur()}};function v(){const t=g();if(null===t)return;const n=s.get(t,pr);if(n.readOnly)return;let r=p.value;if(n.maxLength>0&&r.length>n.maxLength&&(r=r.substring(0,n.maxLength),p.value=r),r!==n.value){n.value=r;e.getResource(nr).emit(t,"change")}n.cursorPos=p.selectionStart??r.length,n.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=s.get(t,pr);e.focused=!1,e.dirty=!0}e.getResource(mr).blur(),p.blur()}function S(){d=!0,u=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",x),p.addEventListener("blur",w),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",x),p.removeEventListener("blur",w),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==i&&(t._free(i),i=0,l=0)};let P=null;function M(e,a,c,u){(r.width<c||r.height<u)&&(r.width=vn(Math.max(r.width,c)),r.height=vn(Math.max(r.height,u))),o.clearRect(0,0,r.width,r.height);const h=a.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(a.padding,0,c-2*a.padding,u),o.clip(),o.font=`${a.fontSize}px ${a.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===a.value.length,p=f?a.placeholder:a.password?"●".repeat(a.value.length):a.value,g=f?a.placeholderColor:a.color;o.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*a.fontSize),m=a.padding;if(a.multiline){const e=wn(o,p,c-2*m);let t=m;for(const s of e)o.fillText(s,m,t),t+=y}else{const e=(u-a.fontSize)/2;o.fillText(p,m,e)}if(a.focused&&d){const e=a.password?"●".repeat(a.cursorPos):a.value.substring(0,a.cursorPos);let t,s,n;if(a.multiline){const e=wn(o,a.value,c-2*m);let r=0,i=0,l=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(r+s>=a.cursorPos){i=t,l=a.cursorPos-r;break}r+=s,t<e.length-1&&r<a.value.length&&"\n"===a.value[r]&&r++,i=t+1,l=0}const d=i<e.length?e[i].substring(0,l):"";t=m+o.measureText(d).width,s=m+i*y,n=y}else t=m+o.measureText(e).width,s=(u-a.fontSize)/2,n=a.fontSize;o.fillStyle=`rgba(${Math.round(255*a.color.r)}, ${Math.round(255*a.color.g)}, ${Math.round(255*a.color.b)}, ${a.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>l&&(0!==i&&t._free(i),i=t._malloc(x.length),l=x.length),t.HEAPU8.set(x,i);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const b=w.createTexture(c,u,i,x.length,1,!0);n.set(e,b);const S=s.get(e,re);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,re,S)}e.addSystemToSchedule(exports.Schedule.Update,et([ve(mr)],e=>{const t=s.getEntitiesWithComponents([pr]);for(const e of t)Tn(s,e,gr,{tabIndex:0,isFocused:!1}),Tn(s,e,Qn,{enabled:!0,blockRaycast:!0});const n=g();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,pr)){const e=s.get(P,pr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,pr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let r=0===h?0:(e-h)/1e3;h=e,r=Math.min(r,.1);const o=g();if(null!==o&&(u+=r,u>=.5)){u-=.5,d=!d;s.get(o,pr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,pr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([pr,hn]);for(const e of a){const t=s.get(e,pr);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(gn(s,e),M(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const xr=new _r,wr={Simple:0,Sliced:1,Tiled:2,Filled:3},vr={Horizontal:0,Vertical:1},br={Left:0,Right:1,Bottom:2,Top:3},Sr=j("Image",{texture:L,color:{r:1,g:1,b:1,a:1},imageType:wr.Simple,fillMethod:vr.Horizontal,fillOrigin:br.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Pr=Cn({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?Sn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Pn(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Mr=new class{build(e){q("Image",Sr);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Sr)||s.delete(e);const e=t.getEntitiesWithComponents([Sr]);for(const n of e){const e=t.get(n,Sr),r=t.has(n,hn)?t.get(n,hn):null,o={image:e,uiRect:r,entity:n},i=s.get(n);if(i&&!Pr.changed(i,o))continue;gn(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,r&&(a.size.x=Sn(r,n),a.size.y=Pn(r,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===wr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===vr.Horizontal?e.fillOrigin===br.Left?(a.uvScale.x=t,a.size.x=s*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=s*t):e.fillOrigin===br.Bottom?(a.uvScale.y=t,a.size.y=n*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=n*t)}else e.imageType===wr.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,Pr.take(o))}else a.color.a=0,t.insert(n,re,a),s.set(n,Pr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Tr=j("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Er=j("ToggleGroup",{allowSwitchOff:!1});const Cr=new class{build(e){q("Toggle",Tr),q("ToggleGroup",Er);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,et([ve(nr)],e=>{const n=t.getEntitiesWithComponents([Tr]);if(!lr()||cr()){const r=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Tr);n.isOn&&0!==n.group&&t.valid(n.group)&&(r.has(n.group)?(n.isOn=!1,t.insert(e,Tr,n)):r.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Tr);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(Tn(t,s,Qn,{enabled:!0}),!t.has(s,Zn))continue;const n=t.get(s,Zn),r=t.get(s,Tr),i=t.get(s,Qn);if(n.justPressed&&i.enabled){const n=r.group,i=0!==n&&t.valid(n)&&t.has(n,Er);if(r.isOn&&i){if(!t.get(n,Er).allowSwitchOff)continue}if(r.isOn=!r.isOn,t.insert(s,Tr,r),r.isOn&&i){const r=o.get(n);if(r)for(const n of r){if(n===s)continue;const r=t.get(n,Tr);r.isOn&&(r.isOn=!1,t.insert(n,Tr,r),e.emit(n,"change"))}}e.emit(s,"change")}if(r.transition&&t.has(s,re)){const e=t.get(s,re);e.color=_n(r.transition,i.enabled,n.pressed,n.hovered),t.insert(s,re,e)}}}for(const e of n){const s=t.get(e,Tr);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"]})}},Rr=dn,Ar=j("ProgressBar",{value:0,fillEntity:0,direction:dn.LeftToRight});function Ir(e,t,s,n){if(!e.has(t,hn))return;const r=e.get(t,hn),o=s/2,i=n/2,a={left:-o,bottom:-i,right:o,top:i},l=un(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,a,r.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,te)){const s=e.get(t,te),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,te,s))}}class Fr{build(e){q("ProgressBar",Ar);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([Ar,hn]);for(const s of e){const e=t.get(s,Ar);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,hn),r=Math.max(0,Math.min(1,e.value));mn(t,e.fillEntity,e.direction,r);const o=Sn(n,s),i=Pn(n,s);Ir(t,e.fillEntity,o,i)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const kr=new Fr,Br=j("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Dr=j("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 Ur=new class{build(e){q("Draggable",Br),q("DragState",Dr);const t=e.world,s=e.getResource(nr);let n=null,r={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at)],(e,i)=>{if(lr()&&!cr())return;if(!i.valid)return;const a={x:i.worldMouseX,y:i.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Br,Zn]);let s=null,o=-1/0,i=-1;for(const n of e){if(!t.get(n,Br).enabled)continue;if(t.get(n,Zn).hovered){let e=0;t.has(n,re)&&(e=t.get(n,re).layer);const r=bn(t,n);(e>o||e===o&&r>=i)&&(o=e,i=r,s=n)}}if(null!==s){n=s,r={x:a.x,y:a.y},t.has(s,Dr)||t.insert(s,Dr);const e=t.get(s,Dr),o=t.get(s,te);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,Dr)){t.get(n,Dr).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-r.x,l=a.y-r.y,c=Math.sqrt(e*e+l*l),d=t.get(n,Br);if(c*(i.vpW/(i.worldRight-i.worldLeft))>=d.dragThreshold){o=n,n=null;t.get(o,Dr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Dr))return void(o=null);const n=t.get(o,Dr),r=t.get(o,Br),i=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+i,d=n.startWorldPos.y+l;const u=function(e,t,s,n){let r=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(r=Math.max(r,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(r=Math.min(r,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:r,y:o}}(r,n,c,d);c=u.x,d=u.y;const h=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:d-f},n.currentWorldPos={x:c,y:d},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:d-n.startWorldPos.y},t.has(o,te)){const e=function(e,t,s,n){if(!e.has(t,le))return{x:s,y:n};const r=e.get(t,le).entity;if(!e.valid(r)||!e.has(r,te))return{x:s,y:n};const o=e.get(r,te),i=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Nn(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(s*d-n*c)/i,y:(s*c+n*d)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,te);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,te,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}},Lr=j("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function zr(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 Wr(e,t,s,n,r){const o=2/(n=Math.max(1e-4,n)),i=o*r,a=1/(1+i+.48*i*i+.235*i*i*i),l=e-t,c=(s+o*l)*r,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(s-o*c)*a}}const $r=new class{build(e){q("ScrollView",Lr);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt),ve(at),ve(Me)],(e,r,o)=>{const i=lr()&&!cr(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);r.valid&&(n.x=r.worldMouseX,n.y=r.worldMouseY);const l=t.getEntitiesWithComponents([Lr,hn]);for(const o of l){Tn(t,o,Hn,{enabled:!0,mode:$n});const l=t.get(o,Lr),c=t.get(o,hn);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=Sn(c,o),h=Pn(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,ce)){const e=t.get(l.contentEntity,ce).entities;let s=0,n=0,r=0,o=0;for(const i of e){if(!t.valid(i)||!t.has(i,te))continue;const e=t.get(i,te);let a=0,l=0,c=.5,d=.5;if(t.has(i,hn)){const e=t.get(i,hn);a=Sn(e,i)||e.size.x,l=Pn(e,i)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(i,re)){const e=t.get(i,re);a=e.size.x,l=e.size.y}const u=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);u<s&&(s=u),h>n&&(n=h),f<r&&(r=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-r)}const g=Math.max(0,f-u),y=Math.max(0,p-h);if(!i&&r.valid){Tn(t,o,Qn,{enabled:!0,blockRaycast:!0});const s=t.has(o,Zn)?t.get(o,Zn):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=zr(l.scrollX,0,g,u);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const n=a>0?-e*t/a:0;d.velocityX+=(n-d.velocityX)*s}}if(l.verticalEnabled){const e=zr(l.scrollY,0,y,h);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const n=a>0?t*e/a:0;d.velocityY+=(n-d.velocityY)*s}}d.lastWorldX=n.x,d.lastWorldY=n.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*u,t=5*h;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=zr(l.scrollY,0,y,h);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=zr(l.scrollX,0,g,u);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Wr(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)<Rn&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Rn?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Wr(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)<Rn&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Rn?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*u,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,te)){const e=t.get(l.contentEntity,te),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,te,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Or=dn,Hr=j("Slider",{value:0,minValue:0,maxValue:1,direction:dn.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Xr(e,t,s,n,r,o){const i=Sn(n,r)*s.worldScale.x,a=Pn(n,r)*s.worldScale.y,l=Nn(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),u=e-s.worldPosition.x,h=t-s.worldPosition.y,f=u*d-h*c,p=u*c+h*d,g=-n.pivot.x*i,y=-n.pivot.y*a;switch(o){case dn.LeftToRight:return i>0?(f-g)/i:0;case dn.RightToLeft:return i>0?1-(f-g)/i:0;case dn.BottomToTop:return a>0?(p-y)/a:0;case dn.TopToBottom:return a>0?1-(p-y)/a:0}}function jr(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case dn.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case dn.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case dn.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case dn.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class Yr{build(e){q("Slider",Hr);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(rt),ve(at),ve(nr)],(e,n,r)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([Hr,hn]);for(const i of o){const o=t.get(i,Hr),a=t.get(i,hn);if(!lr()||cr()){if(t.has(i,te)){Tn(t,i,Qn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Tn(t,o.handleEntity,Qn,{enabled:!0,blockRaycast:!1});const l=t.get(i,te),c=t.has(i,Zn)?t.get(i,Zn):null;let d=c?.justPressed??!1;if(!d&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Zn)&&(d=t.get(o.handleEntity,Zn).justPressed),d&&(s=i),s===i&&e.isMouseButtonDown(0)){let e=Xr(n.worldMouseX,n.worldMouseY,l,a,i,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(i,Hr,o),o.value!==c&&r.emit(i,"change")}s===i&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,d=Sn(a,i),u=Pn(a,i),h={left:-d/2,bottom:-u/2,right:d/2,top:u/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(mn(t,o.fillEntity,o.direction,c),En(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,hn)){const e=t.get(o.handleEntity,hn);jr(e,o.direction,c),t.insert(o.handleEntity,hn,e),En(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nr=new Yr;const Vr=new class{build(e){q("Focusable",gr);const t=e.world,s=new yr;e.insertResource(mr,s),e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(nr)],(e,n)=>{if(lr()&&!cr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const r=t.getEntitiesWithComponents([gr]);for(const e of r){if(!t.has(e,Zn))continue;t.get(e,Zn).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of r){if(!t.valid(s))continue;if(t.has(s,Qn)){if(!t.get(s,Qn).enabled)continue}const n=t.get(s,gr);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const i=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===i?a?n.length-1:0:a?(i-1+n.length)%n.length:(i+1)%n.length,o(n[l])}function o(e){const r=s.focusedEntity;if(r===e)return;if(null!==r&&t.valid(r)&&t.has(r,gr)){t.get(r,gr).isFocused=!1,n.emit(r,"blur",r)}s.focus(e);t.get(e,gr).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Gr=j("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function qr(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:r}=t;return{top:s.top,bottom:r-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}const Kr=new class{build(e){q("SafeArea",Gr);const t=e.world;let n=qr(),r=!0,o=0,i=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=qr(),r=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=qr(),r=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,et([ve(at)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===i||(o=e.screenH,i=a,r=!0),!r)return;r=!1;const l=c(),d=s()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Gr,hn]);for(const e of u){const s=t.get(e,Gr),r=t.get(e,hn),o=s.applyTop?n.top*d:0,i=s.applyBottom?n.bottom*d:0,a=s.applyLeft?n.left*d:0,l=s.applyRight?n.right*d:0;let c=!1;r.offsetMin.x===a&&r.offsetMin.y===i||(r.offsetMin={x:a,y:i},c=!0),r.offsetMax.x===-l&&r.offsetMax.y===-o||(r.offsetMax={x:-l,y:-o},c=!0),c&&t.insert(e,hn,r)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Jr=j("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Qr=null;const Zr=new class{build(e){q("ListView",Jr);const t=e.world,s=new Map;Qr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(rt)],e=>{const n=lr()&&!cr();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const r=t.getEntitiesWithComponents([Jr,hn]);for(const o of r){Tn(t,o,Qn,{enabled:!0,blockRaycast:!0}),Tn(t,o,Hn,{enabled:!0,mode:$n});let r=s.get(o);r||(r={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,r));const i=t.get(o,Jr),a=t.get(o,hn),l=Pn(a,o),c=Sn(a,o);if(!n){const s=t.has(o,Zn)?t.get(o,Zn):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(i.scrollY+=.1*t.y)}}const d=Math.max(0,i.itemCount*i.itemHeight-l);i.scrollY=Math.max(0,Math.min(i.scrollY,d));const u=Math.max(0,Math.floor(i.scrollY/i.itemHeight)-i.overscan),h=Math.min(i.itemCount,Math.ceil((i.scrollY+l)/i.itemHeight)+i.overscan);for(const[e,s]of r.itemEntities)(e<u||e>=h)&&(t.valid(s)&&t.despawn(s),r.itemEntities.delete(e));for(let e=u;e<h;e++){let s=r.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,he,{value:`ListItem_${e}`}),t.insert(s,hn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:i.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),r.itemEntities.set(e,s),r.renderer&&r.renderer(e,s)),t.has(s,te)){const n=t.get(s,te);n.position.y=-(e*i.itemHeight-i.scrollY),t.insert(s,te,n)}}r.visibleStart=u,r.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},eo=j("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const to=new class{build(e){q("Dropdown",eo);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,te))return;const s=t.get(e,te);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,te,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function r(e){if(t.has(e,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 r=s.listEntity;if(0===r||!t.valid(r))return;d(r,!0),c(n);const o=t.get(e,re),i=o.size.x,a=o.size.y;n.ddWidth=i;const l=s.options.length*An;t.insert(r,hn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:l},pivot:{x:.5,y:.5}}),t.insert(r,te,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,re,{texture:L,color:{r:1,g:1,b:1,a:1},size:{x:i,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*An;t.insert(o,he,{value:`Option_${e}`}),t.insert(o,hn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*An},offsetMax:{x:0,y:0},size:{x:i,y:An},pivot:{x:.5,y:.5}}),t.insert(o,te,{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:L,color:{r:.95,g:.95,b:.95,a:1},size:{x:i,y:An},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Qn,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,r),n.optionEntities.push(o);const c=t.spawn();t.insert(c,te,{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,Dn,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Fn.Left,verticalAlign:kn.Middle,wordWrap:!1,overflow:Bn.Clip,lineHeight:1.2}),t.insert(c,hn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:i,y:An},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}u(n)}function i(e,t,s){t.isOpen=!1,c(s),d(t.listEntity,!1)}function a(e,t,s,n,r){t.selectedIndex=n,i(0,t,s),r.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Dn))return;const n=t.get(s,Dn);let r={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,i=!1;if(1===r.r&&1===r.g&&1===r.b&&1===r.a&&(r={r:0,g:0,b:0,a:1},i=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,i=!0)}i&&t.insert(s,Dn,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:r,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function d(e,s){if(0!==e&&t.valid(e)&&(t.has(e,Qn)&&t.insert(e,Qn,{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 u(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 r=s===e.highlightIndex?{...In}:{r:.95,g:.95,b:.95,a:1};t.insert(n,re,{texture:L,color:r,size:{x:e.ddWidth,y:An},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,Zn))continue;if(t.get(s,Zn).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,et([ve(rt),ve(nr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=lr()&&!cr(),p=t.getEntitiesWithComponents([eo]);for(const g of p){const p=t.get(g,eo);let y=s.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(g,y)),n(p.listEntity),r(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Tn(t,g,Qn,{enabled:!0,blockRaycast:!0});const m=t.has(g,Zn)?t.get(g,Zn):null;if(m?.justPressed&&(p.isOpen?i(g,p,y):o(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,Zn))continue;if(t.get(s,Zn).justPressed){a(g,p,y,e,c);break}}let s=-1;for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,Zn))continue;if(t.get(n,Zn).hovered){s=e;break}}s>=0&&s!==y.highlightIndex&&(y.highlightIndex=s,u(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,u(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,u(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&i(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||h(y)||i(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},so=0,no=0,ro=2,oo=j("LayoutGroup",{direction:so,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:no,reverseOrder:!1});const io=new class{build(e){q("LayoutGroup",oo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,et([],()=>{const e=t.getEntitiesWithComponents([oo,hn,ce]);for(const s of e){const e=t.get(s,oo),n=t.get(s,hn),r=t.get(s,ce);if(!r.entities||0===r.entities.length)continue;const o=[];for(const e of r.entities)t.valid(e)&&t.has(e,hn)&&t.has(e,te)&&o.push({entity:e,rect:t.get(e,hn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const i=Sn(n,s),a=Pn(n,s),l=n.pivot.x,c=n.pivot.y,d=e.padding,u=e.direction===so;let h=0;for(let s=0;s<o.length;s++){const n=o[s],r=Sn(n.rect,n.entity),f=Pn(n.rect,n.entity),p=n.rect.pivot.x,g=n.rect.pivot.y;let y,m;u?(y=-l*i+d.left+h+p*r,m=e.childAlignment===no?(1-c)*a-d.top-(1-g)*f:e.childAlignment===ro?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,h+=r,s<o.length-1&&(h+=e.spacing)):(y=e.childAlignment===no?-l*i+d.left+p*r:e.childAlignment===ro?(1-l)*i-d.right-(1-p)*r:(.5-l)*i+.5*(d.left-d.right)+(p-.5)*r,m=(1-c)*a-d.top-h-(1-g)*f,h+=f,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,te);_.position.x=y,_.position.y=m,t.insert(n.entity,te,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};J("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),J("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class ao{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,et([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const lo=new ao;async function co(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 uo=we({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ho=we(null,"PhysicsAPI");function fo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function po(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class go{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(uo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=co(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ie]);for(const s of t){const t=e.world.get(s,ie);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;i.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,et([ve(Me)],a=>{const l=i.getEntitiesWithComponents([pe,te]),c=new Set;for(const r of l){c.add(r);const a=i.get(r,pe),l=i.get(r,te);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=fo(l.worldRotation);n._physics_createBody(r,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),yo(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===_e.Kinematic){const e=fo(l.worldRotation);n._physics_setBodyTransform(r,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const d=e.world.get(i,te);if(!d)continue;let u=a,h=l,f=c;if(e.world.has(i,le)){const t=e.world.get(i,le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,te)){const s=e.world.get(t.entity,te),n=fo(s.worldRotation),r=a-s.worldPosition.x,o=l-s.worldPosition.y,i=Math.cos(-n),d=Math.sin(-n);u=(r*i-o*d)/(0!==s.worldScale.x?s.worldScale.x:1),h=(r*d+o*i)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}d.position.x=u,d.position.y=h;const p=po(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(i,te,d)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<d;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(uo,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ho,mo._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function yo(e,t,s){const n=e.world;if(n.has(s,ge)){const e=n.get(s,ge);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,ye)){const e=n.get(s,ye);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,me)){const e=n.get(s,me);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 mo{constructor(e){if(this.module_=e.physicsModule,!this.module_)throw new Error("Physics module not loaded. Ensure PhysicsPlugin init is complete.")}static _fromModule(e){const t=Object.create(mo.prototype);return t.module_=e,t}applyForce(e,t){this.module_._physics_applyForce(e,t.x,t.y)}applyImpulse(e,t){this.module_._physics_applyImpulse(e,t.x,t.y)}setLinearVelocity(e,t){this.module_._physics_setLinearVelocity(e,t.x,t.y)}getLinearVelocity(e){const t=this.module_._physics_getLinearVelocity(e)>>2;return{x:this.module_.HEAPF32[t],y:this.module_.HEAPF32[t+1]}}setGravity(e){this.module_._physics_setGravity(e.x,e.y)}getGravity(){const e=this.module_._physics_getGravity()>>2;return{x:this.module_.HEAPF32[e],y:this.module_.HEAPF32[e+1]}}setAngularVelocity(e,t){this.module_._physics_setAngularVelocity(e,t)}getAngularVelocity(e){return this.module_._physics_getAngularVelocity(e)}applyTorque(e,t){this.module_._physics_applyTorque(e,t)}applyAngularImpulse(e,t){this.module_._physics_applyAngularImpulse(e,t)}}const _o={nearest:0,linear:1},xo={repeat:0,clamp:1,mirror:2};function wo(e,t,s=!0,n){const r=e.getResourceManager(),o=e._malloc(t.pixels.length);let i;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&r.createTextureEx){const e=_o[n.filterMode??"linear"]??1,a=xo[n.wrapMode??"clamp"]??1;i=r.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else i=r.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),i}function vo(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(/\.png$/i.test(e)||/\.jpg$/i.test(e))&&t.push(e)}return t}function bo(e,t,s,n){const r=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),i=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,u=a+a,h=l+l,f=c+c,p=a*u,g=a*h,y=a*f,m=l*h,_=l*f,x=c*f,w=d*u,v=d*h,b=d*f;return new Float32Array([(1-(m+x))*r,(g+b)*r,(y-v)*r,0,(g-b)*o,(1-(p+x))*o,(_+w)*o,0,(y+v)*i,(_-w)*i,(1-(p+m))*i,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function So(e,t,s,n,r,o,i,a,l){const c=await async function(e,t,s){const n={},r=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=Rt(t.type);for(const i of o){if("texture"!==i.type)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=r?.[o];n[o]=wo(e,await s.loadPixels(o),!0,t)}catch{n[o]=0}}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,c);let d={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),d=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){const i=At(n.type);if(!i||!n.data)continue;const a=n.data[i.skeletonField],l=n.data[i.atlasField];if(!a||!l)continue;const c=r.resolvePath(a),d=r.resolvePath(l);try{const n=await r.readText(l),i="binary"===m(c)?.contentType;let u,h;if(i){const e=await r.readBinary(a);h=e.length,u=t._malloc(h),t.HEAPU8.set(e,u)}else{const e=await r.readText(a),s=(new TextEncoder).encode(e);h=s.length,u=t._malloc(h+1),t.HEAPU8.set(s,u),t.HEAPU8[u+h]=0}const f=s.loadSkeleton(u,h,n,n.length,i);if(t._free(u),f<0)continue;o[a]=f;const p=vo(n),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=g+"/"+p[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=wo(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,u,s,n)),o){const t={gravity:i?.gravity??{...B},fixedTimestep:i?.fixedTimestep??D,subStepCount:i?.subStepCount??4};new go("",t,()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){const r=Rt(t.type).find(e=>"font"===e.type);if(!r)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,r;const i=m(o);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(o)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${i}`:i;t=await s.readText(l),r=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),r=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=r?`${r}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),d=wo(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),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=Rt(e.type).find(e=>"material"===e.type);if(!r)continue;const o=e.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const r=e.vertexSource+e.fragmentSource;let i=n[r];i||(i=mt.createShader(e.vertexSource,e.fragmentSource),n[r]=i),s[o]=mt.createFromAsset(e,i)}catch{s[o]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=Rt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,c,h,f);const p=Dt(e.world,s);if(l&&e.hasResource(Ys))for(const t of p.values())e.world.insert(t,fe,{scene:l,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const i=At(t.type);if(!i||!t.data)continue;const a=s[t.data[i.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return r}(u,s,d,p);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=k);const c=e.world;for(const e in r){const o=Number(e),i=r[e],a=c.has(o,ue)?c.get(o,ue):null,d=!1!==a?.playing,u=a?.timeScale??1;d&&n.update(i,l*u);let h=0;if(c.has(o,te)){const e=bo(c.get(o,te),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(i);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,l=2*o,c=s._malloc(a),d=s._malloc(l),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(i,e,c,d,u,f);const p=s.HEAPU32[u>>2],g=s.HEAPU32[f>>2],y=new Float32Array(s.HEAPF32.buffer,c,8*r),m=new Uint16Array(s.HEAPU8.buffer,d,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(_,r,x,o,p,g,h),t._free(_),t._free(x),s._free(c),s._free(d),s._free(u),s._free(f)}h&&t._free(h)}})}(e,t,r,u,n)}if(a){const t=e.getResource($t);t&&t.setAddressableManifest(a)}}class Po{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components){if(!e.data)continue;const r=At(e.type);if(r){const n=e.data[r.skeletonField],o=e.data[r.atlasField];n&&("binary"===m(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Rt(e.type);for(const s of o){const r=e.data[s.field];"string"==typeof r&&r&&("font"===s.type?(n.add(r),t.add(r)):"material"===s.type&&t.add(r))}}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=m(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Mo="__preview__";const To={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Ds.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Ds.getTargetTexture(s),width:e.width,height:e.height}},release(e){Ds.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ds.releaseRenderTarget(e._handle),To.create({width:t,height:s,depth:!0})),begin(e,t){Ds.begin(t,e._handle)},end(){Ds.end()},getDepthTexture:e=>Ds.getTargetDepthTexture(e._handle)};var Eo;exports.LogLevel=void 0,(Eo=exports.LogLevel||(exports.LogLevel={}))[Eo.Debug=0]="Debug",Eo[Eo.Info=1]="Info",Eo[Eo.Warn=2]="Warn",Eo[Eo.Error=3]="Error";class Co{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 Ro{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new Co)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Ao=new Ro;const Io=[Wn,Jn,or,Mr,kr,fr,Ur,$r,Nr,Cr,xr,Vr,Kr,Zr,to,io,lo];R||(R=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await d(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return u(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=A,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.App=qs,exports.AssetPlugin=Ot,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=Wt,exports.Assets=$t,exports.AsyncCache=Tt,exports.BitmapText=de,exports.BodyType=_e,exports.BoxCollider=ge,exports.Button=tr,exports.ButtonState=er,exports.Camera=oe,exports.Canvas=ie,exports.CapsuleCollider=me,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=ce,exports.CircleCollider=ye,exports.ClearFlags=Z,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Ve,exports.DEFAULT_DESIGN_HEIGHT=F,exports.DEFAULT_DESIGN_WIDTH=I,exports.DEFAULT_FALLBACK_DT=k,exports.DEFAULT_FIXED_TIMESTEP=D,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=B,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=Dr,exports.Draggable=Br,exports.Draw=as,exports.Dropdown=eo,exports.EntityCommands=Ne,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=Je,exports.EventRegistry=qe,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=Ke,exports.FillDirection=dn,exports.FillMethod=vr,exports.FillOrigin=br,exports.FocusManager=mr,exports.FocusManagerState=yr,exports.Focusable=gr,exports.GLDebug=Ws,exports.Geometry=Ss,exports.GetWorld=function(){return{_type:"get_world"}},exports.INVALID_ENTITY=0,exports.INVALID_FONT=z,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=L,exports.Image=Sr,exports.ImageType=wr,exports.Input=rt,exports.InputPlugin=ot,exports.InputState=nt,exports.Interactable=Qn,exports.ListView=Jr,exports.LocalTransform=se,exports.Logger=Ro,exports.Material=mt,exports.MaterialLoader=Et,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=he,exports.Parent=le,exports.Physics=mo,exports.PhysicsEvents=uo,exports.PhysicsPlugin=go,exports.PostProcess=Cs,exports.PrefabServer=Gt,exports.Prefabs=qt,exports.PrefabsPlugin=Kt,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(Ys);t.register({name:Mo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Mo),this.loadPromise_=t.load(Mo).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 Po(this.baseUrl_);await s.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await So(this.app_,this.app_.wasmModule,t,s,r,null,void 0,null,Mo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([oe]);for(const n of s){if(e.get(n,oe).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([ie]);for(const r of n){const n=e.get(r,ie);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ys).getScene(Mo),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,te,i);const a={isActive:!0,projectionType:Q.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Z.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(Ys);await e.switchTo(Mo),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=Ar,exports.ProgressBarDirection=Rr,exports.ProgressBarPlugin=Fr,exports.ProjectionType=Q,exports.Query=function(...e){return Xe(e)},exports.QueryInstance=je,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=Ye,exports.RenderPipeline=$s,exports.RenderTexture=To,exports.Renderer=Ds,exports.Res=ve,exports.ResMut=be,exports.RigidBody=pe,exports.RuntimeConfig=U,exports.SafeArea=Gr,exports.ScaleMode=ee,exports.SceneManager=Ys,exports.SceneManagerState=js,exports.SceneOwner=fe,exports.ScrollView=Lr,exports.ShaderSources=Mt,exports.Slider=Hr,exports.SliderDirection=Or,exports.SliderPlugin=Yr,exports.SpineAnimation=ue,exports.Sprite=re,exports.SystemRunner=st,exports.Text=Dn,exports.TextAlign=Fn,exports.TextInput=pr,exports.TextInputPlugin=_r,exports.TextOverflow=Bn,exports.TextPlugin=zn,exports.TextRenderer=Un,exports.TextVerticalAlign=kn,exports.Time=Me,exports.Toggle=Tr,exports.Transform=te,exports.UICameraInfo=at,exports.UIEventQueue=sr,exports.UIEvents=nr,exports.UIInteraction=Zn,exports.UIInteractionPlugin=hr,exports.UILayoutPlugin=rr,exports.UIMask=Hn,exports.UIMaskPlugin=Kn,exports.UIRect=hn,exports.UIRenderOrderPlugin=ao,exports.Velocity=ae,exports.WebAssetProvider=Po,exports.World=ze,exports.WorldTransform=ne,exports.addStartupSystem=function(e){tt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){tt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){tt().push({schedule:e,system:t})},exports.applyDirectionalFill=mn,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=U.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=U.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=U.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=U.canvasMatchWidthOrHeight)},exports.assetPlugin=Ht,exports.clearDrawCallbacks=ps,exports.clearUserComponents=function(){const e=X();for(const t of e.keys())G.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=yn,exports.computeFillSize=function(e,t,s,n){switch(e){case dn.BottomToTop:case dn.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case dn.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case dn.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case dn.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=un,exports.createMaskProcessor=qn,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,async setup(){await So(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=qs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ns(e),pt(e),ws(e),Ms(e),ks(e),Ls(e);const r=new $s;s.setPipeline(r);let o=l();const i=t?.getViewportSize??(()=>{const e=c();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,r,o){o||(o=en(e,n,t,r));const i=s.getResource(at);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(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 d={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();a(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=i();if(0===t||0===c)return;const d=e.registry_getCanvasEntity(n);if(d>=0){const e=n.getCanvas(d).backgroundColor;Ds.setClearColor(e.x,e.y,e.z,e.w)}const u=(l()-o)/1e3;let h;if(Ds.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ys)){const e=s.getResource(Ys).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const f=en(e,n,t,c,s.world,h);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:Ks,width:t,height:c,elapsed:u});else{for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:l},clearFlags:e.clearFlags,elapsed:u})}Ds.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(exports.Schedule.First,d),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(Ht),s.addPlugin(Jt),s.addPlugin(it),s.addPlugin(Gs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Io,...t})},exports.debug=function(e,t,s){Ao.debug(e,t,s)},exports.defineComponent=j,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=we,exports.defineSystem=et,exports.defineTag=function(e){const t=G.get(e)??X().get(e);if(t)return t;const s=O(e,{});return X().set(e,s),G.set(e,s),N(e,{},!0),s},exports.error=function(e,t,s){Ao.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([he]);for(const n of s){const s=e.get(n,he);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return m(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of h)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return g},exports.getAssetMimeType=function(e){return f[e.toLowerCase()]},exports.getAssetTypeEntry=m,exports.getComponent=K,exports.getComponentAssetFieldDescriptors=Rt,exports.getComponentAssetFields=function(e){const t=Ct.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},exports.getComponentDefaults=function(e){const t=K(e);return t?W(t._default):null},exports.getComponentEntityFields=Ft,exports.getComponentSpineFieldDescriptor=At,exports.getCustomExtensions=x,exports.getEditorType=function(e){return m(e)?.editorType??"unknown"},exports.getLogger=function(){return Ao},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=Y,exports.getWeChatPackOptions=function(){return x().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Ao.info(e,t,s)},exports.initDrawAPI=ns,exports.initGLDebugAPI=Ls,exports.initGeometryAPI=ws,exports.initMaterialAPI=pt,exports.initPostProcessAPI=Ms,exports.initRendererAPI=ks,exports.inputPlugin=it,exports.instantiatePrefab=Xt,exports.intersectRects=Xn,exports.invertMatrix4=jn,exports.isBuiltinComponent=V,exports.isCustomExtension=w,exports.isEditor=lr,exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=cr,exports.isRuntime=function(){return!ir},exports.isTextureRef=ct,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=zt,exports.loadPhysicsModule=co,exports.loadRuntimeScene=So,exports.loadSceneData=Dt,exports.loadSceneWithAssets=Ut,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(y(e)))},exports.platformFetch=n,exports.platformFileExists=i,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=r,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,r,o,i,a,l,c){const d=Nn(l,c),u=Math.sin(-d),h=Math.cos(-d),f=e-s,p=t-n,g=f*h-p*u+s,y=f*u+p*h+n;return g>=s-r*i&&g<=s+r*(1-i)&&y>=n-o*a&&y<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)},exports.prefabsPlugin=Jt,exports.progressBarPlugin=kr,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=q,exports.registerComponentAssetFields=function(e,t){Ct.set(e,t)},exports.registerComponentEntityFields=function(e,t){It.set(e,t)},exports.registerDrawCallback=hs,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource($t);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=Pt,exports.remapEntityFields=kt,exports.sceneManagerPlugin=Gs,exports.screenToWorld=Yn,exports.setEditorMode=function(e){ir=e},exports.setListViewRenderer=function(e,t){if(!Qr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Qr.get(e);s?s.renderer=t:Qr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){Ao.setMinLevel(e)},exports.setPlayMode=function(e){ar=e},exports.setWasmErrorHandler=Ae,exports.shutdownDrawAPI=rs,exports.shutdownGLDebugAPI=zs,exports.shutdownGeometryAPI=vs,exports.shutdownMaterialAPI=gt,exports.shutdownPostProcessAPI=Ts,exports.shutdownRendererAPI=Bs,exports.sliderPlugin=Nr,exports.syncFillSpriteSize=function(e,t,s,n,r,o){if(!e.has(t,re))return;const i=e.get(t,re);let a,l;switch(s){case dn.BottomToTop:case dn.TopToBottom:a=r,l=o*n;break;default:a=r*n,l=o}i.size.x===a&&i.size.y===l||(i.size.x=a,i.size.y=l,e.insert(t,re,i))},exports.textInputPlugin=xr,exports.textPlugin=Wn,exports.transitionTo=async function(e,t,s){const n=e.getResource(Ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=fr,exports.uiLayoutPlugin=or,exports.uiMaskPlugin=Jn,exports.uiPlugins=Io,exports.uiRenderOrderPlugin=lo,exports.unregisterComponent=function(e){X().delete(e),G.delete(e)},exports.unregisterDrawCallback=fs,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([oe]);for(const n of s){const s=e.get(n,oe);s&&(s.aspectRatio=t,e.insert(n,oe,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Ao.warn(e,t,s)},exports.wrapSceneSystem=Ns,exports.wxFileExists=T,exports.wxFileExistsSync=function(e){const t=b();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=E,exports.wxLoadImagePixels=async function(e){return C(await E(e))},exports.wxReadFile=P,exports.wxReadTextFile=M,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{b().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 3252dfca0..dc49a802a 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function d(e,n){return t().instantiateWasm(e,n)}function 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}function p(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function g(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const y=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of y)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function M(e){for(const t of y)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return w.has(e.toLowerCase())}function T(){return w}function E(e){return"string"==typeof e&&(!!e.includes("/")&&P(x(e)))}function C(){const e=[];for(const t of y)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function k(e){const t=v(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(k(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 z(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function W(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function O(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 L(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 H(e){return L(await O(e))}let X=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return p(e,t)}async readFile(e){return z(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},Y=1920,N=1080,V=100,G=512,q={x:100,y:100},K="Arial",J=24,Q=1.2,Z=.5,ee=1/60,te={x:0,y:-9.81},ne=1/60,se="default",ie={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=ie.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=ie.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=ie.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=ie.canvasMatchWidthOrHeight)}const oe=0,ae=4294967295,le=4294967295,ce=0,de=(e=0,t=0)=>({x:e,y:t}),he=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ue=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),fe=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),pe=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ge(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ge);const t={};for(const n in e)t[n]=ge(e[n]);return t}let ye=0;function me(e,t){const n=++ye,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?{...ge(t),...e}:ge(t):e?{...t,...e}:{...t}}}const _e=new Map;function we(){return"undefined"==typeof window?_e:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function xe(e,t){const n=Ee.get(e)??we().get(e);if(n)return n;const s=me(e,t);return we().set(e,s),Ee.set(e,s),Pe(e,t,!1),s}function ve(e){const t=Ee.get(e)??we().get(e);if(t)return t;const n=me(e,{});return we().set(e,n),Ee.set(e,n),Pe(e,{},!0),n}function be(e){return we().get(e)}function Se(){const e=we();for(const t of e.keys())Ee.delete(t);e.clear()}function Me(e){we().delete(e),Ee.delete(e)}function Pe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Te(e){return!0===e._builtin}const Ee=new Map;function Ce(e,t){Ee.set(e,t)}function Re(e){return Ee.get(e)??be(e)}function Ae(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ee.set(e,n),n}const ke={Perspective:0,Orthographic:1},Ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Be=Ae("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}}),ze=Be,Ue=Be,$e=Ae("Sprite",{texture:ae,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}),We=Ae("Camera",{projectionType:ke.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}),De=Ae("Canvas",{designResolution:{x:Y,y:N},pixelsPerUnit:100,scaleMode:Fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Oe=Ae("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Le=Ae("Parent",{entity:0}),He=Ae("Children",{entities:[]}),Xe=Ae("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:le,enabled:!0}),je=Ae("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=xe("Name",{value:""}),Ne=xe("SceneOwner",{scene:"",persistent:!1});function Ve(e){const t=Re(e);return t?ge(t._default):null}const Ge=Ae("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),qe=Ae("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ke=Ae("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Je=Ae("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Qe={Static:0,Kinematic:1,Dynamic:2};let Ze=0;function et(e,t){const n=++Ze;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function tt(e){return{_type:"res",_resource:e}}function nt(e){return{_type:"res_mut",_resource:e}}class st{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 it{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 st(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const rt=et({delta:0,elapsed:0,frameCount:0},"Time");function ot(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=at(t[e]),r=at(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function at(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function lt(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 ct=null;function dt(e){ct=e}function ht(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ct&&ct(e,t)}function ut(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 ft=1;const pt=new WeakMap;function gt(e){let t=pt.get(e);return void 0===t&&(t=ft++,pt.set(e,t)),t}const yt=[];function mt(e,t=[],n=[]){yt.length=0;for(const t of e)yt.push(gt(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(gt(e));yt.sort((e,t)=>e-t),s+="|+"+yt.join(",")}if(n.length>0){yt.length=0;for(const e of n)yt.push(gt(e));yt.sort((e,t)=>e-t),s+="|-"+yt.join(",")}return s}class _t{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.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 ht(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_;return this.entities_.set(e,t),this.worldVersion_++,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){ht(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)}}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){ht(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ht(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Te(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(Te(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,ut(n))}catch(n){ht(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 Te(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Te(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Te(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ht(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.");Te(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ot(t._name,t._default,s);if(e.length>0)throw new Error(lt(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,ut(i))}catch(n){ht(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return ht(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 ht(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ht(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=ot(t._name,t._default,e);if(i.length>0)throw new Error(lt(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Ee)if(Te(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=we();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),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!Te(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function wt(e){return{_type:"mut",_component:e}}function xt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function vt(e){return{_filterType:"added",_component:e}}function bt(e){return{_filterType:"changed",_component:e}}function St(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Pt(e){return xt(e)||St(e)||Mt(e)?e._component:e}function Tt(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{xt(e)&&s.push(t),St(e)?i.push({index:t,component:e._component}):Mt(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Tt(e,[...t,...s],n),without:(...s)=>Tt(e,t,[...n,...s])}}function Et(...e){return Tt(e)}class Ct{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Pt),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,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Rt(e){return{_type:"removed",_component:e}}class At{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 kt(){return{_type:"commands"}}class It{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=Te(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 Ft{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new It(this,null);return this.spawned_.push(e),e}entity(e){return new It(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Bt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class zt{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 zt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new zt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function $t(e){return{_type:"event_writer",_event:e}}function Wt(e){return{_type:"event_reader",_event:e}}class Dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ot{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Lt;!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"}(Lt||(Lt={}));let Ht=0;function Xt(e,t,n){const s=++Ht;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function jt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Yt(e){jt().push({schedule:Lt.Update,system:e})}function Nt(e){jt().push({schedule:Lt.Startup,system:e})}function Vt(e,t){jt().push({schedule:e,system:t})}class Gt{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 Ft&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ct(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 Ft(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ot(n)}case"removed":{const t=e;return new At(this.world_,t._component,this.currentLastRunTick_)}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 Kt=et(new qt,"Input");class Jt{constructor(e){this.target_=e??null}build(e){const n=new qt;e.insertResource(Kt,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(Lt.Last,Xt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Qt=new Jt,Zt=et({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 en;function tn(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"}(en||(en={}));let nn=null,sn=null,rn=1;const on=new Map;function an(e){nn=e,sn=e.getResourceManager(),mn()}function ln(){0!==un&&nn&&(nn._free(un),un=0),on.clear(),rn=1,hn=!1,pn.clear(),gn=null,sn=null,nn=null}function cn(){if(!sn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return sn}const dn={createShader:(e,t)=>cn().createShader(e,t),releaseShader(e){e>0&&cn().releaseShader(e)},create(e){const t=rn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??en.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 on.set(t,n),t},get:e=>on.get(e),setUniform(e,t,n){const s=on.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,nn?.invalidateMaterialCache(e))},getUniform(e,t){const n=on.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=on.get(e);n&&(n.blendMode=t,nn?.invalidateMaterialCache(e))},getBlendMode(e){const t=on.get(e);return t?.blendMode??en.Normal},setDepthTest(e,t){const n=on.get(e);n&&(n.depthTest=t,nn?.invalidateMaterialCache(e))},getShader(e){const t=on.get(e);return t?.shader??0},release(e){on.delete(e),nn?.invalidateMaterialCache(e)},isValid:e=>on.has(e),releaseAll(){on.clear(),nn?.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??en.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=on.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=rn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return on.set(n,s),n},toAssetData(e,t){const n=on.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=on.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let hn=!1,un=0;const fn=16384,pn=new Map;let gn=null;function yn(e){const t=(0===un&&nn&&(un=nn._malloc(fn)),un);if(0===t||!nn)return{ptr:0,count:0};let n=0,s=0;const i=nn.HEAPU8,r=nn.HEAPU32,o=nn.HEAPF32;for(const[a,l]of e){if(tn(l))continue;let e=pn.get(a);e||(gn||(gn=new TextEncoder),e=gn.encode(a),pn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>fn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${fn} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function mn(){if(!nn||hn)return;nn.materialDataProvider=(e,t,n,s,i)=>{const r=on.get(e);if(!r)return nn.HEAPU32[t>>2]=0,nn.HEAPU32[n>>2]=0,nn.HEAPU32[s>>2]=0,void(nn.HEAPU32[i>>2]=0);nn.HEAPU32[t>>2]=r.shader,nn.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=yn(r.uniforms);nn.HEAPU32[s>>2]=o,nn.HEAPU32[i>>2]=a},hn=!0}const _n={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 wn{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class xn{constructor(e,t=""){this.cache_=new wn,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&&(dn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())dn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:dn.createFromAsset(s,r),shaderHandle:r,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const vn=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"}]}]]);function bn(e,t){vn.set(e,t)}function Sn(e){const t=vn.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 Mn(e){return vn.get(e)?.fields??[]}function Pn(e){return vn.get(e)?.spine??null}const Tn=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function En(e,t){Tn.set(e,t)}function Cn(e){return Tn.get(e)}function Rn(e,t){const n=Tn.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function An(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Ye,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Rn(i,n),Bn(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 kn(e,t){return An(e,t)}async function In(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl,r=new Map;s&&await async function(e,t,n,s,i){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of Fn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=vn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...Fn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=vn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=l.get(e.type)?.get(t)??0)}}}(t,s,i,r,n?.collectAssets);const o=An(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const Fn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}]]);function Bn(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=Re(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([We]);for(const s of n){const n=e.get(s,We);n&&(n.aspectRatio=t,e.insert(s,We,n))}}function Un(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);if(n&&n.value===t)return s}return null}class $n{constructor(e){this.textureCache_=new wn,this.shaderCache_=new wn,this.jsonCache_=new wn,this.textCache_=new wn,this.binaryCache_=new wn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new wn,this.prefabCache_=new wn,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.module_=e,this.canvas_=h(ie.textCanvasSize,ie.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 xn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),dn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===v(e)?.contentType,h=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,r,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=v(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return In(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 n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const i=s??n;return new Promise((n,s)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(r)},r.onerror=()=>s(new Error(`Failed to load image: ${e}`)),r.src=i})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(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 dn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return dn.createShader(i,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Wn=et(null,"Assets");class Dn{build(e){const t=e.wasmModule;t?e.insertResource(Wn,new $n(t)):console.warn("AssetPlugin: No WASM module available")}}const On=new Dn;class Ln{constructor(){this.textureRefs_=new Map,this.fontRefs_=new Map,this.materialRefs_=new Map}addTextureRef(e,t){let n=this.textureRefs_.get(e);n||(n=new Set,this.textureRefs_.set(e,n)),n.add(t)}removeTextureRef(e,t){const n=this.textureRefs_.get(e);n&&(n.delete(t),0===n.size&&this.textureRefs_.delete(e))}getTextureRefCount(e){return this.textureRefs_.get(e)?.size??0}getTextureRefs(e){return Array.from(this.textureRefs_.get(e)??[])}addFontRef(e,t){let n=this.fontRefs_.get(e);n||(n=new Set,this.fontRefs_.set(e,n)),n.add(t)}removeFontRef(e,t){const n=this.fontRefs_.get(e);n&&(n.delete(t),0===n.size&&this.fontRefs_.delete(e))}getFontRefCount(e){return this.fontRefs_.get(e)?.size??0}getFontRefs(e){return Array.from(this.fontRefs_.get(e)??[])}addMaterialRef(e,t){let n=this.materialRefs_.get(e);n||(n=new Set,this.materialRefs_.set(e,n)),n.add(t)}removeMaterialRef(e,t){const n=this.materialRefs_.get(e);n&&(n.delete(t),0===n.size&&this.materialRefs_.delete(e))}getMaterialRefCount(e){return this.materialRefs_.get(e)?.size??0}getMaterialRefs(e){return Array.from(this.materialRefs_.get(e)??[])}getAllTextureRefs(){const e=[];for(const[t,n]of this.textureRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllFontRefs(){const e=[];for(const[t,n]of this.fontRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}getAllMaterialRefs(){const e=[];for(const[t,n]of this.materialRefs_.entries())e.push({assetPath:t,refCount:n.size,entities:Array.from(n)});return e}removeAllRefsForEntity(e){for(const t of this.textureRefs_.values())t.delete(e);for(const t of this.fontRefs_.values())t.delete(e);for(const t of this.materialRefs_.values())t.delete(e);for(const[e,t]of this.textureRefs_.entries())0===t.size&&this.textureRefs_.delete(e);for(const[e,t]of this.fontRefs_.entries())0===t.size&&this.fontRefs_.delete(e);for(const[e,t]of this.materialRefs_.entries())0===t.size&&this.materialRefs_.delete(e)}clear(){this.textureRefs_.clear(),this.fontRefs_.clear(),this.materialRefs_.clear()}getTotalRefCount(){return{textures:this.textureRefs_.size,fonts:this.fontRefs_.size,materials:this.materialRefs_.size}}}function Hn(e,t){const n=e.getResource(Wn);n&&n.registerEmbeddedAssets(t)}async function Xn(e,t,n){const{entities:s,rootId:i}=await Yn(t,n?.overrides??[],n,void 0,new Set),r={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await In(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const jn=10;async function Yn(e,t,n,s,i,r=0){if(r>jn)throw new Error(`Prefab nesting depth exceeded ${jn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Yn(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Nn(h.components,o),Vn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Nn(e,t){for(const n of e){const e=Cn(n.type);if(e)for(const s of e){const e=n.data[s];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(n.data[s]=i)}}}}function 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 Gn{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 Xn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const qn=et(null,"Prefabs");class Kn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Wn]}build(e){const t=e.getResource(Wn);e.insertResource(qn,new Gn(e.world,t))}}const Jn=new Kn;let Qn=null,Zn=0,es=0,ts=0;const ns=new Float32Array(256);function ss(e){Qn=e,Zn=Qn._malloc(64),es=Qn._malloc(64),ts=Qn._malloc(1024)}function is(){Qn&&(Zn&&(Qn._free(Zn),Zn=0),es&&(Qn._free(es),es=0),ts&&(Qn._free(ts),ts=0)),Qn=null}function rs(){if(!Qn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Qn}const os={r:1,g:1,b:1,a:1},as={begin(e){const t=rs();try{t.HEAPF32.set(e,Zn/4),t.draw_begin(Zn)}catch(e){ht(e,"Draw.begin")}},end(){try{rs().draw_end()}catch(e){ht(e,"Draw.end")}},line(e,t,n,s=1){try{rs().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.line")}},rect(e,t,n,s=!0){try{rs().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{rs().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{rs().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{rs().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circleOutline")}},texture(e,t,n,s=os){try{rs().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ht(e,"Draw.texture")}},textureRotated(e,t,n,s,i=os){try{rs().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ht(e,"Draw.textureRotated")}},setLayer(e){rs().draw_setLayer(e)},setDepth(e){rs().draw_setDepth(e)},getDrawCallCount:()=>Qn?Qn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Qn?Qn.draw_getPrimitiveCount():0,setBlendMode(e){rs().draw_setBlendMode(e)},setDepthTest(e){rs().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=rs();s.HEAPF32.set(n,es/4),s.draw_mesh(e,t,es)}catch(n){ht(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=rs(),i=dn.get(t);if(!i)return;if(as.setBlendMode(i.blendMode),as.setDepthTest(i.depthTest),0===i.uniforms.size)return void as.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,es/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=ds(t);if(!(s<0)){if(tn(n))ns[r++]=10,ns[r++]=s,ns[r++]=n.slot??e++,ns[r++]=n.textureId;else if("number"==typeof n)ns[r++]=1,ns[r++]=s,ns[r++]=n;else if(Array.isArray(n)){ns[r++]=n.length,ns[r++]=s;for(let e=0;e<n.length;e++)ns[r++]=n[e]}else"w"in n?(ns[r++]=4,ns[r++]=s,ns[r++]=n.x,ns[r++]=n.y,ns[r++]=n.z,ns[r++]=n.w):"z"in n?(ns[r++]=3,ns[r++]=s,ns[r++]=n.x,ns[r++]=n.y,ns[r++]=n.z):(ns[r++]=2,ns[r++]=s,ns[r++]=n.x,ns[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(ns.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,es);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),ts/4),s.draw_meshWithUniforms(e,i.shader,es,ts,r)}catch(n){ht(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ls={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},cs=new Set;function ds(e){const t=ls[e];return void 0!==t?t:(cs.has(e)||(cs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ls).join(", ")}`)),-1)}const hs=new Map;function us(e,t,n){hs.set(e,{fn:t,scene:n??""})}function fs(e){hs.delete(e)}function ps(){hs.clear()}var gs;!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"}(gs||(gs={}));let ys=null,ms=0,_s=0,ws=0;function xs(e){ys=e,ms=ys._malloc(262144),_s=ys._malloc(65536),ws=ys._malloc(256)}function vs(){ys&&(ms&&ys._free(ms),_s&&ys._free(_s),ws&&ys._free(ws),ms=0,_s=0,ws=0),ys=null}function bs(){if(!ys)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ys}const Ss={create(e){const t=bs(),n=t.geometry_create();if(0===n)throw new Error("Failed to create geometry");const s=e.vertices.length;if(4*s>262144)throw new Error(`Vertex data too large: ${s} floats (max 65536)`);t.HEAPF32.set(e.vertices,ms/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ws,i).set(r),t.geometry_init(n,ms,s,ws,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=bs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ms/4),s.geometry_updateVertices(e,ms,i,n)},release(e){e>0&&bs().geometry_release(e)},isValid:e=>!(!ys||e<=0)&&ys.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return Ss.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:gs.Float2},{name:"a_texCoord",type:gs.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ss.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:gs.Float2},{name:"a_texCoord",type:gs.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Ss.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:gs.Float2},{name:"a_texCoord",type:gs.Float2}],indices:new Uint16Array(o)})}};let Ms=null;function Ps(e){Ms=e}function Ts(){Ms&&Cs.isInitialized()&&Cs.shutdown(),Ms=null}function Es(){if(!Ms)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ms}const Cs={init(e,t){try{return Es().postprocess_init(e,t)}catch(n){return ht(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Es().postprocess_shutdown()}catch(e){ht(e,"PostProcess.shutdown")}},resize(e,t){try{Es().postprocess_resize(e,t)}catch(n){ht(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Es().postprocess_addPass(e,t)}catch(t){return ht(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Es().postprocess_removePass(e)}catch(t){ht(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Es().postprocess_setPassEnabled(e,t)}catch(t){ht(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Es().postprocess_isPassEnabled(e)}catch(t){return ht(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Es().postprocess_setUniformFloat(e,t,n)}catch(n){ht(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Es().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ht(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Es().postprocess_begin()}catch(e){ht(e,"PostProcess.begin")}},end(){try{Es().postprocess_end()}catch(e){ht(e,"PostProcess.end")}},getPassCount(){try{return Es().postprocess_getPassCount()}catch(e){return ht(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ms)return!1;try{return Ms.postprocess_isInitialized()}catch(e){return ht(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Es().postprocess_setBypass(e)}catch(e){ht(e,"PostProcess.setBypass")}},isBypassed(){if(!Ms)return!0;try{return Ms.postprocess_isBypassed()}catch(e){return ht(e,"PostProcess.isBypassed"),!0}},createBlur:()=>dn.createShader(Rs,"#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:()=>dn.createShader(Rs,"#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:()=>dn.createShader(Rs,"#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:()=>dn.createShader(Rs,"#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")},Rs="#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 As;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(As||(As={}));let ks=null,Is=0;function Fs(e){ks=e,Is=ks._malloc(64)}function Bs(){ks&&Is&&(ks._free(Is),Is=0),ks=null}const zs={init(e,t){ks?.renderer_init(e,t)},resize(e,t){ks?.renderer_resize(e,t)},begin(e,t){if(ks&&Is)try{ks.HEAPF32.set(e,Is/4),ks.renderer_begin(Is,t??0)}catch(e){ht(e,"Renderer.begin")}},flush(){try{ks?.renderer_flush()}catch(e){ht(e,"Renderer.flush")}},end(){try{ks?.renderer_end()}catch(e){ht(e,"Renderer.end")}},submitSprites(e){if(ks)try{ks.renderer_submitSprites(e._cpp)}catch(e){ht(e,"Renderer.submitSprites")}},submitBitmapText(e){if(ks)try{ks.renderer_submitBitmapText(e._cpp)}catch(e){ht(e,"Renderer.submitBitmapText")}},submitSpine(e){if(ks)try{ks.renderer_submitSpine?.(e._cpp)}catch(e){ht(e,"Renderer.submitSpine")}},setStage(e){ks?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ks?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ks?.renderer_releaseTarget(e)},getTargetTexture:e=>ks?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ks?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){ks?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){ks?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){ks?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){ks?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>ks?ks.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>ks?{drawCalls:ks.renderer_getDrawCalls(),triangles:ks.renderer_getTriangles(),sprites:ks.renderer_getSprites(),text:ks.renderer_getText(),spine:ks.renderer_getSpine?.()??0,meshes:ks.renderer_getMeshes(),culled:ks.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Us=null;function $s(e){Us=e}function Ws(){Us=null}const Ds={enable(){Us?.gl_enableErrorCheck(!0)},disable(){Us?.gl_enableErrorCheck(!1)},check:e=>Us?.gl_checkErrors(e)??0,diagnose(){Us?.renderer_diagnose()}};class Os{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(zs.resize(s,i),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.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,r):zs.submitSpine(t),zs.flush(),this.executeDrawCallbacks(n,r),zs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=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,r):zs.submitSpine(t),zs.flush(),this.executeDrawCallbacks(n,r),zs.end()}executeDrawCallbacks(e,t){const n=hs;if(n.size>0){as.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)}as.end();for(const e of s)fs(e)}}}const Ls="__scene_transition_overlay__";class Hs{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 Xs{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,Ne,{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),us(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Cs.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,Ne)){const n=this.app_.world.get(e,Ne);n.persistent=t,this.app_.world.insert(e,Ne,n)}}}class js{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??ie.sceneTransitionDuration,i=t.color??{...ie.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},us(Ls,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),n="fade-out"===this.transition_.phase?t:1-t;as.setLayer(9999),as.setDepth(9999),as.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,fs(Ls),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,fs(Ls),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const n=new Hs(t);this.scenes_.set(e,n);const s=new Xs(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Wn)?this.app_.getResource(Wn):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 Hs(t);this.scenes_.set(e,n);const s=new Xs(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Wn)?this.app_.getResource(Wn):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,Ne)){if(this.app_.world.get(e,Ne).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())fs(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Cs.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Wn)&&(i.assetServer=this.app_.getResource(Wn));const r=await In(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,Ne,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Ns(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(Wn)?this.app_.getResource(Wn):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)dn.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,$e)){const t=n.get(e,$e);s.sprite=t.color.a,t.color.a=0,n.insert(e,$e,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,Xe)){const t=n.get(e,Xe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Xe,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,$e)){const t=n.get(e,$e);t.color.a=s.sprite,n.insert(e,$e,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,Xe)){const t=n.get(e,Xe);t.color.a=s.bitmapText,n.insert(e,Xe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Cs.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 Ys=et(null,"SceneManager");function Ns(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ys).getSceneStatus(t)&&n._fn(...s)}}}const Vs=Xt([nt(Ys),tt(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Gs={name:"SceneManager",build(e){const t=new js(e);e.insertResource(Ys,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ys),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Lt.Startup,n),e.addSystemToSchedule(Lt.Last,Vs)}};class qs{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new Ut,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Lt.Last);else{this.runSchedule(Lt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Lt.FixedPreUpdate),this.runSchedule(Lt.FixedUpdate),this.runSchedule(Lt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new _t,this.resources_=new it;for(const e of Object.values(Lt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new qs}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,n){return this.systems_.get(e).push({system:t,runBefore:n?.runBefore,runAfter:n?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(Lt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Lt.Startup,e)}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(Ys).register(e),this}setInitialScene(e){return this.getResource(Ys).setInitial(e),this}tick(e){this.runner_||(this.runner_=new Gt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(rt)||this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Lt.First),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Gt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,ps();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Ws,Bs,Ts,vs,ln,is];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(rt);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ks(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Js=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Qs(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case Fe.FixedWidth:return r;case Fe.FixedHeight:return o;case Fe.Expand:return Math.max(r,o);case Fe.Shrink:return Math.min(r,o);case Fe.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const Zs=[];function ei(e){if(e<Zs.length)return Zs[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 Zs.push(t),t}function ti(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,Ne);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===ke.Orthographic){if(h=i.orthoSize,l){h=Qs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=si(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=ri(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=ai(r.position.x,r.position.y,r.position.z),f=ei(c.length);f.entity=e,f.viewProjection.set(ci(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const ni=new Float32Array(16);function si(e,t,n,s,i,r){const o=ni;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const ii=new Float32Array(16);function ri(e,t,n,s){const i=ii;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const oi=new Float32Array(16);function ai(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 li=new Float32Array(16);function ci(e,t){const n=li;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 di={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function hi(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+o.x*m,originY:p+o.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const ui=Ae("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 fi=null,pi=null;function gi(e,t){e.has(t,$e)||e.insert(t,$e,{texture:ae,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 yi(e,t){switch(e){case di.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case di.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case di.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 mi(e,t){switch(e){case di.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case di.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case di.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 di.BottomToTop:case di.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function wi(e,t,n,s){if(!e.has(t,ui))return;const i=e.get(t,ui),r=yi(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,ui,i)}function xi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function vi(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function bi(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(vi(o.charCodeAt(0))&&s.length>0&&vi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!vi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Si(e){let t=1;for(;t<e;)t*=2;return t}function Mi(e,t){let n=0,s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;n++,s=t}return n}function Pi(e,t){if(fi&&pi){const e=fi.getUIRectComputedWidth(pi,t);if(e>0)return e}return e.size.x}function Ti(e,t){if(fi&&pi){const e=fi.getUIRectComputedHeight(pi,t);if(e>0)return e}return e.size.y}function Ei(e,t,n,s,i,r){if(!e.has(t,$e))return;const o=e.get(t,$e);let a,l;switch(n){case di.BottomToTop:case di.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,$e,o))}function Ci(e,t,n){let s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ri(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Ai(e,t,n,s,i){if(!e.has(t,ui))return;const r=e.get(t,ui),o=hi(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,Be,n)}}function ki(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,Fi=30,Bi={r:.3,g:.5,b:.8,a:1},zi={Left:0,Center:1,Right:2},Ui={Top:0,Middle:1,Bottom:2},$i={Visible:0,Clip:1,Ellipsis:2},Wi=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:zi.Left,verticalAlign:Ui.Top,wordWrap:!0,overflow:$i.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(ie.textCanvasSize,ie.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,Si(this.frameMaxW_)),e.height=Math.max(e.height,Si(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Si(this.frameMaxW_),e.height=Si(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=bi(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===$i.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Si(f)),s.height=Math.max(s.height,Si(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===$i.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 Ui.Top:x=d;break;case Ui.Middle:x=d+(p-2*d-w)/2;break;case Ui.Bottom:x=p-w-d;break;default:x=d}else x=d;let v=x;for(const t of l){let s;switch(e.align){case zi.Left:s=d;break;case zi.Center:s=f/2;break;case zi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===$i.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 Oi=ki({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?Pi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ti(e.uiRect,e.entity):0});class Li{build(e){Ce("Text",Wi);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(Lt.PreUpdate,Xt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Wi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Wi)){if(s.valid(e)&&s.has(e,$e)){const t=s.get(e,$e);s.insert(e,$e,{texture:ae,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([Wi]);for(const t of e){const e=s.get(t,Wi),r=s.has(t,ui)?s.get(t,ui):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Oi.changed(a,o)){if(s.has(t,$e)&&s.get(t,$e).texture!==ae)continue}gi(s,t);const l=r?{size:{x:Pi(r,t),y:Ti(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,$e);s.insert(t,$e,{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,Oi.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Hi=new Li,Xi=0,ji=1,Yi=Ae("UIMask",{enabled:!0,mode:Xi});function Ni(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function Vi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,M=r*d-o*c,P=h*y-u*g,T=h*m-f*g,E=h*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let k=w*A-x*R+v*C+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*R+d*C)*k,n[1]=(r*R-i*A-o*C)*k,n[2]=(y*M-m*S+_*b)*k,n[3]=(f*S-u*M-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(m*v-g*M-_*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*R-l*E+d*P)*k,n[9]=(i*E-s*R-o*P)*k,n[10]=(g*S-y*v+_*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*C-c*P)*k,n[13]=(s*C-i*T+r*P)*k,n[14]=(y*x-g*b-m*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function Gi(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function qi(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function Ki(e,t){return 2*Math.atan2(e,t)}function Ji(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function Qi(e,t,n,s,i,r,o,a,l,c){const d=Ki(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function Zi(e,t,n,s,i,r,o){if(!e.has(t,ui)||!e.has(t,Be))return null;const a=e.get(t,ui),l=e.get(t,Be),c=Pi(a,t)*l.worldScale.x,d=Ti(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),w=Ki(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-m*v,u+g*v+m*x],[h+y*x-m*v,u+y*v+m*x],[h+y*x-_*v,u+y*v+_*x],[h+g*x-_*v,u+g*v+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Ji(e,t,n,s,i,r,o);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 er(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Yi]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Yi);n.enabled&&(h.add(e),n.mode===ji?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;Ci(t,e,e=>{if(i.has(e)){if(t.get(e,Yi).mode===Xi)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,Yi).mode===Xi){const e=Zi(t,n,r,o,a,l,c);e&&(s=Ni(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Zi(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Ci(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class tr{build(e){if(Ce("UIMask",Yi),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(er(e.wasmModule,e.world))}}const nr=new tr,sr=Ae("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),ir=Ae("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),rr={Normal:0,Hovered:1,Pressed:2,Disabled:3},or=xe("Button",{state:rr.Normal,transition:null});class ar{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 lr=et(new ar,"UIEvents");class cr{build(e){Ce("UIRect",ui);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){fi=e,pi=t}(n,s);e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Zt)],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(Lt.PostUpdate,Xt([tt(Zt)],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(Lt.PostUpdate,Xt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const dr=new cr;let hr=!1,ur=!1;function fr(e){hr=e}function pr(){return hr}function gr(){return!hr}function yr(e){ur=e}function mr(){return ur}const _r=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 wr(e,t,n,s){t.emit(n,s,n),Ci(e,n,i=>{if(!e.has(i,sr))return!1;const r=e.get(i,sr);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class xr{build(e){Ce("Interactable",sr),Ce("Button",or);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new ar;e.insertResource(lr,i);let r=null,o=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt)],(e,a)=>{if(i.drain(),pr()&&!mr())return;const l=t.getEntitiesWithComponents([ir]);for(const e of l){const n=t.get(e,ir);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,ir,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;_r.update(a.viewProjection);const u=Gi(d,h,_r.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const m=n.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,ir)){const e=t.get(r,ir);e.hovered=!1,t.insert(r,ir,e),i.emit(r,"hover_exit")}if(null!==_){Ri(t,_,ir);const e=t.get(_,ir);e.hovered=!0,t.insert(_,ir,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,ir);e.pressed=!0,e.justPressed=!0,t.insert(_,ir,e),o=_,wr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,ir)){const e=t.get(o,ir);e.pressed=!1,e.justReleased=!0,t.insert(o,ir,e),wr(t,i,o,"release"),o===r&&wr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Lt.Update,Xt([],()=>{const e=t.getEntitiesWithComponents([or]);for(const n of e){if(Ri(t,n,sr,{enabled:!0}),!t.has(n,ir))continue;const e=t.get(n,ir),s=t.get(n,or),i=t.get(n,sr),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=rr.Pressed:e.hovered?s.state=rr.Hovered:s.state=rr.Normal:s.state=rr.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,$e)){const r=t.get(n,$e);r.color=xi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,$e,r)}}},{name:"ButtonSystem"}))}}const vr=new xr,br=xe("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}),Sr=xe("Focusable",{tabIndex:0,isFocused:!1});class Mr{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 Pr=et(new Mr,"FocusManager");class Tr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ce("TextInput",br),pr()&&!mr())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(ie.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function g(){const t=e.getResource(Pr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,br)?s:null}const y=()=>{l||null===g()||v()},m=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,br);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(lr).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,br);s.focused=!1,s.dirty=!0;e.getResource(Pr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,br);if(s.readOnly)return;let i=p.value;if(s.maxLength>0&&i.length>s.maxLength&&(i=i.substring(0,s.maxLength),p.value=i),i!==s.value){s.value=i;e.getResource(lr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=n.get(t,br);e.focused=!1,e.dirty=!0}e.getResource(Pr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let M=null;function P(e,l,d,h){(i.width<d||i.height<h)&&(i.width=Si(Math.max(i.width,d)),i.height=Si(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=bi(r,p,d-2*m);let t=m;for(const n of e)r.fillText(n,m,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,m,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=bi(r,l.value,d-2*m);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=m+r.measureText(c).width,n=m+o*y,s=y}else t=m+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,d,h),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,$e);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,$e,S)}e.addSystemToSchedule(Lt.Update,Xt([tt(Pr)],e=>{const t=n.getEntitiesWithComponents([br]);for(const e of t)Ri(n,e,Sr,{tabIndex:0,isFocused:!1}),Ri(n,e,sr,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,br)){const e=n.get(M,br);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,br);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(s),M=s}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Lt.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 r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,br).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,br)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([br,ui]);for(const e of a){const t=n.get(e,br);if(!t.dirty)continue;const s=n.get(e,ui),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(gi(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Er=new Tr,Cr={Simple:0,Sliced:1,Tiled:2,Filled:3},Rr={Horizontal:0,Vertical:1},Ar={Left:0,Right:1,Bottom:2,Top:3},kr=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Cr.Simple,fillMethod:Rr.Horizontal,fillOrigin:Ar.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Ir=ki({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?Pi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ti(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Fr=new class{build(e){Ce("Image",kr);const t=e.world,n=new Map;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,kr)||n.delete(e);const e=t.getEntitiesWithComponents([kr]);for(const s of e){const e=t.get(s,kr),i=t.has(s,ui)?t.get(s,ui):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Ir.changed(o,r))continue;gi(t,s);const a=t.get(s,$e);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=Pi(i,s),a.size.y=Ti(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Cr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Rr.Horizontal?e.fillOrigin===Ar.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===Ar.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===Cr.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,$e,a),n.set(s,Ir.take(r))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Ir.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},Br=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),zr=xe("ToggleGroup",{allowSwitchOff:!1});const Ur=new class{build(e){Ce("Toggle",Br),Ce("ToggleGroup",zr);const t=e.world,n=new Set;e.addSystemToSchedule(Lt.Update,Xt([tt(lr)],e=>{const s=t.getEntitiesWithComponents([Br]);if(!pr()||mr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,Br);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,Br,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,Br);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Ri(t,n,sr,{enabled:!0}),!t.has(n,ir))continue;const s=t.get(n,ir),i=t.get(n,Br),o=t.get(n,sr);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,zr);if(i.isOn&&o){if(!t.get(s,zr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,Br,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,Br);i.isOn&&(i.isOn=!1,t.insert(s,Br,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=xi(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}}for(const e of s){const n=t.get(e,Br);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,$e)){const e=t.get(n.graphicEntity,$e);e.enabled=n.isOn,t.insert(n.graphicEntity,$e,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},$r=di,Wr=xe("ProgressBar",{value:0,fillEntity:0,direction:di.LeftToRight});function Dr(e,t,n,s){if(!e.has(t,ui))return;const i=e.get(t,ui),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=hi(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be),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,Be,n))}}class Or{build(e){Ce("ProgressBar",Wr);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{const e=t.getEntitiesWithComponents([Wr,ui]);for(const n of e){const e=t.get(n,Wr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,ui),i=Math.max(0,Math.min(1,e.value));wi(t,e.fillEntity,e.direction,i);const r=Pi(s,n),o=Ti(s,n);Dr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Lr=new Or,Hr=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Xr=xe("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 jr=new class{build(e){Ce("Draggable",Hr),Ce("DragState",Xr);const t=e.world,n=e.getResource(lr);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt)],(e,o)=>{if(pr()&&!mr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Hr,ir]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Hr).enabled)continue;if(t.get(s,ir).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const i=Mi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Xr)||t.insert(n,Xr);const e=t.get(n,Xr),r=t.get(n,Be);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Xr)){t.get(s,Xr).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(s,Hr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Xr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Xr))return void(r=null);const s=t.get(r,Xr),i=t.get(r,Hr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,Be)){const e=function(e,t,n,s){if(!e.has(t,Le))return{x:n,y:s};const i=e.get(t,Le).entity;if(!e.valid(i)||!e.has(i,Be))return{x:n,y:s};const r=e.get(i,Be),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Ki(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,Be);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,Be,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Yr=xe("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Nr(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 Vr(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const Gr=new class{build(e){Ce("ScrollView",Yr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(Kt),tt(Zt),tt(rt)],(e,i,r)=>{const o=pr()&&!mr(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Yr,ui]);for(const r of l){Ri(t,r,Yi,{enabled:!0,mode:Xi});const l=t.get(r,Yr),c=t.get(r,ui);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=Pi(c,r),u=Ti(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,He)){const e=t.get(l.contentEntity,He).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,Be))continue;const e=t.get(o,Be);let a=0,l=0,c=.5,d=.5;if(t.has(o,ui)){const e=t.get(o,ui);a=Pi(e,o)||e.size.x,l=Ti(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,$e)){const e=t.get(o,$e);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){Ri(t,r,sr,{enabled:!0,blockRaycast:!0});const n=t.has(r,ir)?t.get(r,ir):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=Nr(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=Nr(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Nr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Nr(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Vr(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)<Ii&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Ii?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Vr(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)<Ii&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Ii?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Be)){const e=t.get(l.contentEntity,Be),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,Be,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},qr=di,Kr=xe("Slider",{value:0,minValue:0,maxValue:1,direction:di.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Jr(e,t,n,s,i,r){const o=Pi(s,i)*n.worldScale.x,a=Ti(s,i)*n.worldScale.y,l=Ki(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case di.LeftToRight:return o>0?(f-g)/o:0;case di.RightToLeft:return o>0?1-(f-g)/o:0;case di.BottomToTop:return a>0?(p-y)/a:0;case di.TopToBottom:return a>0?1-(p-y)/a:0}}function Qr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case di.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case di.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case di.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case di.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Zr{build(e){Ce("Slider",Kr);const t=e.world;let n=null;e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Kt),tt(Zt),tt(lr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Kr,ui]);for(const o of r){const r=t.get(o,Kr),a=t.get(o,ui);if(!pr()||mr()){if(t.has(o,Be)){Ri(t,o,sr,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ri(t,r.handleEntity,sr,{enabled:!0,blockRaycast:!1});const l=t.get(o,Be),c=t.has(o,ir)?t.get(o,ir):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,ir)&&(d=t.get(r.handleEntity,ir).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Jr(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,Kr,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=Pi(a,o),h=Ti(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(wi(t,r.fillEntity,r.direction,c),Ai(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,ui)){const e=t.get(r.handleEntity,ui);Qr(e,r.direction,c),t.insert(r.handleEntity,ui,e),Ai(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const eo=new Zr;const to=new class{build(e){Ce("Focusable",Sr);const t=e.world,n=new Mr;e.insertResource(Pr,n),e.addSystemToSchedule(Lt.Update,Xt([tt(Kt),tt(lr)],(e,s)=>{if(pr()&&!mr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Sr]);for(const e of i){if(!t.has(e,ir))continue;t.get(e,ir).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,sr)){if(!t.get(n,sr).enabled)continue}const s=t.get(n,Sr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Sr)){t.get(i,Sr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Sr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},no=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function so(){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 io=new class{build(e){Ce("SafeArea",no);const t=e.world;let n=so(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=so(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=so(),s=!0});e.addSystemToSchedule(Lt.PreUpdate,Xt([tt(Zt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([no,ui]);for(const e of d){const s=t.get(e,no),i=t.get(e,ui),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,ui,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},ro=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let oo=null;function ao(e,t){if(!oo)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=oo.get(e);n?n.renderer=t:oo.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const lo=new class{build(e){Ce("ListView",ro);const t=e.world,n=new Map;oo=n,e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(Kt)],e=>{const s=pr()&&!mr();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([ro,ui]);for(const r of i){Ri(t,r,sr,{enabled:!0,blockRaycast:!0}),Ri(t,r,Yi,{enabled:!0,mode:Xi});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,ro),a=t.get(r,ui),l=Ti(a,r),c=Pi(a,r);if(!s){const n=t.has(r,ir)?t.get(r,ir):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ye,{value:`ListItem_${e}`}),t.insert(n,ui,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Be)){const s=t.get(n,Be);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Be,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},co=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const ho=new class{build(e){Ce("Dropdown",co);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Be))return;const n=t.get(e,Be);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Be,{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,$e)){const n=t.get(e,$e);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,$e,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,$e),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Fi;t.insert(i,ui,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Be,{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,$e,{texture:ae,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*Fi;t.insert(r,Ye,{value:`Option_${e}`}),t.insert(r,ui,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Fi},offsetMax:{x:0,y:0},size:{x:o,y:Fi},pivot:{x:.5,y:.5}}),t.insert(r,Be,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,$e,{texture:ae,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Fi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,sr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,Be,{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,Wi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:zi.Left,verticalAlign:Ui.Middle,wordWrap:!1,overflow:$i.Clip,lineHeight:1.2}),t.insert(c,ui,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Fi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Wi))return;const s=t.get(n,Wi);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Wi,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,sr)&&t.insert(e,sr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,$e))){const s=t.get(e,$e);t.insert(e,$e,{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,$e))continue;const i=n===e.highlightIndex?{...Bi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,$e,{texture:ae,color:i,size:{x:e.ddWidth,y:Fi},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,ir))continue;if(t.get(n,ir).hovered)return!0}return!1}e.addSystemToSchedule(Lt.Update,Xt([tt(Kt),tt(lr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=pr()&&!mr(),p=t.getEntitiesWithComponents([co]);for(const g of p){const p=t.get(g,co);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Ri(t,g,sr,{enabled:!0,blockRaycast:!0});const m=t.has(g,ir)?t.get(g,ir):null;if(m?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,ir))continue;if(t.get(n,ir).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,ir))continue;if(t.get(s,ir).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},uo=0,fo=0,po=2,go=xe("LayoutGroup",{direction:uo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:fo,reverseOrder:!1});const yo=new class{build(e){Ce("LayoutGroup",go);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,Xt([],()=>{const e=t.getEntitiesWithComponents([go,ui,He]);for(const n of e){const e=t.get(n,go),s=t.get(n,ui),i=t.get(n,He);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,ui)&&t.has(e,Be)&&r.push({entity:e,rect:t.get(e,ui)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Pi(s,n),a=Ti(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===uo;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Pi(s.rect,s.entity),f=Ti(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*o+d.left+u+p*i,m=e.childAlignment===fo?(1-c)*a-d.top-(1-g)*f:e.childAlignment===po?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===fo?-l*o+d.left+p*i:e.childAlignment===po?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,m=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const _=t.get(s.entity,Be);_.position.x=y,_.position.y=m,t.insert(s.entity,Be,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Ae("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Ae("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class mo{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Lt.PostUpdate,Xt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const _o=new mo;async function wo(e,t,n){const s=e.getResource(Ys);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function xo(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 vo=et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),bo=et(null,"PhysicsAPI");function So(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Mo(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Po{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(vo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=xo(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([De]);for(const n of t){const t=e.world.get(n,De);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(Lt.PostUpdate,Xt([tt(rt)],a=>{const l=o.getEntitiesWithComponents([Ge,Be]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,Ge),l=o.get(i,Be);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=So(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),To(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===Qe.Kinematic){const e=So(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,Be);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,Le)){const t=e.world.get(o,Le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Be)){const n=e.world.get(t.entity,Be),s=So(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=Mo(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,Be,d)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(vo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(bo,Eo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function To(e,t,n){const s=e.world;if(s.has(n,qe)){const e=s.get(n,qe);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,Ke)){const e=s.get(n,Ke);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,Je)){const e=s.get(n,Je);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 Eo{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(Eo.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 Co={nearest:0,linear:1},Ro={repeat:0,clamp:1,mirror:2};function Ao(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Co[s.filterMode??"linear"]??1,a=Ro[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function ko(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 Io(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Fo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Mn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=Ao(e,await n.loadPixels(r),!0,t)}catch{s[r]=0}}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let d={},h=null;if(i&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=Pn(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===v(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=ko(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=Ao(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...te},fixedTimestep:o?.fixedTimestep??ne,subStepCount:o?.subStepCount??4};new Po("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Mn(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=v(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=Ao(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Mn(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=dn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=dn.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Mn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,u,f);const p=kn(e.world,n);if(l&&e.hasResource(Ys))for(const t of p.values())e.world.insert(t,Ne,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=Pn(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=ee);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,je)?c.get(r,je):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,Be)){const e=Io(c.get(r,Be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,d,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,u),t._free(_),t._free(w),n._free(c),n._free(d),n._free(h),n._free(f)}u&&t._free(u)}})}(e,t,i,h,s)}if(a){const t=e.getResource(Wn);t&&t.setAddressableManifest(a)}}function Bo(e,t,n){return{name:e,async setup(){await Fo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class zo{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=Pn(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Mn(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=v(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Uo="__preview__";class $o{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(Ys);t.register({name:Uo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Uo),this.loadPromise_=t.load(Uo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new zo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Fo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,Uo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([We]);for(const s of n){if(e.get(s,We).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([De]);for(const i of s){const s=e.get(i,De);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Ys).getScene(Uo),r=i?i.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,Be,o);const a={isActive:!0,projectionType:ke.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Ie.ColorAndDepth};e.insert(r,We,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(Ys);await e.switchTo(Uo),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 Wo={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),Wo.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 Do;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Do||(Do={}));class Oo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Do[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Do.Debug:console.debug(t,n);break;case Do.Info:console.log(t,n);break;case Do.Warn:console.warn(t,n);break;case Do.Error:console.error(t,n)}}}class Lo{constructor(){this.handlers_=[],this.minLevel_=Do.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,n){this.log(Do.Debug,e,t,n)}info(e,t,n){this.log(Do.Info,e,t,n)}warn(e,t,n){this.log(Do.Warn,e,t,n)}error(e,t,n){this.log(Do.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 Ho=new Lo;function Xo(){return Ho}function jo(e){Ho.setMinLevel(e)}function Yo(e,t,n){Ho.debug(e,t,n)}function No(e,t,n){Ho.info(e,t,n)}function Vo(e,t,n){Ho.warn(e,t,n)}function Go(e,t,n){Ho.error(e,t,n)}const qo=[Hi,nr,dr,Fr,Lr,vr,jr,Gr,eo,Ur,Er,to,io,lo,ho,yo,_o];function Ko(e,t){return function(e,t){const n=qs.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ss(e),an(e),xs(e),Ps(e),Fs(e),$s(e);const i=new Os;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=ti(e,s,t,i));const o=n.getResource(Zt);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(Zt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;zs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(zs.resize(t,l),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,l),n.hasResource(Ys)){const e=n.getResource(Ys).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ti(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Js,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}zs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Lt.First,l),n.addSystemToSchedule(Lt.Last,c),n.addPlugin(On),n.addPlugin(Jn),n.addPlugin(Qt),n.addPlugin(Gs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:qo,...t})}X||(X=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await p(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return g(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{vt as Added,qs as App,Dn as AssetPlugin,Ln as AssetRefCounter,$n as AssetServer,Wn as Assets,wn as AsyncCache,Xe as BitmapText,en as BlendMode,Qe as BodyType,qe as BoxCollider,or as Button,rr as ButtonState,We as Camera,De as Canvas,Je as CapsuleCollider,bt as Changed,He as Children,Ke as CircleCollider,Ie as ClearFlags,kt as Commands,Ft as CommandsInstance,N as DEFAULT_DESIGN_HEIGHT,Y as DEFAULT_DESIGN_WIDTH,ee as DEFAULT_FALLBACK_DT,ne as DEFAULT_FIXED_TIMESTEP,K as DEFAULT_FONT_FAMILY,J as DEFAULT_FONT_SIZE,te as DEFAULT_GRAVITY,Q as DEFAULT_LINE_HEIGHT,Z as DEFAULT_MAX_DELTA_TIME,V as DEFAULT_PIXELS_PER_UNIT,se as DEFAULT_SPINE_SKIN,q as DEFAULT_SPRITE_SIZE,G as DEFAULT_TEXT_CANVAS_SIZE,gs as DataType,Xr as DragState,Hr as Draggable,as as Draw,co as Dropdown,It as EntityCommands,Wt as EventReader,Ot as EventReaderInstance,Ut as EventRegistry,$t as EventWriter,Dt as EventWriterInstance,di as FillDirection,Rr as FillMethod,Ar as FillOrigin,Pr as FocusManager,Mr as FocusManagerState,Sr as Focusable,Ds as GLDebug,Ss as Geometry,oe as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,kr as Image,Cr as ImageType,Kt as Input,Jt as InputPlugin,qt as InputState,sr as Interactable,ro as ListView,ze as LocalTransform,Do as LogLevel,Lo as Logger,dn as Material,xn as MaterialLoader,wt as Mut,Ye as Name,Le as Parent,Eo as Physics,vo as PhysicsEvents,Po as PhysicsPlugin,Cs as PostProcess,Gn as PrefabServer,qn as Prefabs,Kn as PrefabsPlugin,$o as PreviewPlugin,Wr as ProgressBar,$r as ProgressBarDirection,Or as ProgressBarPlugin,ke as ProjectionType,Et as Query,Ct as QueryInstance,Rt as Removed,At as RemovedQueryInstance,Os as RenderPipeline,As as RenderStage,Wo as RenderTexture,zs as Renderer,tt as Res,nt as ResMut,Ge as RigidBody,ie as RuntimeConfig,no as SafeArea,Fe as ScaleMode,Ys as SceneManager,js as SceneManagerState,Ne as SceneOwner,Lt as Schedule,Yr as ScrollView,_n as ShaderSources,Kr as Slider,qr as SliderDirection,Zr as SliderPlugin,je as SpineAnimation,$e as Sprite,Gt as SystemRunner,Wi as Text,zi as TextAlign,br as TextInput,Tr as TextInputPlugin,$i as TextOverflow,Li as TextPlugin,Di as TextRenderer,Ui as TextVerticalAlign,rt as Time,Br as Toggle,Be as Transform,Zt as UICameraInfo,ar as UIEventQueue,lr as UIEvents,ir as UIInteraction,xr as UIInteractionPlugin,cr as UILayoutPlugin,Yi as UIMask,tr as UIMaskPlugin,ui as UIRect,mo as UIRenderOrderPlugin,Oe as Velocity,zo as WebAssetProvider,_t as World,Ue as WorldTransform,Nt as addStartupSystem,Yt as addSystem,Vt as addSystemToSchedule,wi as applyDirectionalFill,re as applyRuntimeConfig,On as assetPlugin,ps as clearDrawCallbacks,Se as clearUserComponents,fe as color,yi as computeFillAnchors,_i as computeFillSize,mi as computeHandleAnchors,hi as computeUIRectLayout,er as createMaskProcessor,Bo as createRuntimeSceneConfig,Ko as createWebApp,Yo as debug,xe as defineComponent,Bt as defineEvent,et as defineResource,Xt as defineSystem,ve as defineTag,Go as error,Un as findEntityByName,Ks as flushPendingSystems,S as getAddressableType,M as getAddressableTypeByEditorType,T as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,Mn as getComponentAssetFieldDescriptors,Sn as getComponentAssetFields,Ve as getComponentDefaults,Cn as getComponentEntityFields,Pn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,Xo as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,No as info,ss as initDrawAPI,$s as initGLDebugAPI,xs as initGeometryAPI,an as initMaterialAPI,Ps as initPostProcessAPI,Fs as initRendererAPI,Qt as inputPlugin,Xn as instantiatePrefab,Ni as intersectRects,Vi as invertMatrix4,Te as isBuiltinComponent,k as isCustomExtension,pr as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,mr as isPlayMode,gr as isRuntime,tn as isTextureRef,i as isWeChat,r as isWeb,Bn as loadComponent,xo as loadPhysicsModule,Fo as loadRuntimeScene,kn as loadSceneData,In as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Qi as pointInOBB,qi as pointInWorldRect,Jn as prefabsPlugin,Lr as progressBarPlugin,pe as quat,Ce as registerComponent,bn as registerComponentAssetFields,En as registerComponentEntityFields,us as registerDrawCallback,Hn as registerEmbeddedAssets,mn as registerMaterialCallback,Rn as remapEntityFields,Gs as sceneManagerPlugin,Gi as screenToWorld,fr as setEditorMode,ao as setListViewRenderer,jo as setLogLevel,yr as setPlayMode,dt as setWasmErrorHandler,is as shutdownDrawAPI,Ws as shutdownGLDebugAPI,vs as shutdownGeometryAPI,ln as shutdownMaterialAPI,Ts as shutdownPostProcessAPI,Bs as shutdownRendererAPI,eo as sliderPlugin,Ei as syncFillSpriteSize,Er as textInputPlugin,Hi as textPlugin,wo as transitionTo,vr as uiInteractionPlugin,dr as uiLayoutPlugin,nr as uiMaskPlugin,qo as uiPlugins,_o as uiRenderOrderPlugin,Me as unregisterComponent,fs as unregisterDrawCallback,zn as updateCameraAspectRatio,de as vec2,he as vec3,ue as vec4,Vo as warn,Ns as wrapSceneSystem,$ as wxFileExists,W as wxFileExistsSync,L as wxGetImagePixels,O as wxLoadImage,H as wxLoadImagePixels,z as wxReadFile,U as wxReadTextFile,D as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function 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}function p(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function g(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const y=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,w=new Set;for(const e of y)for(const t of e.extensions)_.set(t,e),w.add(t);function x(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function v(e){return _.get(x(e))}function b(e){return v(e)?.editorType??"unknown"}function S(e){return v(e)?.addressableType??null}function M(e){for(const t of y)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return w.has(e.toLowerCase())}function T(){return w}function E(e){return"string"==typeof e&&(!!e.includes("/")&&P(x(e)))}function C(){const e=[];for(const t of y)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function R(){return C().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function k(e){const t=v(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function B(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(k(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 z(e){return new Promise((t,n)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(B(e,t.errMsg)))}})})}function U(e,t="utf-8"){return new Promise((n,s)=>{F().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(B(e,t.errMsg)))}})})}function $(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function W(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function D(e,t){return new Promise((n,s)=>{F().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function O(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 L(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 H(e){return L(await O(e))}let X=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return p(e,t)}async readFile(e){return z(e)}async readTextFile(e){return U(e)}async fileExists(e){return $(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return g(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)}),wx.onTouchEnd(t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)})}},Y=1920,N=1080,V=100,G=512,q={x:100,y:100},K="Arial",J=24,Q=1.2,Z=.5,ee=1/60,te={x:0,y:-9.81},ne=1/60,se="default",ie={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=ie.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=ie.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=ie.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=ie.canvasMatchWidthOrHeight)}const oe=0,ae=4294967295,le=4294967295,ce=0,de=(e=0,t=0)=>({x:e,y:t}),he=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ue=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),fe=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),pe=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function ge(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(ge);const t={};for(const n in e)t[n]=ge(e[n]);return t}let ye=0;function me(e,t){const n=++ye,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?{...ge(t),...e}:ge(t):e?{...t,...e}:{...t}}}const _e=new Map;function we(){return"undefined"==typeof window?_e:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function xe(e,t){const n=Ee.get(e)??we().get(e);if(n)return n;const s=me(e,t);return we().set(e,s),Ee.set(e,s),Pe(e,t,!1),s}function ve(e){const t=Ee.get(e)??we().get(e);if(t)return t;const n=me(e,{});return we().set(e,n),Ee.set(e,n),Pe(e,{},!0),n}function be(e){return we().get(e)}function Se(){const e=we();for(const t of e.keys())Ee.delete(t);e.clear()}function Me(e){we().delete(e),Ee.delete(e)}function Pe(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function Te(e){return!0===e._builtin}const Ee=new Map;function Ce(e,t){Ee.set(e,t)}function Re(e){return Ee.get(e)??be(e)}function Ae(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ee.set(e,n),n}const ke={Perspective:0,Orthographic:1},Ie={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Fe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},Be=Ae("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}}),ze=Be,Ue=Be,$e=Ae("Sprite",{texture:ae,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}),We=Ae("Camera",{projectionType:ke.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}),De=Ae("Canvas",{designResolution:{x:Y,y:N},pixelsPerUnit:100,scaleMode:Fe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Oe=Ae("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Le=Ae("Parent",{entity:0}),He=Ae("Children",{entities:[]}),Xe=Ae("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:le,enabled:!0}),je=Ae("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=xe("Name",{value:""}),Ne=xe("SceneOwner",{scene:"",persistent:!1});function Ve(e){const t=Re(e);return t?ge(t._default):null}const Ge=Ae("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),qe=Ae("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ke=Ae("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Je=Ae("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Qe={Static:0,Kinematic:1,Dynamic:2};let Ze=0;function et(e,t){const n=++Ze;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function tt(e){return{_type:"res",_resource:e}}function nt(e){return{_type:"res_mut",_resource:e}}class st{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 it{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 st(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const rt=et({delta:0,elapsed:0,frameCount:0},"Time");function ot(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=at(t[e]),r=at(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function at(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function lt(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 ct=null;function dt(e){ct=e}function ht(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ct&&ct(e,t)}function ut(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 ft=1;const pt=new WeakMap;function gt(e){let t=pt.get(e);return void 0===t&&(t=ft++,pt.set(e,t)),t}const yt=[];function mt(e,t=[],n=[]){yt.length=0;for(const t of e)yt.push(gt(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(gt(e));yt.sort((e,t)=>e-t),s+="|+"+yt.join(",")}if(n.length>0){yt.length=0;for(const e of n)yt.push(gt(e));yt.sort((e,t)=>e-t),s+="|-"+yt.join(",")}return s}class _t{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.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 ht(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_;return this.entities_.set(e,t),this.worldVersion_++,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){ht(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)}}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){ht(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ht(t,`removeParent(entity=${e})`)}}insert(e,t,n){return Te(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(Te(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,ut(n))}catch(n){ht(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 Te(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Te(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Te(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ht(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.");Te(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=ot(t._name,t._default,s);if(e.length>0)throw new Error(lt(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,ut(i))}catch(n){ht(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return ht(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 ht(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ht(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=ot(t._name,t._default,e);if(i.length>0)throw new Error(lt(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Ee)if(Te(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=we();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),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!Te(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function wt(e){return{_type:"mut",_component:e}}function xt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function vt(e){return{_filterType:"added",_component:e}}function bt(e){return{_filterType:"changed",_component:e}}function St(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Mt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Pt(e){return xt(e)||St(e)||Mt(e)?e._component:e}function Tt(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{xt(e)&&s.push(t),St(e)?i.push({index:t,component:e._component}):Mt(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Tt(e,[...t,...s],n),without:(...s)=>Tt(e,t,[...n,...s])}}function Et(...e){return Tt(e)}class Ct{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Pt),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,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Rt(e){return{_type:"removed",_component:e}}class At{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 kt(){return{_type:"commands"}}class It{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=Te(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 Ft{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new It(this,null);return this.spawned_.push(e),e}entity(e){return new It(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Bt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class zt{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 zt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new zt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function $t(e){return{_type:"event_writer",_event:e}}function Wt(e){return{_type:"event_reader",_event:e}}class Dt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class Ot{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Lt;function Ht(){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"}(Lt||(Lt={}));let Xt=0;function jt(e,t,n){const s=++Xt;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function Yt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Nt(e){Yt().push({schedule:Lt.Update,system:e})}function Vt(e){Yt().push({schedule:Lt.Startup,system:e})}function Gt(e,t){Yt().push({schedule:e,system:t})}class qt{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 Ft&&t[e].flush()}finally{this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Ct(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 Ft(this.world_,this.resources_);case"event_writer":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Dt(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new Ot(n)}case"removed":{const t=e;return new At(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Kt{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 Jt=et(new Kt,"Input");class Qt{constructor(e){this.target_=e??null}build(e){const n=new Kt;e.insertResource(Jt,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(Lt.Last,jt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Zt=new Qt,en=et({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 tn;function nn(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"}(tn||(tn={}));let sn=null,rn=null,on=1;const an=new Map;function ln(e){sn=e,rn=e.getResourceManager(),_n()}function cn(){0!==fn&&sn&&(sn._free(fn),fn=0),an.clear(),on=1,un=!1,gn.clear(),yn=null,rn=null,sn=null}function dn(){if(!rn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return rn}const hn={createShader:(e,t)=>dn().createShader(e,t),releaseShader(e){e>0&&dn().releaseShader(e)},create(e){const t=on++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??tn.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 an.set(t,n),t},get:e=>an.get(e),setUniform(e,t,n){const s=an.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,sn?.invalidateMaterialCache(e))},getUniform(e,t){const n=an.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=an.get(e);n&&(n.blendMode=t,sn?.invalidateMaterialCache(e))},getBlendMode(e){const t=an.get(e);return t?.blendMode??tn.Normal},setDepthTest(e,t){const n=an.get(e);n&&(n.depthTest=t,sn?.invalidateMaterialCache(e))},getShader(e){const t=an.get(e);return t?.shader??0},release(e){an.delete(e),sn?.invalidateMaterialCache(e)},isValid:e=>an.has(e),releaseAll(){an.clear(),sn?.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??tn.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=an.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=on++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return an.set(n,s),n},toAssetData(e,t){const n=an.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=an.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let un=!1,fn=0;const pn=16384,gn=new Map;let yn=null;function mn(e){const t=(0===fn&&sn&&(fn=sn._malloc(pn)),fn);if(0===t||!sn)return{ptr:0,count:0};let n=0,s=0;const i=sn.HEAPU8,r=sn.HEAPU32,o=sn.HEAPF32;for(const[a,l]of e){if(nn(l))continue;let e=gn.get(a);e||(yn||(yn=new TextEncoder),e=yn.encode(a),gn.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>pn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${pn} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function _n(){if(!sn||un)return;sn.materialDataProvider=(e,t,n,s,i)=>{const r=an.get(e);if(!r)return sn.HEAPU32[t>>2]=0,sn.HEAPU32[n>>2]=0,sn.HEAPU32[s>>2]=0,void(sn.HEAPU32[i>>2]=0);sn.HEAPU32[t>>2]=r.shader,sn.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=mn(r.uniforms);sn.HEAPU32[s>>2]=o,sn.HEAPU32[i>>2]=a},un=!0}const wn={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 xn{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class vn{constructor(e,t=""){this.cache_=new xn,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&&(hn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())hn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:hn.createFromAsset(s,r),shaderHandle:r,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}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"}]}]]);function Sn(e,t){bn.set(e,t)}function Mn(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 Pn(e){return bn.get(e)?.fields??[]}function Tn(e){return bn.get(e)?.spine??null}const En=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Cn(e,t){En.set(e,t)}function Rn(e){return En.get(e)}function An(e,t){const n=En.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function kn(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,Ye,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)An(i,n),zn(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 In(e,t){return kn(e,t)}async function Fn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl,r=new Map;s&&await async function(e,t,n,s,i){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of Bn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=bn.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...Bn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=bn.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=l.get(e.type)?.get(t)??0)}}}(t,s,i,r,n?.collectAssets);const o=kn(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const Bn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}]]);function zn(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=Re(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 Un(e,t){const n=e.getEntitiesWithComponents([We]);for(const s of n){const n=e.get(s,We);n&&(n.aspectRatio=t,e.insert(s,We,n))}}function $n(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);if(n&&n.value===t)return s}return null}class Wn{constructor(e){this.textureCache_=new xn,this.shaderCache_=new xn,this.jsonCache_=new xn,this.textCache_=new xn,this.binaryCache_=new xn,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new xn,this.prefabCache_=new xn,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.module_=e,this.canvas_=h(ie.textCanvasSize,ie.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 vn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),hn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===v(e)?.contentType,h=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,r,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=v(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Fn(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const i=s??n;return new Promise((n,s)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(r)},r.onerror=()=>s(new Error(`Failed to load image: ${e}`)),r.src=i})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(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 hn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return hn.createShader(i,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Dn=et(null,"Assets");class On{build(e){const t=e.wasmModule;t?e.insertResource(Dn,new Wn(t)):console.warn("AssetPlugin: No WASM module available")}}const Ln=new On;class Hn{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 Xn(e,t){const n=e.getResource(Dn);n&&n.registerEmbeddedAssets(t)}async function jn(e,t,n){const{entities:s,rootId:i}=await Nn(t,n?.overrides??[],n,void 0,new Set),r={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await Fn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const Yn=10;async function Nn(e,t,n,s,i,r=0){if(r>Yn)throw new Error(`Prefab nesting depth exceeded ${Yn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Nn(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Vn(h.components,o),Gn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Vn(e,t){for(const n of e){const e=Rn(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 Gn(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 jn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Kn=et(null,"Prefabs");class Jn{constructor(){this.name="PrefabsPlugin",this.dependencies=[Dn]}build(e){const t=e.getResource(Dn);e.insertResource(Kn,new qn(e.world,t))}}const Qn=new Jn;let Zn=null,es=0,ts=0,ns=0;const ss=new Float32Array(256);function is(e){Zn=e,es=Zn._malloc(64),ts=Zn._malloc(64),ns=Zn._malloc(1024)}function rs(){Zn&&(es&&(Zn._free(es),es=0),ts&&(Zn._free(ts),ts=0),ns&&(Zn._free(ns),ns=0)),Zn=null}function os(){if(!Zn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Zn}const as={r:1,g:1,b:1,a:1},ls={begin(e){const t=os();try{t.HEAPF32.set(e,es/4),t.draw_begin(es)}catch(e){ht(e,"Draw.begin")}},end(){try{os().draw_end()}catch(e){ht(e,"Draw.end")}},line(e,t,n,s=1){try{os().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.line")}},rect(e,t,n,s=!0){try{os().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{os().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ht(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{os().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{os().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ht(e,"Draw.circleOutline")}},texture(e,t,n,s=as){try{os().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ht(e,"Draw.texture")}},textureRotated(e,t,n,s,i=as){try{os().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ht(e,"Draw.textureRotated")}},setLayer(e){os().draw_setLayer(e)},setDepth(e){os().draw_setDepth(e)},getDrawCallCount:()=>Zn?Zn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Zn?Zn.draw_getPrimitiveCount():0,setBlendMode(e){os().draw_setBlendMode(e)},setDepthTest(e){os().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=os();s.HEAPF32.set(n,ts/4),s.draw_mesh(e,t,ts)}catch(n){ht(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=os(),i=hn.get(t);if(!i)return;if(ls.setBlendMode(i.blendMode),ls.setDepthTest(i.depthTest),0===i.uniforms.size)return void ls.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,ts/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=hs(t);if(!(s<0)){if(nn(n))ss[r++]=10,ss[r++]=s,ss[r++]=n.slot??e++,ss[r++]=n.textureId;else if("number"==typeof n)ss[r++]=1,ss[r++]=s,ss[r++]=n;else if(Array.isArray(n)){ss[r++]=n.length,ss[r++]=s;for(let e=0;e<n.length;e++)ss[r++]=n[e]}else"w"in n?(ss[r++]=4,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y,ss[r++]=n.z,ss[r++]=n.w):"z"in n?(ss[r++]=3,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y,ss[r++]=n.z):(ss[r++]=2,ss[r++]=s,ss[r++]=n.x,ss[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(ss.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,ts);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),ns/4),s.draw_meshWithUniforms(e,i.shader,ts,ns,r)}catch(n){ht(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},cs={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},ds=new Set;function hs(e){const t=cs[e];return void 0!==t?t:(ds.has(e)||(ds.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(cs).join(", ")}`)),-1)}const us=new Map;function fs(e,t,n){us.set(e,{fn:t,scene:n??""})}function ps(e){us.delete(e)}function gs(){us.clear()}var ys;!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"}(ys||(ys={}));let ms=null,_s=0,ws=0,xs=0;function vs(e){ms=e,_s=ms._malloc(262144),ws=ms._malloc(65536),xs=ms._malloc(256)}function bs(){ms&&(_s&&ms._free(_s),ws&&ms._free(ws),xs&&ms._free(xs),_s=0,ws=0,xs=0),ms=null}function Ss(){if(!ms)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ms}const Ms={create(e){const t=Ss(),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,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,xs,i).set(r),t.geometry_init(n,_s,s,xs,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,ws,s).set(e.indices),t.geometry_setIndices16(n,ws,s)}else{new Uint32Array(t.HEAPU8.buffer,ws,s).set(e.indices),t.geometry_setIndices32(n,ws,s)}}return n},updateVertices(e,t,n=0){const s=Ss(),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&&Ss().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 Ms.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:ys.Float2},{name:"a_texCoord",type:ys.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return Ms.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ys.Float2},{name:"a_texCoord",type:ys.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return Ms.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ys.Float2},{name:"a_texCoord",type:ys.Float2}],indices:new Uint16Array(o)})}};let Ps=null;function Ts(e){Ps=e}function Es(){Ps&&Rs.isInitialized()&&Rs.shutdown(),Ps=null}function Cs(){if(!Ps)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ps}const Rs={init(e,t){try{return Cs().postprocess_init(e,t)}catch(n){return ht(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Cs().postprocess_shutdown()}catch(e){ht(e,"PostProcess.shutdown")}},resize(e,t){try{Cs().postprocess_resize(e,t)}catch(n){ht(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Cs().postprocess_addPass(e,t)}catch(t){return ht(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Cs().postprocess_removePass(e)}catch(t){ht(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Cs().postprocess_setPassEnabled(e,t)}catch(t){ht(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Cs().postprocess_isPassEnabled(e)}catch(t){return ht(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{Cs().postprocess_setUniformFloat(e,t,n)}catch(n){ht(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{Cs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ht(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Cs().postprocess_begin()}catch(e){ht(e,"PostProcess.begin")}},end(){try{Cs().postprocess_end()}catch(e){ht(e,"PostProcess.end")}},getPassCount(){try{return Cs().postprocess_getPassCount()}catch(e){return ht(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Ps)return!1;try{return Ps.postprocess_isInitialized()}catch(e){return ht(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Cs().postprocess_setBypass(e)}catch(e){ht(e,"PostProcess.setBypass")}},isBypassed(){if(!Ps)return!0;try{return Ps.postprocess_isBypassed()}catch(e){return ht(e,"PostProcess.isBypassed"),!0}},createBlur:()=>hn.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>hn.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>hn.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>hn.createShader(As,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 offset = u_intensity / u_resolution;\n float r = texture(u_texture, v_texCoord + offset).r;\n float g = texture(u_texture, v_texCoord).g;\n float b = texture(u_texture, v_texCoord - offset).b;\n float a = texture(u_texture, v_texCoord).a;\n fragColor = vec4(r, g, b, a);\n}\n")},As="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ks;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ks||(ks={}));let Is=null,Fs=0;function Bs(e){Is=e,Fs=Is._malloc(64)}function zs(){Is&&Fs&&(Is._free(Fs),Fs=0),Is=null}const Us={init(e,t){Is?.renderer_init(e,t)},resize(e,t){Is?.renderer_resize(e,t)},begin(e,t){if(Is&&Fs)try{Is.HEAPF32.set(e,Fs/4),Is.renderer_begin(Fs,t??0)}catch(e){ht(e,"Renderer.begin")}},flush(){try{Is?.renderer_flush()}catch(e){ht(e,"Renderer.flush")}},end(){try{Is?.renderer_end()}catch(e){ht(e,"Renderer.end")}},submitSprites(e){if(Is)try{Is.renderer_submitSprites(e._cpp)}catch(e){ht(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Is)try{Is.renderer_submitBitmapText(e._cpp)}catch(e){ht(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Is)try{Is.renderer_submitSpine?.(e._cpp)}catch(e){ht(e,"Renderer.submitSpine")}},setStage(e){Is?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Is?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Is?.renderer_releaseTarget(e)},getTargetTexture:e=>Is?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Is?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Is?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Is?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Is?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Is?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Is?Is.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Is?{drawCalls:Is.renderer_getDrawCalls(),triangles:Is.renderer_getTriangles(),sprites:Is.renderer_getSprites(),text:Is.renderer_getText(),spine:Is.renderer_getSpine?.()??0,meshes:Is.renderer_getMeshes(),culled:Is.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $s=null;function Ws(e){$s=e}function Ds(){$s=null}const Os={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.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:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(Us.resize(s,i),Rs.isInitialized()&&Rs.getPassCount()>0&&Rs.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),Us.setViewport(0,0,s,i),Us.clearBuffers(3),Us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),Us.submitSprites(t),Us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Us.submitSpine(t),Us.flush(),this.executeDrawCallbacks(n,r),Us.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;Us.setViewport(s.x,s.y,s.w,s.h),Us.setScissor(s.x,s.y,s.w,s.h,!0),Us.clearBuffers(i),Us.setScissor(0,0,0,0,!1),Us.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),Us.submitSprites(t),Us.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):Us.submitSpine(t),Us.flush(),this.executeDrawCallbacks(n,r),Us.end()}executeDrawCallbacks(e,t){const n=us;if(n.size>0){ls.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)}ls.end();for(const e of s)ps(e)}}}const Hs="__scene_transition_overlay__";class Xs{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 js{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,Ne,{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),fs(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=Rs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){Rs.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,Ne)){const n=this.app_.world.get(e,Ne);n.persistent=t,this.app_.world.insert(e,Ne,n)}}}class Ys{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??ie.sceneTransitionDuration,i=t.color??{...ie.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},fs(Hs,()=>{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;ls.setLayer(9999),ls.setDepth(9999),ls.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,ps(Hs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ps(Hs),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 Xs(t);this.scenes_.set(e,n);const s=new js(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Dn)?this.app_.getResource(Dn):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 Xs(t);this.scenes_.set(e,n);const s=new js(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Dn)?this.app_.getResource(Dn):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,Ne)){if(this.app_.world.get(e,Ne).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ps(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{Rs.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Dn)&&(i.assetServer=this.app_.getResource(Dn));const r=await Fn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,Ne,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Vs(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(Dn)?this.app_.getResource(Dn):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)hn.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,$e)){const t=n.get(e,$e);s.sprite=t.color.a,t.color.a=0,n.insert(e,$e,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,Xe)){const t=n.get(e,Xe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Xe,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,$e)){const t=n.get(e,$e);t.color.a=s.sprite,n.insert(e,$e,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,Xe)){const t=n.get(e,Xe);t.color.a=s.bitmapText,n.insert(e,Xe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{Rs.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 Ns=et(null,"SceneManager");function Vs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Ns).getSceneStatus(t)&&n._fn(...s)}}}const Gs=jt([nt(Ns),tt(rt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),qs={name:"SceneManager",build(e){const t=new Ys(e);e.insertResource(Ns,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ns),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Lt.Startup,n),e.addSystemToSchedule(Lt.Last,Gs)}};class Ks{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.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(Lt.Last);else{this.runSchedule(Lt.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Lt.FixedPreUpdate),this.runSchedule(Lt.FixedUpdate),this.runSchedule(Lt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new _t,this.resources_=new it;for(const e of Object.values(Lt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Ks}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(Lt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Lt.Startup,e)}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(Ns).register(e),this}setInitialScene(e){return this.getResource(Ns).setInitial(e),this}tick(e){this.runner_||(this.runner_=new qt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(rt)||this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Lt.First),this.runSchedule(Lt.PreUpdate),this.runSchedule(Lt.Update),this.runSchedule(Lt.PostUpdate),this.runSchedule(Lt.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new qt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(rt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Lt.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,gs();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=[Ds,zs,Es,bs,cn,rs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(rt);t.delta=e,t.elapsed+=e,t.frameCount++}}function Js(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Zs(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case Fe.FixedWidth:return r;case Fe.FixedHeight:return o;case Fe.Expand:return Math.max(r,o);case Fe.Shrink:return Math.min(r,o);case Fe.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const ei=[];function ti(e){if(e<ei.length)return ei[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 ei.push(t),t}function ni(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,Ne);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===ke.Orthographic){if(h=i.orthoSize,l){h=Zs(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=ii(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=oi(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=li(r.position.x,r.position.y,r.position.z),f=ti(c.length);f.entity=e,f.viewProjection.set(di(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const si=new Float32Array(16);function ii(e,t,n,s,i,r){const o=si;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const ri=new Float32Array(16);function oi(e,t,n,s){const i=ri;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const ai=new Float32Array(16);function li(e,t,n){const s=ai;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 ci=new Float32Array(16);function di(e,t){const n=ci;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 hi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ui(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const m=Math.max(0,g-f),_=Math.max(0,y-p);return{originX:f+o.x*m,originY:p+o.y*_,width:m,height:_,rect:{left:f,bottom:p,right:g,top:y}}}const fi=Ae("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 pi=null,gi=null;function yi(e,t){e.has(t,$e)||e.insert(t,$e,{texture:ae,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 hi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case hi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case hi.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 hi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case hi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case hi.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 wi(e,t,n,s){switch(e){case hi.BottomToTop:case hi.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function xi(e,t,n,s){if(!e.has(t,fi))return;const i=e.get(t,fi),r=mi(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,fi,i)}function vi(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 Si(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(bi(o.charCodeAt(0))&&s.length>0&&bi(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!bi(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Mi(e){let t=1;for(;t<e;)t*=2;return t}function Pi(e,t){let n=0,s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;n++,s=t}return n}function Ti(e,t){if(pi&&gi){const e=pi.getUIRectComputedWidth(gi,t);if(e>0)return e}return e.size.x}function Ei(e,t){if(pi&&gi){const e=pi.getUIRectComputedHeight(gi,t);if(e>0)return e}return e.size.y}function Ci(e,t,n,s,i,r){if(!e.has(t,$e))return;const o=e.get(t,$e);let a,l;switch(n){case hi.BottomToTop:case hi.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,$e,o))}function Ri(e,t,n){let s=t;for(;e.has(s,Le);){const t=e.get(s,Le).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ai(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function ki(e,t,n,s,i){if(!e.has(t,fi))return;const r=e.get(t,fi),o=ui(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,Be,n)}}function Ii(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 Fi=.1,Bi=30,zi={r:.3,g:.5,b:.8,a:1},Ui={Left:0,Center:1,Right:2},$i={Top:0,Middle:1,Bottom:2},Wi={Visible:0,Clip:1,Ellipsis:2},Di=xe("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ui.Left,verticalAlign:$i.Top,wordWrap:!0,overflow:Wi.Visible,lineHeight:1.2});class Oi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(ie.textCanvasSize,ie.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,Mi(this.frameMaxW_)),e.height=Math.max(e.height,Mi(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Mi(this.frameMaxW_),e.height=Mi(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=Si(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===Wi.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Mi(f)),s.height=Math.max(s.height,Mi(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),m=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${m}, ${_})`,i&&e.overflow===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 $i.Top:x=d;break;case $i.Middle:x=d+(p-2*d-w)/2;break;case $i.Bottom:x=p-w-d;break;default:x=d}else x=d;let v=x;for(const t of l){let s;switch(e.align){case Ui.Left:s=d;break;case Ui.Center:s=f/2;break;case Ui.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 Ui.Left:return"left";case Ui.Center:return"center";case Ui.Right:return"right"}}}const Li=Ii({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?Ti(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Ei(e.uiRect,e.entity):0});class Hi{build(e){Ce("Text",Di);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Oi(t),s=e.world,i=new Map;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Di));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Di)){if(s.valid(e)&&s.has(e,$e)){const t=s.get(e,$e);s.insert(e,$e,{texture:ae,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([Di]);for(const t of e){const e=s.get(t,Di),r=s.has(t,fi)?s.get(t,fi):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Li.changed(a,o)){if(s.has(t,$e)&&s.get(t,$e).texture!==ae)continue}yi(s,t);const l=r?{size:{x:Ti(r,t),y:Ei(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,$e);s.insert(t,$e,{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,Li.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Xi=new Hi,ji=0,Yi=1,Ni=Ae("UIMask",{enabled:!0,mode:ji});function Vi(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function Gi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],m=e[14],_=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,M=r*d-o*c,P=h*y-u*g,T=h*m-f*g,E=h*_-p*g,C=u*m-f*y,R=u*_-p*y,A=f*_-p*m;let k=w*A-x*R+v*C+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*R+d*C)*k,n[1]=(r*R-i*A-o*C)*k,n[2]=(y*M-m*S+_*b)*k,n[3]=(f*S-u*M-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(m*v-g*M-_*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*R-l*E+d*P)*k,n[9]=(i*E-s*R-o*P)*k,n[10]=(g*S-y*v+_*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*C-c*P)*k,n[13]=(s*C-i*T+r*P)*k,n[14]=(y*x-g*b-m*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function qi(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function Ki(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function Ji(e,t){return 2*Math.atan2(e,t)}function Qi(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function Zi(e,t,n,s,i,r,o,a,l,c){const d=Ji(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function er(e,t,n,s,i,r,o){if(!e.has(t,fi)||!e.has(t,Be))return null;const a=e.get(t,fi),l=e.get(t,Be),c=Ti(a,t)*l.worldScale.x,d=Ei(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),m=-d*p,_=d*(1-p),w=Ji(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-m*v,u+g*v+m*x],[h+y*x-m*v,u+y*v+m*x],[h+y*x-_*v,u+y*v+_*x],[h+g*x-_*v,u+g*v+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Qi(e,t,n,s,i,r,o);S=Math.min(S,a),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 tr(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ni]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ni);n.enabled&&(h.add(e),n.mode===Yi?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;Ri(t,e,e=>{if(i.has(e)){if(t.get(e,Ni).mode===ji)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,Ni).mode===ji){const e=er(t,n,r,o,a,l,c);e&&(s=Vi(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=er(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;Ri(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class nr{build(e){if(Ce("UIMask",Ni),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(tr(e.wasmModule,e.world))}}const sr=new nr,ir=Ae("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),rr=Ae("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),or={Normal:0,Hovered:1,Pressed:2,Disabled:3},ar=xe("Button",{state:or.Normal,transition:null});class lr{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 cr=et(new lr,"UIEvents");class dr{build(e){Ce("UIRect",fi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){pi=e,gi=t}(n,s);e.addSystemToSchedule(Lt.PreUpdate,jt([tt(en)],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(Lt.PostUpdate,jt([tt(en)],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(Lt.PostUpdate,jt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const hr=new dr;let ur=!1,fr=!1;function pr(e){ur=e}function gr(){return ur}function yr(){return!ur}function mr(e){fr=e}function _r(){return fr}const wr=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&&(Gi(t,e),n=!1),e)}}();function xr(e,t,n,s){t.emit(n,s,n),Ri(e,n,i=>{if(!e.has(i,ir))return!1;const r=e.get(i,ir);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class vr{build(e){Ce("Interactable",ir),Ce("Button",ar);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new lr;e.insertResource(cr,i);let r=null,o=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en)],(e,a)=>{if(i.drain(),gr()&&!_r())return;const l=t.getEntitiesWithComponents([rr]);for(const e of l){const n=t.get(e,rr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,rr,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;wr.update(a.viewProjection);const u=qi(d,h,wr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const m=n.uiHitTest_getHitEntity(),_=4294967295===m?null:m;if(null===r||t.valid(r)||(r=null),r!==_){if(null!==r&&t.valid(r)&&t.has(r,rr)){const e=t.get(r,rr);e.hovered=!1,t.insert(r,rr,e),i.emit(r,"hover_exit")}if(null!==_){Ai(t,_,rr);const e=t.get(_,rr);e.hovered=!0,t.insert(_,rr,e),i.emit(_,"hover_enter")}r=_}if(g&&null!==_){const e=t.get(_,rr);e.pressed=!0,e.justPressed=!0,t.insert(_,rr,e),o=_,xr(t,i,_,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,rr)){const e=t.get(o,rr);e.pressed=!1,e.justReleased=!0,t.insert(o,rr,e),xr(t,i,o,"release"),o===r&&xr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Lt.Update,jt([],()=>{const e=t.getEntitiesWithComponents([ar]);for(const n of e){if(Ai(t,n,ir,{enabled:!0}),!t.has(n,rr))continue;const e=t.get(n,rr),s=t.get(n,ar),i=t.get(n,ir),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=or.Pressed:e.hovered?s.state=or.Hovered:s.state=or.Normal:s.state=or.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,$e)){const r=t.get(n,$e);r.color=vi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,$e,r)}}},{name:"ButtonSystem"}))}}const br=new vr,Sr=xe("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Mr=xe("Focusable",{tabIndex:0,isFocused:!1});class Pr{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 Tr=et(new Pr,"FocusManager");class Er{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Ce("TextInput",Sr),gr()&&!_r())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(ie.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function g(){const t=e.getResource(Tr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,Sr)?s:null}const y=()=>{l||null===g()||v()},m=()=>{l=!0},_=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,Sr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(cr).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,Sr);s.focused=!1,s.dirty=!0;e.getResource(Tr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,Sr);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(cr).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=n.get(t,Sr);e.focused=!1,e.dirty=!0}e.getResource(Tr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",m),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",m),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let M=null;function P(e,l,d,h){(i.width<d||i.height<h)&&(i.width=Mi(Math.max(i.width,d)),i.height=Mi(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),m=l.padding;if(l.multiline){const e=Si(r,p,d-2*m);let t=m;for(const n of e)r.fillText(n,m,t),t+=y}else{const e=(h-l.fontSize)/2;r.fillText(p,m,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=Si(r,l.value,d-2*m);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=m+r.measureText(c).width,n=m+o*y,s=y}else t=m+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const _=r.getImageData(0,0,d,h),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,$e);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,$e,S)}e.addSystemToSchedule(Lt.Update,jt([tt(Tr)],e=>{const t=n.getEntitiesWithComponents([Sr]);for(const e of t)Ai(n,e,Mr,{tabIndex:0,isFocused:!1}),Ai(n,e,ir,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,Sr)){const e=n.get(M,Sr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,Sr);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(Lt.PreUpdate,jt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,Sr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,Sr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([Sr,fi]);for(const e of a){const t=n.get(e,Sr);if(!t.dirty)continue;const s=n.get(e,fi),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(yi(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Cr=new Er,Rr={Simple:0,Sliced:1,Tiled:2,Filled:3},Ar={Horizontal:0,Vertical:1},kr={Left:0,Right:1,Bottom:2,Top:3},Ir=xe("Image",{texture:ae,color:{r:1,g:1,b:1,a:1},imageType:Rr.Simple,fillMethod:Ar.Horizontal,fillOrigin:kr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Fr=Ii({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?Ti(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Ei(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const Br=new class{build(e){Ce("Image",Ir);const t=e.world,n=new Map;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Ir)||n.delete(e);const e=t.getEntitiesWithComponents([Ir]);for(const s of e){const e=t.get(s,Ir),i=t.has(s,fi)?t.get(s,fi):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!Fr.changed(o,r))continue;yi(t,s);const a=t.get(s,$e);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=Ti(i,s),a.size.y=Ei(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===Rr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===Ar.Horizontal?e.fillOrigin===kr.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===kr.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===Rr.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,$e,a),n.set(s,Fr.take(r))}else a.color.a=0,t.insert(s,$e,a),n.set(s,Fr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},zr=xe("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Ur=xe("ToggleGroup",{allowSwitchOff:!1});const $r=new class{build(e){Ce("Toggle",zr),Ce("ToggleGroup",Ur);const t=e.world,n=new Set;e.addSystemToSchedule(Lt.Update,jt([tt(cr)],e=>{const s=t.getEntitiesWithComponents([zr]);if(!gr()||_r()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,zr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,zr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,zr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(Ai(t,n,ir,{enabled:!0}),!t.has(n,rr))continue;const s=t.get(n,rr),i=t.get(n,zr),o=t.get(n,ir);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,Ur);if(i.isOn&&o){if(!t.get(s,Ur).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,zr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,zr);i.isOn&&(i.isOn=!1,t.insert(s,zr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,$e)){const e=t.get(n,$e);e.color=vi(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,$e,e)}}}for(const e of s){const n=t.get(e,zr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,$e)){const e=t.get(n.graphicEntity,$e);e.enabled=n.isOn,t.insert(n.graphicEntity,$e,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Wr=hi,Dr=xe("ProgressBar",{value:0,fillEntity:0,direction:hi.LeftToRight});function Or(e,t,n,s){if(!e.has(t,fi))return;const i=e.get(t,fi),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=ui(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,$e)){const n=e.get(t,$e);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,$e,n))}if(e.has(t,Be)){const n=e.get(t,Be),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,Be,n))}}class Lr{build(e){Ce("ProgressBar",Dr);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e=t.getEntitiesWithComponents([Dr,fi]);for(const n of e){const e=t.get(n,Dr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,fi),i=Math.max(0,Math.min(1,e.value));xi(t,e.fillEntity,e.direction,i);const r=Ti(s,n),o=Ei(s,n);Or(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Hr=new Lr,Xr=xe("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),jr=xe("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 Yr=new class{build(e){Ce("Draggable",Xr),Ce("DragState",jr);const t=e.world,n=e.getResource(cr);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en)],(e,o)=>{if(gr()&&!_r())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Xr,rr]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Xr).enabled)continue;if(t.get(s,rr).hovered){let e=0;t.has(s,$e)&&(e=t.get(s,$e).layer);const i=Pi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,jr)||t.insert(n,jr);const e=t.get(n,jr),r=t.get(n,Be);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,jr)){t.get(s,jr).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(s,Xr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,jr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,jr))return void(r=null);const s=t.get(r,jr),i=t.get(r,Xr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,Be)){const e=function(e,t,n,s){if(!e.has(t,Le))return{x:n,y:s};const i=e.get(t,Le).entity;if(!e.valid(i)||!e.has(i,Be))return{x:n,y:s};const r=e.get(i,Be),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Ji(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,Be);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,Be,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Nr=xe("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Vr(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 Gr(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const qr=new class{build(e){Ce("ScrollView",Nr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(Lt.PostUpdate,jt([tt(Jt),tt(en),tt(rt)],(e,i,r)=>{const o=gr()&&!_r(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Nr,fi]);for(const r of l){Ai(t,r,Ni,{enabled:!0,mode:ji});const l=t.get(r,Nr),c=t.get(r,fi);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=Ti(c,r),u=Ei(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,He)){const e=t.get(l.contentEntity,He).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,Be))continue;const e=t.get(o,Be);let a=0,l=0,c=.5,d=.5;if(t.has(o,fi)){const e=t.get(o,fi);a=Ti(e,o)||e.size.x,l=Ei(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,$e)){const e=t.get(o,$e);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){Ai(t,r,ir,{enabled:!0,blockRaycast:!0});const n=t.has(r,rr)?t.get(r,rr):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=Vr(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=Vr(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Vr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Vr(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Gr(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)<Fi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>Fi?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Gr(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)<Fi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>Fi?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,Be)){const e=t.get(l.contentEntity,Be),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,Be,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Kr=hi,Jr=xe("Slider",{value:0,minValue:0,maxValue:1,direction:hi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Qr(e,t,n,s,i,r){const o=Ti(s,i)*n.worldScale.x,a=Ei(s,i)*n.worldScale.y,l=Ji(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case hi.LeftToRight:return o>0?(f-g)/o:0;case hi.RightToLeft:return o>0?1-(f-g)/o:0;case hi.BottomToTop:return a>0?(p-y)/a:0;case hi.TopToBottom:return a>0?1-(p-y)/a:0}}function Zr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case hi.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case hi.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case hi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case hi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class eo{build(e){Ce("Slider",Jr);const t=e.world;let n=null;e.addSystemToSchedule(Lt.PreUpdate,jt([tt(Jt),tt(en),tt(cr)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Jr,fi]);for(const o of r){const r=t.get(o,Jr),a=t.get(o,fi);if(!gr()||_r()){if(t.has(o,Be)){Ai(t,o,ir,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&Ai(t,r.handleEntity,ir,{enabled:!0,blockRaycast:!1});const l=t.get(o,Be),c=t.has(o,rr)?t.get(o,rr):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,rr)&&(d=t.get(r.handleEntity,rr).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Qr(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,Jr,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=Ti(a,o),h=Ei(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(xi(t,r.fillEntity,r.direction,c),ki(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,fi)){const e=t.get(r.handleEntity,fi);Zr(e,r.direction,c),t.insert(r.handleEntity,fi,e),ki(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const to=new eo;const no=new class{build(e){Ce("Focusable",Mr);const t=e.world,n=new Pr;e.insertResource(Tr,n),e.addSystemToSchedule(Lt.Update,jt([tt(Jt),tt(cr)],(e,s)=>{if(gr()&&!_r())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Mr]);for(const e of i){if(!t.has(e,rr))continue;t.get(e,rr).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,ir)){if(!t.get(n,ir).enabled)continue}const s=t.get(n,Mr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Mr)){t.get(i,Mr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Mr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},so=xe("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function io(){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 ro=new class{build(e){Ce("SafeArea",so);const t=e.world;let n=io(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=io(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=io(),s=!0});e.addSystemToSchedule(Lt.PreUpdate,jt([tt(en)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([so,fi]);for(const e of d){const s=t.get(e,so),i=t.get(e,fi),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,fi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},oo=xe("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let ao=null;function lo(e,t){if(!ao)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=ao.get(e);n?n.renderer=t:ao.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const co=new class{build(e){Ce("ListView",oo);const t=e.world,n=new Map;ao=n,e.addSystemToSchedule(Lt.PostUpdate,jt([tt(Jt)],e=>{const s=gr()&&!_r();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([oo,fi]);for(const r of i){Ai(t,r,ir,{enabled:!0,blockRaycast:!0}),Ai(t,r,Ni,{enabled:!0,mode:ji});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,oo),a=t.get(r,fi),l=Ei(a,r),c=Ti(a,r);if(!s){const n=t.has(r,rr)?t.get(r,rr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,Ye,{value:`ListItem_${e}`}),t.insert(n,fi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,Be)){const s=t.get(n,Be);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,Be,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},ho=xe("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const uo=new class{build(e){Ce("Dropdown",ho);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,Be))return;const n=t.get(e,Be);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,Be,{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,$e)){const n=t.get(e,$e);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,$e,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,$e),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*Bi;t.insert(i,fi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,Be,{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,$e,{texture:ae,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*Bi;t.insert(r,Ye,{value:`Option_${e}`}),t.insert(r,fi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Bi},offsetMax:{x:0,y:0},size:{x:o,y:Bi},pivot:{x:.5,y:.5}}),t.insert(r,Be,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,$e,{texture:ae,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:Bi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,ir,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,Be,{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,Di,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ui.Left,verticalAlign:$i.Middle,wordWrap:!1,overflow:Wi.Clip,lineHeight:1.2}),t.insert(c,fi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:Bi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Di))return;const s=t.get(n,Di);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Di,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,ir)&&t.insert(e,ir,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,$e))){const s=t.get(e,$e);t.insert(e,$e,{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,$e))continue;const i=n===e.highlightIndex?{...zi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,$e,{texture:ae,color:i,size:{x:e.ddWidth,y:Bi},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,rr))continue;if(t.get(n,rr).hovered)return!0}return!1}e.addSystemToSchedule(Lt.Update,jt([tt(Jt),tt(cr)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=gr()&&!_r(),p=t.getEntitiesWithComponents([ho]);for(const g of p){const p=t.get(g,ho);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;Ai(t,g,ir,{enabled:!0,blockRaycast:!0});const m=t.has(g,rr)?t.get(g,rr):null;if(m?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,rr))continue;if(t.get(n,rr).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,rr))continue;if(t.get(s,rr).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(m?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},fo=0,po=0,go=2,yo=xe("LayoutGroup",{direction:fo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:po,reverseOrder:!1});const mo=new class{build(e){Ce("LayoutGroup",yo);const t=e.world;e.addSystemToSchedule(Lt.PreUpdate,jt([],()=>{const e=t.getEntitiesWithComponents([yo,fi,He]);for(const n of e){const e=t.get(n,yo),s=t.get(n,fi),i=t.get(n,He);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,fi)&&t.has(e,Be)&&r.push({entity:e,rect:t.get(e,fi)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=Ti(s,n),a=Ei(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===fo;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=Ti(s.rect,s.entity),f=Ei(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,m;h?(y=-l*o+d.left+u+p*i,m=e.childAlignment===po?(1-c)*a-d.top-(1-g)*f:e.childAlignment===go?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===po?-l*o+d.left+p*i:e.childAlignment===go?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,m=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const _=t.get(s.entity,Be);_.position.x=y,_.position.y=m,t.insert(s.entity,Be,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};Ae("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),Ae("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class _o{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(Lt.PostUpdate,jt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const wo=new _o;async function xo(e,t,n){const s=e.getResource(Ns);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function vo(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}const bo=et({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),So=et(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 Po(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class To{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(bo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=vo(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([De]);for(const n of t){const t=e.world.get(n,De);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(Lt.PostUpdate,jt([tt(rt)],a=>{const l=o.getEntitiesWithComponents([Ge,Be]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,Ge),l=o.get(i,Be);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Mo(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Eo(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===Qe.Kinematic){const e=Mo(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,Be);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,Le)){const t=e.world.get(o,Le);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,Be)){const n=e.world.get(t.entity,Be),s=Mo(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=Po(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,Be,d)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(bo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(So,Co._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function Eo(e,t,n){const s=e.world;if(s.has(n,qe)){const e=s.get(n,qe);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,Ke)){const e=s.get(n,Ke);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,Je)){const e=s.get(n,Je);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 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},Ao={repeat:0,clamp:1,mirror:2};function ko(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=Ro[s.filterMode??"linear"]??1,a=Ao[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function Io(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 Fo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,m=l*u,_=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(m+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(_+x)*r,0,(y+v)*o,(_-x)*o,(1-(p+m))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Bo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Pn(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=ko(e,await n.loadPixels(r),!0,t)}catch{s[r]=0}}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let d={},h=null;if(i&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=Tn(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===v(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=Io(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=ko(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...te},fixedTimestep:o?.fixedTimestep??ne,subStepCount:o?.subStepCount??4};new To("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Pn(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=v(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=ko(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Pn(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=hn.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=hn.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Pn(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,u,f);const p=In(e.world,n);if(l&&e.hasResource(Ns))for(const t of p.values())e.world.insert(t,Ne,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=Tn(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=ee);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,je)?c.get(r,je):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,Be)){const e=Fo(c.get(r,Be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),m=new Uint16Array(n.HEAPU8.buffer,d,r),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,_>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(m),t.renderer_submitTriangles(_,i,w,r,p,g,u),t._free(_),t._free(w),n._free(c),n._free(d),n._free(h),n._free(f)}u&&t._free(u)}})}(e,t,i,h,s)}if(a){const t=e.getResource(Dn);t&&t.setAddressableManifest(a)}}function zo(e,t,n){return{name:e,async setup(){await Bo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class Uo{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Tn(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===v(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Pn(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=v(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const $o="__preview__";class Wo{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(Ns);t.register({name:$o,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial($o),this.loadPromise_=t.load($o).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Uo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Bo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,$o)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([We]);for(const s of n){if(e.get(s,We).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([De]);for(const i of s){const s=e.get(i,De);if(s.designResolution){const e=s.pixelsPerUnit||100;t=s.designResolution.y/2/e,n=s.designResolution.x/s.designResolution.y;break}}const i=this.app_.getResource(Ns).getScene($o),r=i?i.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,Be,o);const a={isActive:!0,projectionType:ke.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Ie.ColorAndDepth};e.insert(r,We,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(Ns);await e.switchTo($o),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 Do={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=Us.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:Us.getTargetTexture(n),width:e.width,height:e.height}},release(e){Us.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(Us.releaseRenderTarget(e._handle),Do.create({width:t,height:n,depth:!0})),begin(e,t){Us.begin(t,e._handle)},end(){Us.end()},getDepthTexture:e=>Us.getTargetDepthTexture(e._handle)};var Oo;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Oo||(Oo={}));class Lo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Oo[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Oo.Debug:console.debug(t,n);break;case Oo.Info:console.log(t,n);break;case Oo.Warn:console.warn(t,n);break;case Oo.Error:console.error(t,n)}}}class Ho{constructor(){this.handlers_=[],this.minLevel_=Oo.Info,this.addHandler(new Lo)}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(Oo.Debug,e,t,n)}info(e,t,n){this.log(Oo.Info,e,t,n)}warn(e,t,n){this.log(Oo.Warn,e,t,n)}error(e,t,n){this.log(Oo.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 Xo=new Ho;function jo(){return Xo}function Yo(e){Xo.setMinLevel(e)}function No(e,t,n){Xo.debug(e,t,n)}function Vo(e,t,n){Xo.info(e,t,n)}function Go(e,t,n){Xo.warn(e,t,n)}function qo(e,t,n){Xo.error(e,t,n)}const Ko=[Xi,sr,hr,Br,Hr,br,Yr,qr,to,$r,Cr,no,ro,co,uo,mo,wo];function Jo(e,t){return function(e,t){const n=Ks.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),is(e),ln(e),vs(e),Ts(e),Bs(e),Ws(e);const i=new Ls;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=ni(e,s,t,i));const o=n.getResource(en);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(en,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;Us.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(Us.resize(t,l),Rs.isInitialized()&&Rs.getPassCount()>0&&!Rs.isBypassed()&&Rs.resize(t,l),n.hasResource(Ns)){const e=n.getResource(Ns).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ni(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Qs,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}Us.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(Lt.First,l),n.addSystemToSchedule(Lt.Last,c),n.addPlugin(Ln),n.addPlugin(Qn),n.addPlugin(Zt),n.addPlugin(qs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Ko,...t})}X||(X=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await p(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return g(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{vt as Added,Ks as App,On as AssetPlugin,Hn as AssetRefCounter,Wn as AssetServer,Dn as Assets,xn as AsyncCache,Xe as BitmapText,tn as BlendMode,Qe as BodyType,qe as BoxCollider,ar as Button,or as ButtonState,We as Camera,De as Canvas,Je as CapsuleCollider,bt as Changed,He as Children,Ke as CircleCollider,Ie as ClearFlags,kt as Commands,Ft as CommandsInstance,N as DEFAULT_DESIGN_HEIGHT,Y as DEFAULT_DESIGN_WIDTH,ee as DEFAULT_FALLBACK_DT,ne as DEFAULT_FIXED_TIMESTEP,K as DEFAULT_FONT_FAMILY,J as DEFAULT_FONT_SIZE,te as DEFAULT_GRAVITY,Q as DEFAULT_LINE_HEIGHT,Z as DEFAULT_MAX_DELTA_TIME,V as DEFAULT_PIXELS_PER_UNIT,se as DEFAULT_SPINE_SKIN,q as DEFAULT_SPRITE_SIZE,G as DEFAULT_TEXT_CANVAS_SIZE,ys as DataType,jr as DragState,Xr as Draggable,ls as Draw,ho as Dropdown,It as EntityCommands,Wt as EventReader,Ot as EventReaderInstance,Ut as EventRegistry,$t as EventWriter,Dt as EventWriterInstance,hi as FillDirection,Ar as FillMethod,kr as FillOrigin,Tr as FocusManager,Pr as FocusManagerState,Mr as Focusable,Os as GLDebug,Ms as Geometry,Ht as GetWorld,oe as INVALID_ENTITY,le as INVALID_FONT,ce as INVALID_MATERIAL,ae as INVALID_TEXTURE,Ir as Image,Rr as ImageType,Jt as Input,Qt as InputPlugin,Kt as InputState,ir as Interactable,oo as ListView,ze as LocalTransform,Oo as LogLevel,Ho as Logger,hn as Material,vn as MaterialLoader,wt as Mut,Ye as Name,Le as Parent,Co as Physics,bo as PhysicsEvents,To as PhysicsPlugin,Rs as PostProcess,qn as PrefabServer,Kn as Prefabs,Jn as PrefabsPlugin,Wo as PreviewPlugin,Dr as ProgressBar,Wr as ProgressBarDirection,Lr as ProgressBarPlugin,ke as ProjectionType,Et as Query,Ct as QueryInstance,Rt as Removed,At as RemovedQueryInstance,Ls as RenderPipeline,ks as RenderStage,Do as RenderTexture,Us as Renderer,tt as Res,nt as ResMut,Ge as RigidBody,ie as RuntimeConfig,so as SafeArea,Fe as ScaleMode,Ns as SceneManager,Ys as SceneManagerState,Ne as SceneOwner,Lt as Schedule,Nr as ScrollView,wn as ShaderSources,Jr as Slider,Kr as SliderDirection,eo as SliderPlugin,je as SpineAnimation,$e as Sprite,qt as SystemRunner,Di as Text,Ui as TextAlign,Sr as TextInput,Er as TextInputPlugin,Wi as TextOverflow,Hi as TextPlugin,Oi as TextRenderer,$i as TextVerticalAlign,rt as Time,zr as Toggle,Be as Transform,en as UICameraInfo,lr as UIEventQueue,cr as UIEvents,rr as UIInteraction,vr as UIInteractionPlugin,dr as UILayoutPlugin,Ni as UIMask,nr as UIMaskPlugin,fi as UIRect,_o as UIRenderOrderPlugin,Oe as Velocity,Uo as WebAssetProvider,_t as World,Ue as WorldTransform,Vt as addStartupSystem,Nt as addSystem,Gt as addSystemToSchedule,xi as applyDirectionalFill,re as applyRuntimeConfig,Ln as assetPlugin,gs as clearDrawCallbacks,Se as clearUserComponents,fe as color,mi as computeFillAnchors,wi as computeFillSize,_i as computeHandleAnchors,ui as computeUIRectLayout,tr as createMaskProcessor,zo as createRuntimeSceneConfig,Jo as createWebApp,No as debug,xe as defineComponent,Bt as defineEvent,et as defineResource,jt as defineSystem,ve as defineTag,qo as error,$n as findEntityByName,Js as flushPendingSystems,S as getAddressableType,M as getAddressableTypeByEditorType,T as getAllAssetExtensions,A as getAssetMimeType,v as getAssetTypeEntry,Re as getComponent,Pn as getComponentAssetFieldDescriptors,Mn as getComponentAssetFields,Ve as getComponentDefaults,Rn as getComponentEntityFields,Tn as getComponentSpineFieldDescriptor,C as getCustomExtensions,b as getEditorType,jo as getLogger,t as getPlatform,s as getPlatformType,be as getUserComponent,R as getWeChatPackOptions,Vo as info,is as initDrawAPI,Ws as initGLDebugAPI,vs as initGeometryAPI,ln as initMaterialAPI,Ts as initPostProcessAPI,Bs as initRendererAPI,Zt as inputPlugin,jn as instantiatePrefab,Vi as intersectRects,Gi as invertMatrix4,Te as isBuiltinComponent,k as isCustomExtension,gr as isEditor,P as isKnownAssetExtension,n as isPlatformInitialized,_r as isPlayMode,yr as isRuntime,nn as isTextureRef,i as isWeChat,r as isWeb,zn as loadComponent,vo as loadPhysicsModule,Bo as loadRuntimeScene,In as loadSceneData,Fn as loadSceneWithAssets,E as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Zi as pointInOBB,Ki as pointInWorldRect,Qn as prefabsPlugin,Hr as progressBarPlugin,pe as quat,Ce as registerComponent,Sn as registerComponentAssetFields,Cn as registerComponentEntityFields,fs as registerDrawCallback,Xn as registerEmbeddedAssets,_n as registerMaterialCallback,An as remapEntityFields,qs as sceneManagerPlugin,qi as screenToWorld,pr as setEditorMode,lo as setListViewRenderer,Yo as setLogLevel,mr as setPlayMode,dt as setWasmErrorHandler,rs as shutdownDrawAPI,Ds as shutdownGLDebugAPI,bs as shutdownGeometryAPI,cn as shutdownMaterialAPI,Es as shutdownPostProcessAPI,zs as shutdownRendererAPI,to as sliderPlugin,Ci as syncFillSpriteSize,Cr as textInputPlugin,Xi as textPlugin,xo as transitionTo,br as uiInteractionPlugin,hr as uiLayoutPlugin,sr as uiMaskPlugin,Ko as uiPlugins,wo as uiRenderOrderPlugin,Me as unregisterComponent,ps as unregisterDrawCallback,Un as updateCameraAspectRatio,de as vec2,he as vec3,ue as vec4,Go as warn,Vs as wrapSceneSystem,$ as wxFileExists,W as wxFileExistsSync,L as wxGetImagePixels,O as wxLoadImage,H as wxLoadImagePixels,z as wxReadFile,U as wxReadTextFile,D 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 9926bbda0..59a763d31 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -1019,9 +1019,13 @@ declare enum Schedule {
FixedUpdate = 11,
FixedPostUpdate = 12
}
+interface GetWorldDescriptor {
+ readonly _type: 'get_world';
+}
+declare function GetWorld(): GetWorldDescriptor;
type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
-type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef>;
-type InferParam<P> = P extends QueryDescriptor<infer C> ? QueryInstance<C> : P extends ResDescriptor<infer T> ? T : P extends ResMutDescriptor<infer T> ? ResMutInstance<T> : P extends CommandsDescriptor ? CommandsInstance : P extends EventWriterDescriptor<infer T> ? EventWriterInstance<T> : P extends EventReaderDescriptor<infer T> ? EventReaderInstance<T> : P extends RemovedQueryDescriptor<infer _T> ? RemovedQueryInstance<_T> : never;
+type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
+type InferParam<P> = P extends QueryDescriptor<infer C> ? QueryInstance<C> : P extends ResDescriptor<infer T> ? T : P extends ResMutDescriptor<infer T> ? ResMutInstance<T> : P extends CommandsDescriptor ? CommandsInstance : P extends EventWriterDescriptor<infer T> ? EventWriterInstance<T> : P extends EventReaderDescriptor<infer T> ? EventReaderInstance<T> : P extends RemovedQueryDescriptor<infer _T> ? RemovedQueryInstance<_T> : P extends GetWorldDescriptor ? World : never;
type InferParams<P extends readonly SystemParam[]> = {
[K in keyof P]: InferParam<P[K]>;
};
@@ -3294,5 +3298,5 @@ declare const uiPlugins: Plugin[];
declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;
-export { Added, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragState, Draggable, Draw, Dropdown, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, Focusable, GLDebug, Geometry, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImageType, Input, InputPlugin, InputState, Interactable, ListView, LocalTransform, LogLevel, Logger, 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, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, Toggle, Transform$1 as Transform, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, applyDirectionalFill, applyRuntimeConfig, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineEvent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, remapEntityFields, sceneManagerPlugin, screenToWorld, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, sliderPlugin, syncFillSpriteSize, textInputPlugin, textPlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };
-export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, 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, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PluginDependency, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeSceneOptions, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
+export { Added, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragState, Draggable, Draw, Dropdown, 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, 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, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, Toggle, Transform$1 as Transform, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, applyDirectionalFill, applyRuntimeConfig, assetPlugin, clearDrawCallbacks, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defineComponent, defineEvent, defineResource, defineSystem, defineTag, error, findEntityByName, flushPendingSystems, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getLogger, getPlatform, getPlatformType, getUserComponent, getWeChatPackOptions, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, looksLikeAssetPath, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, prefabsPlugin, progressBarPlugin, quat, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, remapEntityFields, sceneManagerPlugin, screenToWorld, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, sliderPlugin, syncFillSpriteSize, textInputPlugin, textPlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };
+export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnyComponentDef, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadedMaterial, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, PluginDependency, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeSceneOptions, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteData, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureHandle, TextureInfo, TextureRef, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, 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 3742ff118..739b5fd05 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function r(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function d(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}const p=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),r=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},d=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",r),n.addEventListener("mousedown",o),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",d),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",r),n.removeEventListener("mousedown",o),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",d),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},g=1920,y=1080,_=100,m=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",R={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function C(e){e.Text&&(e.Text._default.fontFamily=R.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=R.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=R.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=R.canvasMatchWidthOrHeight)}const A=0,k=4294967295,I=4294967295,F=0,B=(e=0,t=0)=>({x:e,y:t}),z=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),U=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),$=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),D=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function L(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(L);const t={};for(const n in e)t[n]=L(e[n]);return t}let W=0;function O(e,t){const n=++W,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?{...L(t),...e}:L(t):e?{...t,...e}:{...t}}}const H=new Map;function X(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function Y(e,t){const n=J.get(e)??X().get(e);if(n)return n;const s=O(e,t);return X().set(e,s),J.set(e,s),q(e,t,!1),s}function j(e){const t=J.get(e)??X().get(e);if(t)return t;const n=O(e,{});return X().set(e,n),J.set(e,n),q(e,{},!0),n}function N(e){return X().get(e)}function V(){const e=X();for(const t of e.keys())J.delete(t);e.clear()}function G(e){X().delete(e),J.delete(e)}function q(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e){return!0===e._builtin}const J=new Map;function Q(e,t){J.set(e,t)}function Z(e){return J.get(e)??N(e)}function ee(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return J.set(e,n),n}const te={Perspective:0,Orthographic:1},ne={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ie=ee("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=ie,oe=ie,ae=ee("Sprite",{texture:k,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}),le=ee("Camera",{projectionType:te.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:ne.ColorAndDepth}),ce=ee("Canvas",{designResolution:{x:g,y:y},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),de=ee("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),he=ee("Parent",{entity:0}),ue=ee("Children",{entities:[]}),fe=ee("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:I,enabled:!0}),pe=ee("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ge=Y("Name",{value:""}),ye=Y("SceneOwner",{scene:"",persistent:!1});function _e(e){const t=Z(e);return t?L(t._default):null}const me=ee("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=ee("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=ee("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=ee("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be={Static:0,Kinematic:1,Dynamic:2};let Se=0;function Me(e,t){const n=++Se;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Pe(e){return{_type:"res",_resource:e}}function Te(e){return{_type:"res_mut",_resource:e}}class Ee{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 Ee(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ce=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ae(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=ke(t[e]),r=ke(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ie(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 Fe=null;function Be(e){Fe=e}function ze(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Fe&&Fe(e,t)}function Ue(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 $e=1;const De=new WeakMap;function Le(e){let t=De.get(e);return void 0===t&&(t=$e++,De.set(e,t)),t}const We=[];function Oe(e,t=[],n=[]){We.length=0;for(const t of e)We.push(Le(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(Le(e));We.sort((e,t)=>e-t),s+="|+"+We.join(",")}if(n.length>0){We.length=0;for(const e of n)We.push(Le(e));We.sort((e,t)=>e-t),s+="|-"+We.join(",")}return s}class He{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.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 ze(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_;return this.entities_.set(e,t),this.worldVersion_++,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){ze(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)}}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){ze(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ze(t,`removeParent(entity=${e})`)}}insert(e,t,n){return K(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(K(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Ue(n))}catch(n){ze(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 K(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return K(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(K(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ze(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.");K(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Ae(t._name,t._default,s);if(e.length>0)throw new Error(Ie(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Ue(i))}catch(n){ze(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return ze(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 ze(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ze(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=Ae(t._name,t._default,e);if(i.length>0)throw new Error(Ie(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of J)if(K(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=X();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??Oe(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!K(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Xe(e){return{_type:"mut",_component:e}}function Ye(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function je(e){return{_filterType:"added",_component:e}}function Ne(e){return{_filterType:"changed",_component:e}}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ge(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function qe(e){return Ye(e)||Ve(e)||Ge(e)?e._component:e}function Ke(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),Ve(e)?i.push({index:t,component:e._component}):Ge(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Ke(e,[...t,...s],n),without:(...s)=>Ke(e,t,[...n,...s])}}function Je(...e){return Ke(e)}class Qe{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(qe),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_=Oe(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Ze(e){return{_type:"removed",_component:e}}class et{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 tt(){return{_type:"commands"}}class nt{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=K(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 st{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new nt(this,null);return this.spawned_.push(e),e}entity(e){return new nt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function it(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 ot{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 at(e){return{_type:"event_writer",_event:e}}function lt(e){return{_type:"event_reader",_event:e}}class ct{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class dt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ht;!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"}(ht||(ht={}));let ut=0;function ft(e,t,n){const s=++ut;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function pt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function gt(e){pt().push({schedule:ht.Update,system:e})}function yt(e){pt().push({schedule:ht.Startup,system:e})}function _t(e,t){pt().push({schedule:e,system:t})}class mt{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 st&&t[e].flush()}finally{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 st(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 ct(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(n)}case"removed":{const t=e;return new et(this.world_,t._component,this.currentLastRunTick_)}default:throw new Error("Unknown system parameter type")}}}class wt{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 xt=Me(new wt,"Input");class vt{constructor(e){this.target_=e??null}build(e){const n=new wt;e.insertResource(xt,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(ht.Last,ft([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const bt=new vt,St=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 Mt;function Pt(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"}(Mt||(Mt={}));let Tt=null,Et=null,Rt=1;const Ct=new Map;function At(e){Tt=e,Et=e.getResourceManager(),Wt()}function kt(){0!==zt&&Tt&&(Tt._free(zt),zt=0),Ct.clear(),Rt=1,Bt=!1,$t.clear(),Dt=null,Et=null,Tt=null}function It(){if(!Et)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Et}const Ft={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Rt++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Mt.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 Ct.set(t,n),t},get:e=>Ct.get(e),setUniform(e,t,n){const s=Ct.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Tt?.invalidateMaterialCache(e))},getUniform(e,t){const n=Ct.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Ct.get(e);n&&(n.blendMode=t,Tt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??Mt.Normal},setDepthTest(e,t){const n=Ct.get(e);n&&(n.depthTest=t,Tt?.invalidateMaterialCache(e))},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e),Tt?.invalidateMaterialCache(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear(),Tt?.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??Mt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Rt++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(n,s),n},toAssetData(e,t){const n=Ct.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=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Bt=!1,zt=0;const Ut=16384,$t=new Map;let Dt=null;function Lt(e){const t=(0===zt&&Tt&&(zt=Tt._malloc(Ut)),zt);if(0===t||!Tt)return{ptr:0,count:0};let n=0,s=0;const i=Tt.HEAPU8,r=Tt.HEAPU32,o=Tt.HEAPF32;for(const[a,l]of e){if(Pt(l))continue;let e=$t.get(a);e||(Dt||(Dt=new TextEncoder),e=Dt.encode(a),$t.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>Ut){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Ut} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Wt(){if(!Tt||Bt)return;Tt.materialDataProvider=(e,t,n,s,i)=>{const r=Ct.get(e);if(!r)return Tt.HEAPU32[t>>2]=0,Tt.HEAPU32[n>>2]=0,Tt.HEAPU32[s>>2]=0,void(Tt.HEAPU32[i>>2]=0);Tt.HEAPU32[t>>2]=r.shader,Tt.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Lt(r.uniforms);Tt.HEAPU32[s>>2]=o,Tt.HEAPU32[i>>2]=a},Bt=!0}const Ot={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 Ht{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Xt{constructor(e,t=""){this.cache_=new Ht,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&&(Ft.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ft.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:Ft.createFromAsset(s,r),shaderHandle:r,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const Yt=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"}]}]]);function jt(e,t){Yt.set(e,t)}function Nt(e){const t=Yt.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 Vt(e){return Yt.get(e)?.fields??[]}function Gt(e){return Yt.get(e)?.spine??null}const qt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Kt(e,t){qt.set(e,t)}function Jt(e){return qt.get(e)}function Qt(e,t){const n=qt.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function Zt(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,ge,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Qt(i,n),sn(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 en(e,t){return Zt(e,t)}async function tn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl,r=new Map;s&&await async function(e,t,n,s,i){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of nn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Yt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...nn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Yt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=l.get(e.type)?.get(t)??0)}}}(t,s,i,r,n?.collectAssets);const o=Zt(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const nn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}]]);function sn(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=Z(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 rn(e,t){const n=e.getEntitiesWithComponents([le]);for(const s of n){const n=e.get(s,le);n&&(n.aspectRatio=t,e.insert(s,le,n))}}function on(e,t){const n=e.getEntitiesWithComponents([ge]);for(const s of n){const n=e.get(s,ge);if(n&&n.value===t)return s}return null}const an=[{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}],ln={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",bmfont:"application/json",fnt:"text/plain"},cn=new Map,dn=new Set;for(const e of an)for(const t of e.extensions)cn.set(t,e),dn.add(t);function hn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function un(e){return cn.get(hn(e))}function fn(e){return un(e)?.editorType??"unknown"}function pn(e){return un(e)?.addressableType??null}function gn(e){for(const t of an)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function yn(e){return dn.has(e.toLowerCase())}function _n(){return dn}function mn(e){return"string"==typeof e&&(!!e.includes("/")&&yn(hn(e)))}function wn(){const e=[];for(const t of an)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function xn(){return wn().map(e=>({type:"suffix",value:e}))}function vn(e){return ln[e.toLowerCase()]}function bn(e){const t=un(e);return t?.wechatPackInclude??!1}class Sn{constructor(e){this.textureCache_=new Ht,this.shaderCache_=new Ht,this.jsonCache_=new Ht,this.textCache_=new Ht,this.binaryCache_=new Ht,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ht,this.prefabCache_=new Ht,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.module_=e,this.canvas_=h(R.textCanvasSize,R.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Xt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ft.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===un(e)?.contentType,h=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,r,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=un(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return tn(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 n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const i=s??n;return new Promise((n,s)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(r)},r.onerror=()=>s(new Error(`Failed to load image: ${e}`)),r.src=i})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(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 Ft.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return Ft.createShader(i,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Mn=Me(null,"Assets");class Pn{build(e){const t=e.wasmModule;t?e.insertResource(Mn,new Sn(t)):console.warn("AssetPlugin: No WASM module available")}}const Tn=new Pn;class En{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 Rn(e,t){const n=e.getResource(Mn);n&&n.registerEmbeddedAssets(t)}async function Cn(e,t,n){const{entities:s,rootId:i}=await kn(t,n?.overrides??[],n,void 0,new Set),r={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await tn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const An=10;async function kn(e,t,n,s,i,r=0){if(r>An)throw new Error(`Prefab nesting depth exceeded ${An}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await kn(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};In(h.components,o),Fn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function In(e,t){for(const n of e){const e=Jt(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 Fn(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 Bn{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 Cn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const zn=Me(null,"Prefabs");class Un{constructor(){this.name="PrefabsPlugin",this.dependencies=[Mn]}build(e){const t=e.getResource(Mn);e.insertResource(zn,new Bn(e.world,t))}}const $n=new Un;let Dn=null,Ln=0,Wn=0,On=0;const Hn=new Float32Array(256);function Xn(e){Dn=e,Ln=Dn._malloc(64),Wn=Dn._malloc(64),On=Dn._malloc(1024)}function Yn(){Dn&&(Ln&&(Dn._free(Ln),Ln=0),Wn&&(Dn._free(Wn),Wn=0),On&&(Dn._free(On),On=0)),Dn=null}function jn(){if(!Dn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Dn}const Nn={r:1,g:1,b:1,a:1},Vn={begin(e){const t=jn();try{t.HEAPF32.set(e,Ln/4),t.draw_begin(Ln)}catch(e){ze(e,"Draw.begin")}},end(){try{jn().draw_end()}catch(e){ze(e,"Draw.end")}},line(e,t,n,s=1){try{jn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.line")}},rect(e,t,n,s=!0){try{jn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{jn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{jn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{jn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circleOutline")}},texture(e,t,n,s=Nn){try{jn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ze(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Nn){try{jn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ze(e,"Draw.textureRotated")}},setLayer(e){jn().draw_setLayer(e)},setDepth(e){jn().draw_setDepth(e)},getDrawCallCount:()=>Dn?Dn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Dn?Dn.draw_getPrimitiveCount():0,setBlendMode(e){jn().draw_setBlendMode(e)},setDepthTest(e){jn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=jn();s.HEAPF32.set(n,Wn/4),s.draw_mesh(e,t,Wn)}catch(n){ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=jn(),i=Ft.get(t);if(!i)return;if(Vn.setBlendMode(i.blendMode),Vn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Vn.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,Wn/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Kn(t);if(!(s<0)){if(Pt(n))Hn[r++]=10,Hn[r++]=s,Hn[r++]=n.slot??e++,Hn[r++]=n.textureId;else if("number"==typeof n)Hn[r++]=1,Hn[r++]=s,Hn[r++]=n;else if(Array.isArray(n)){Hn[r++]=n.length,Hn[r++]=s;for(let e=0;e<n.length;e++)Hn[r++]=n[e]}else"w"in n?(Hn[r++]=4,Hn[r++]=s,Hn[r++]=n.x,Hn[r++]=n.y,Hn[r++]=n.z,Hn[r++]=n.w):"z"in n?(Hn[r++]=3,Hn[r++]=s,Hn[r++]=n.x,Hn[r++]=n.y,Hn[r++]=n.z):(Hn[r++]=2,Hn[r++]=s,Hn[r++]=n.x,Hn[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(Hn.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,Wn);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),On/4),s.draw_meshWithUniforms(e,i.shader,Wn,On,r)}catch(n){ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Gn={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},qn=new Set;function Kn(e){const t=Gn[e];return void 0!==t?t:(qn.has(e)||(qn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Gn).join(", ")}`)),-1)}const Jn=new Map;function Qn(e,t,n){Jn.set(e,{fn:t,scene:n??""})}function Zn(e){Jn.delete(e)}function es(){Jn.clear()}var ts;!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"}(ts||(ts={}));let ns=null,ss=0,is=0,rs=0;function os(e){ns=e,ss=ns._malloc(262144),is=ns._malloc(65536),rs=ns._malloc(256)}function as(){ns&&(ss&&ns._free(ss),is&&ns._free(is),rs&&ns._free(rs),ss=0,is=0,rs=0),ns=null}function ls(){if(!ns)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ns}const cs={create(e){const t=ls(),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,ss/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,rs,i).set(r),t.geometry_init(n,ss,s,rs,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=ls(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,ss/4),s.geometry_updateVertices(e,ss,i,n)},release(e){e>0&&ls().geometry_release(e)},isValid:e=>!(!ns||e<=0)&&ns.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return cs.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:ts.Float2},{name:"a_texCoord",type:ts.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return cs.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ts.Float2},{name:"a_texCoord",type:ts.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return cs.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ts.Float2},{name:"a_texCoord",type:ts.Float2}],indices:new Uint16Array(o)})}};let ds=null;function hs(e){ds=e}function us(){ds&&ps.isInitialized()&&ps.shutdown(),ds=null}function fs(){if(!ds)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return ds}const ps={init(e,t){try{return fs().postprocess_init(e,t)}catch(n){return ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{fs().postprocess_shutdown()}catch(e){ze(e,"PostProcess.shutdown")}},resize(e,t){try{fs().postprocess_resize(e,t)}catch(n){ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return fs().postprocess_addPass(e,t)}catch(t){return ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{fs().postprocess_removePass(e)}catch(t){ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{fs().postprocess_setPassEnabled(e,t)}catch(t){ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return fs().postprocess_isPassEnabled(e)}catch(t){return ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{fs().postprocess_setUniformFloat(e,t,n)}catch(n){ze(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{fs().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{fs().postprocess_begin()}catch(e){ze(e,"PostProcess.begin")}},end(){try{fs().postprocess_end()}catch(e){ze(e,"PostProcess.end")}},getPassCount(){try{return fs().postprocess_getPassCount()}catch(e){return ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!ds)return!1;try{return ds.postprocess_isInitialized()}catch(e){return ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{fs().postprocess_setBypass(e)}catch(e){ze(e,"PostProcess.setBypass")}},isBypassed(){if(!ds)return!0;try{return ds.postprocess_isBypassed()}catch(e){return ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ft.createShader(gs,"#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:()=>Ft.createShader(gs,"#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:()=>Ft.createShader(gs,"#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:()=>Ft.createShader(gs,"#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")},gs="#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 ys;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ys||(ys={}));let _s=null,ms=0;function ws(e){_s=e,ms=_s._malloc(64)}function xs(){_s&&ms&&(_s._free(ms),ms=0),_s=null}const vs={init(e,t){_s?.renderer_init(e,t)},resize(e,t){_s?.renderer_resize(e,t)},begin(e,t){if(_s&&ms)try{_s.HEAPF32.set(e,ms/4),_s.renderer_begin(ms,t??0)}catch(e){ze(e,"Renderer.begin")}},flush(){try{_s?.renderer_flush()}catch(e){ze(e,"Renderer.flush")}},end(){try{_s?.renderer_end()}catch(e){ze(e,"Renderer.end")}},submitSprites(e){if(_s)try{_s.renderer_submitSprites(e._cpp)}catch(e){ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(_s)try{_s.renderer_submitBitmapText(e._cpp)}catch(e){ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(_s)try{_s.renderer_submitSpine?.(e._cpp)}catch(e){ze(e,"Renderer.submitSpine")}},setStage(e){_s?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>_s?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){_s?.renderer_releaseTarget(e)},getTargetTexture:e=>_s?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>_s?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){_s?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){_s?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){_s?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){_s?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>_s?_s.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>_s?{drawCalls:_s.renderer_getDrawCalls(),triangles:_s.renderer_getTriangles(),sprites:_s.renderer_getSprites(),text:_s.renderer_getText(),spine:_s.renderer_getSpine?.()??0,meshes:_s.renderer_getMeshes(),culled:_s.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let bs=null;function Ss(e){bs=e}function Ms(){bs=null}const Ps={enable(){bs?.gl_enableErrorCheck(!0)},disable(){bs?.gl_enableErrorCheck(!1)},check:e=>bs?.gl_checkErrors(e)??0,diagnose(){bs?.renderer_diagnose()}};class Ts{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(vs.resize(s,i),ps.isInitialized()&&ps.getPassCount()>0&&ps.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),vs.setViewport(0,0,s,i),vs.clearBuffers(3),vs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),vs.submitSprites(t),vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):vs.submitSpine(t),vs.flush(),this.executeDrawCallbacks(n,r),vs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=e;vs.setViewport(s.x,s.y,s.w,s.h),vs.setScissor(s.x,s.y,s.w,s.h,!0),vs.clearBuffers(i),vs.setScissor(0,0,0,0,!1),vs.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),vs.submitSprites(t),vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,r):vs.submitSpine(t),vs.flush(),this.executeDrawCallbacks(n,r),vs.end()}executeDrawCallbacks(e,t){const n=Jn;if(n.size>0){Vn.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)}Vn.end();for(const e of s)Zn(e)}}}const Es="__scene_transition_overlay__";class Rs{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 Cs{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,ye,{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),Qn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=ps.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){ps.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,ye)){const n=this.app_.world.get(e,ye);n.persistent=t,this.app_.world.insert(e,ye,n)}}}class As{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??R.sceneTransitionDuration,i=t.color??{...R.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Qn(Es,()=>{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;Vn.setLayer(9999),Vn.setDepth(9999),Vn.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,Zn(Es),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Zn(Es),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 Rs(t);this.scenes_.set(e,n);const s=new Cs(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Mn)?this.app_.getResource(Mn):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 Rs(t);this.scenes_.set(e,n);const s=new Cs(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Mn)?this.app_.getResource(Mn):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,ye)){if(this.app_.world.get(e,ye).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())Zn(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{ps.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Mn)&&(i.assetServer=this.app_.getResource(Mn));const r=await tn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,ye,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Is(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(Mn)?this.app_.getResource(Mn):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)Ft.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,ae)){const t=n.get(e,ae);s.sprite=t.color.a,t.color.a=0,n.insert(e,ae,t),i=!0}if(n.has(e,pe)){const t=n.get(e,pe);s.spine=t.color.a,t.color.a=0,n.insert(e,pe,t),i=!0}if(n.has(e,fe)){const t=n.get(e,fe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,fe,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,ae)){const t=n.get(e,ae);t.color.a=s.sprite,n.insert(e,ae,t)}if(void 0!==s.spine&&n.has(e,pe)){const t=n.get(e,pe);t.color.a=s.spine,n.insert(e,pe,t)}if(void 0!==s.bitmapText&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.bitmapText,n.insert(e,fe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{ps.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 ks=Me(null,"SceneManager");function Is(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ks).getSceneStatus(t)&&n._fn(...s)}}}const Fs=ft([Te(ks),Pe(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Bs={name:"SceneManager",build(e){const t=new As(e);e.insertResource(ks,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ks),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ht.Startup,n),e.addSystemToSchedule(ht.Last,Fs)}};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 ot,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(ht.Last);else{this.runSchedule(ht.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ht.FixedPreUpdate),this.runSchedule(ht.FixedUpdate),this.runSchedule(ht.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new He,this.resources_=new Re;for(const e of Object.values(ht))"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(ht.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ht.Startup,e)}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 Be(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(ks).register(e),this}setInitialScene(e){return this.getResource(ks).setInitial(e),this}tick(e){this.runner_||(this.runner_=new mt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ce)||this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(ht.First),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new mt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup),this.lastTime_=u(),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=[Ms,xs,us,as,kt,Yn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ce);t.delta=e,t.elapsed+=e,t.frameCount++}}function Us(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const $s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ds(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case se.FixedWidth:return r;case se.FixedHeight:return o;case se.Expand:return Math.max(r,o);case se.Shrink:return Math.min(r,o);case se.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const Ls=[];function Ws(e){if(e<Ls.length)return Ls[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 Ls.push(t),t}function Os(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,ye);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===te.Orthographic){if(h=i.orthoSize,l){h=Ds(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=Xs(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=js(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=Vs(r.position.x,r.position.y,r.position.z),f=Ws(c.length);f.entity=e,f.viewProjection.set(qs(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const Hs=new Float32Array(16);function Xs(e,t,n,s,i,r){const o=Hs;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const Ys=new Float32Array(16);function js(e,t,n,s){const i=Ys;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const Ns=new Float32Array(16);function Vs(e,t,n){const s=Ns;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 Gs=new Float32Array(16);function qs(e,t){const n=Gs;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 Ks={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Js(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const _=Math.max(0,g-f),m=Math.max(0,y-p);return{originX:f+o.x*_,originY:p+o.y*m,width:_,height:m,rect:{left:f,bottom:p,right:g,top:y}}}const Qs=ee("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 Zs=null,ei=null;function ti(e,t){e.has(t,ae)||e.insert(t,ae,{texture:k,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 ni(e,t){switch(e){case Ks.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ks.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Ks.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 si(e,t){switch(e){case Ks.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Ks.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Ks.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 Ks.BottomToTop:case Ks.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function ri(e,t,n,s){if(!e.has(t,Qs))return;const i=e.get(t,Qs),r=ni(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Qs,i)}function oi(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function ai(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function li(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(ai(o.charCodeAt(0))&&s.length>0&&ai(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!ai(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function ci(e){let t=1;for(;t<e;)t*=2;return t}function di(e,t){let n=0,s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;n++,s=t}return n}function hi(e,t){if(Zs&&ei){const e=Zs.getUIRectComputedWidth(ei,t);if(e>0)return e}return e.size.x}function ui(e,t){if(Zs&&ei){const e=Zs.getUIRectComputedHeight(ei,t);if(e>0)return e}return e.size.y}function fi(e,t,n,s,i,r){if(!e.has(t,ae))return;const o=e.get(t,ae);let a,l;switch(n){case Ks.BottomToTop:case Ks.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,ae,o))}function pi(e,t,n){let s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function gi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function yi(e,t,n,s,i){if(!e.has(t,Qs))return;const r=e.get(t,Qs),o=Js(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,ae)){const n=e.get(t,ae);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,ie,n)}}function _i(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 mi=.1,wi=30,xi={r:.3,g:.5,b:.8,a:1},vi={Left:0,Center:1,Right:2},bi={Top:0,Middle:1,Bottom:2},Si={Visible:0,Clip:1,Ellipsis:2},Mi=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:vi.Left,verticalAlign:bi.Top,wordWrap:!0,overflow:Si.Visible,lineHeight:1.2});class Pi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(R.textCanvasSize,R.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,ci(this.frameMaxW_)),e.height=Math.max(e.height,ci(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ci(this.frameMaxW_),e.height=ci(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=li(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===Si.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,ci(f)),s.height=Math.max(s.height,ci(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),_=Math.round(255*e.color.b),m=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${_}, ${m})`,i&&e.overflow===Si.Clip&&(n.save(),n.beginPath(),n.rect(0,0,f,p),n.clip());const w=l.length*c;let x;if(i)switch(e.verticalAlign){case bi.Top:x=d;break;case bi.Middle:x=d+(p-2*d-w)/2;break;case bi.Bottom:x=p-w-d;break;default:x=d}else x=d;let v=x;for(const t of l){let s;switch(e.align){case vi.Left:s=d;break;case vi.Center:s=f/2;break;case vi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Si.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 vi.Left:return"left";case vi.Center:return"center";case vi.Right:return"right"}}}const Ti=_i({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?hi(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?ui(e.uiRect,e.entity):0});class Ei{build(e){Q("Text",Mi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Pi(t),s=e.world,i=new Map;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Mi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Mi)){if(s.valid(e)&&s.has(e,ae)){const t=s.get(e,ae);s.insert(e,ae,{texture:k,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([Mi]);for(const t of e){const e=s.get(t,Mi),r=s.has(t,Qs)?s.get(t,Qs):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Ti.changed(a,o)){if(s.has(t,ae)&&s.get(t,ae).texture!==k)continue}ti(s,t);const l=r?{size:{x:hi(r,t),y:ui(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,ae);s.insert(t,ae,{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,Ti.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ri=new Ei,Ci=0,Ai=1,ki=ee("UIMask",{enabled:!0,mode:Ci});function Ii(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function Fi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],_=e[14],m=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,M=r*d-o*c,P=h*y-u*g,T=h*_-f*g,E=h*m-p*g,R=u*_-f*y,C=u*m-p*y,A=f*m-p*_;let k=w*A-x*C+v*R+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*C+d*R)*k,n[1]=(r*C-i*A-o*R)*k,n[2]=(y*M-_*S+m*b)*k,n[3]=(f*S-u*M-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(_*v-g*M-m*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*C-l*E+d*P)*k,n[9]=(i*E-s*C-o*P)*k,n[10]=(g*S-y*v+m*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*R-c*P)*k,n[13]=(s*R-i*T+r*P)*k,n[14]=(y*x-g*b-_*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function Bi(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function zi(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function Ui(e,t){return 2*Math.atan2(e,t)}function $i(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function Di(e,t,n,s,i,r,o,a,l,c){const d=Ui(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function Li(e,t,n,s,i,r,o){if(!e.has(t,Qs)||!e.has(t,ie))return null;const a=e.get(t,Qs),l=e.get(t,ie),c=hi(a,t)*l.worldScale.x,d=ui(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),_=-d*p,m=d*(1-p),w=Ui(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-_*v,u+g*v+_*x],[h+y*x-_*v,u+y*v+_*x],[h+y*x-m*v,u+y*v+m*x],[h+g*x-m*v,u+g*v+m*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=$i(e,t,n,s,i,r,o);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 Wi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([ki]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,ki);n.enabled&&(h.add(e),n.mode===Ai?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;pi(t,e,e=>{if(i.has(e)){if(t.get(e,ki).mode===Ci)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,ki).mode===Ci){const e=Li(t,n,r,o,a,l,c);e&&(s=Ii(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Li(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;pi(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Oi{build(e){if(Q("UIMask",ki),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Wi(e.wasmModule,e.world))}}const Hi=new Oi,Xi=ee("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Yi=ee("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),ji={Normal:0,Hovered:1,Pressed:2,Disabled:3},Ni=Y("Button",{state:ji.Normal,transition:null});class Vi{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 Gi=Me(new Vi,"UIEvents");class qi{build(e){Q("UIRect",Qs);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Zs=e,ei=t}(n,s);e.addSystemToSchedule(ht.PreUpdate,ft([Pe(St)],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(ht.PostUpdate,ft([Pe(St)],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(ht.PostUpdate,ft([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ki=new qi;let Ji=!1,Qi=!1;function Zi(e){Ji=e}function er(){return Ji}function tr(){return!Ji}function nr(e){Qi=e}function sr(){return Qi}const ir=function(){const e=new Float32Array(16),t=new Float32Array(16);let n=!0;return{update(e){for(let s=0;s<16;s++)if(t[s]!==e[s]){t.set(e),n=!0;break}},getInverse:t=>(n&&(Fi(t,e),n=!1),e)}}();function rr(e,t,n,s){t.emit(n,s,n),pi(e,n,i=>{if(!e.has(i,Xi))return!1;const r=e.get(i,Xi);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class or{build(e){Q("Interactable",Xi),Q("Button",Ni);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Vi;e.insertResource(Gi,i);let r=null,o=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St)],(e,a)=>{if(i.drain(),er()&&!sr())return;const l=t.getEntitiesWithComponents([Yi]);for(const e of l){const n=t.get(e,Yi);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Yi,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;ir.update(a.viewProjection);const u=Bi(d,h,ir.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const _=n.uiHitTest_getHitEntity(),m=4294967295===_?null:_;if(null===r||t.valid(r)||(r=null),r!==m){if(null!==r&&t.valid(r)&&t.has(r,Yi)){const e=t.get(r,Yi);e.hovered=!1,t.insert(r,Yi,e),i.emit(r,"hover_exit")}if(null!==m){gi(t,m,Yi);const e=t.get(m,Yi);e.hovered=!0,t.insert(m,Yi,e),i.emit(m,"hover_enter")}r=m}if(g&&null!==m){const e=t.get(m,Yi);e.pressed=!0,e.justPressed=!0,t.insert(m,Yi,e),o=m,rr(t,i,m,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,Yi)){const e=t.get(o,Yi);e.pressed=!1,e.justReleased=!0,t.insert(o,Yi,e),rr(t,i,o,"release"),o===r&&rr(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ht.Update,ft([],()=>{const e=t.getEntitiesWithComponents([Ni]);for(const n of e){if(gi(t,n,Xi,{enabled:!0}),!t.has(n,Yi))continue;const e=t.get(n,Yi),s=t.get(n,Ni),i=t.get(n,Xi),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=ji.Pressed:e.hovered?s.state=ji.Hovered:s.state=ji.Normal:s.state=ji.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,ae)){const r=t.get(n,ae);r.color=oi(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,ae,r)}}},{name:"ButtonSystem"}))}}const ar=new or,lr=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}),cr=Y("Focusable",{tabIndex:0,isFocused:!1});class dr{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 hr=Me(new dr,"FocusManager");class ur{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Q("TextInput",lr),er()&&!sr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(R.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function g(){const t=e.getResource(hr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,lr)?s:null}const y=()=>{l||null===g()||v()},_=()=>{l=!0},m=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,lr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Gi).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,lr);s.focused=!1,s.dirty=!0;e.getResource(hr).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,lr);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(Gi).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=n.get(t,lr);e.focused=!1,e.dirty=!0}e.getResource(hr).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",m),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",m),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let M=null;function P(e,l,d,h){(i.width<d||i.height<h)&&(i.width=ci(Math.max(i.width,d)),i.height=ci(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=li(r,p,d-2*_);let t=_;for(const n of e)r.fillText(n,_,t),t+=y}else{const e=(h-l.fontSize)/2;r.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=li(r,l.value,d-2*_);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=_+r.measureText(c).width,n=_+o*y,s=y}else t=_+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const m=r.getImageData(0,0,d,h),w=new Uint8Array(m.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,ae);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,ae,S)}e.addSystemToSchedule(ht.Update,ft([Pe(hr)],e=>{const t=n.getEntitiesWithComponents([lr]);for(const e of t)gi(n,e,cr,{tabIndex:0,isFocused:!1}),gi(n,e,Xi,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,lr)){const e=n.get(M,lr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,lr);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(ht.PreUpdate,ft([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,lr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,lr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([lr,Qs]);for(const e of a){const t=n.get(e,lr);if(!t.dirty)continue;const s=n.get(e,Qs),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(ti(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const fr=new ur,pr={Simple:0,Sliced:1,Tiled:2,Filled:3},gr={Horizontal:0,Vertical:1},yr={Left:0,Right:1,Bottom:2,Top:3},_r=Y("Image",{texture:k,color:{r:1,g:1,b:1,a:1},imageType:pr.Simple,fillMethod:gr.Horizontal,fillOrigin:yr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),mr=_i({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?hi(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?ui(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const wr=new class{build(e){Q("Image",_r);const t=e.world,n=new Map;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,_r)||n.delete(e);const e=t.getEntitiesWithComponents([_r]);for(const s of e){const e=t.get(s,_r),i=t.has(s,Qs)?t.get(s,Qs):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!mr.changed(o,r))continue;ti(t,s);const a=t.get(s,ae);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=hi(i,s),a.size.y=ui(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===pr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===gr.Horizontal?e.fillOrigin===yr.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===yr.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===pr.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,ae,a),n.set(s,mr.take(r))}else a.color.a=0,t.insert(s,ae,a),n.set(s,mr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},xr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),vr=Y("ToggleGroup",{allowSwitchOff:!1});const br=new class{build(e){Q("Toggle",xr),Q("ToggleGroup",vr);const t=e.world,n=new Set;e.addSystemToSchedule(ht.Update,ft([Pe(Gi)],e=>{const s=t.getEntitiesWithComponents([xr]);if(!er()||sr()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,xr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,xr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,xr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(gi(t,n,Xi,{enabled:!0}),!t.has(n,Yi))continue;const s=t.get(n,Yi),i=t.get(n,xr),o=t.get(n,Xi);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,vr);if(i.isOn&&o){if(!t.get(s,vr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,xr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,xr);i.isOn&&(i.isOn=!1,t.insert(s,xr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,ae)){const e=t.get(n,ae);e.color=oi(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,ae,e)}}}for(const e of s){const n=t.get(e,xr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,ae)){const e=t.get(n.graphicEntity,ae);e.enabled=n.isOn,t.insert(n.graphicEntity,ae,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Sr=Ks,Mr=Y("ProgressBar",{value:0,fillEntity:0,direction:Ks.LeftToRight});function Pr(e,t,n,s){if(!e.has(t,Qs))return;const i=e.get(t,Qs),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=Js(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ae)){const n=e.get(t,ae);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie),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,ie,n))}}class Tr{build(e){Q("ProgressBar",Mr);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([Mr,Qs]);for(const n of e){const e=t.get(n,Mr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Qs),i=Math.max(0,Math.min(1,e.value));ri(t,e.fillEntity,e.direction,i);const r=hi(s,n),o=ui(s,n);Pr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Er=new Tr,Rr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Cr=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 Ar=new class{build(e){Q("Draggable",Rr),Q("DragState",Cr);const t=e.world,n=e.getResource(Gi);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St)],(e,o)=>{if(er()&&!sr())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Rr,Yi]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Rr).enabled)continue;if(t.get(s,Yi).hovered){let e=0;t.has(s,ae)&&(e=t.get(s,ae).layer);const i=di(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Cr)||t.insert(n,Cr);const e=t.get(n,Cr),r=t.get(n,ie);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Cr)){t.get(s,Cr).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(s,Rr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Cr).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Cr))return void(r=null);const s=t.get(r,Cr),i=t.get(r,Rr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,ie)){const e=function(e,t,n,s){if(!e.has(t,he))return{x:n,y:s};const i=e.get(t,he).entity;if(!e.valid(i)||!e.has(i,ie))return{x:n,y:s};const r=e.get(i,ie),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=Ui(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,ie);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,ie,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},kr=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 Ir(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 Fr(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const Br=new class{build(e){Q("ScrollView",kr);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ht.PostUpdate,ft([Pe(xt),Pe(St),Pe(Ce)],(e,i,r)=>{const o=er()&&!sr(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([kr,Qs]);for(const r of l){gi(t,r,ki,{enabled:!0,mode:Ci});const l=t.get(r,kr),c=t.get(r,Qs);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=hi(c,r),u=ui(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,ie))continue;const e=t.get(o,ie);let a=0,l=0,c=.5,d=.5;if(t.has(o,Qs)){const e=t.get(o,Qs);a=hi(e,o)||e.size.x,l=ui(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,ae)){const e=t.get(o,ae);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){gi(t,r,Xi,{enabled:!0,blockRaycast:!0});const n=t.has(r,Yi)?t.get(r,Yi):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=Ir(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=Ir(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Ir(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Ir(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Fr(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)<mi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>mi?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Fr(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)<mi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>mi?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ie)){const e=t.get(l.contentEntity,ie),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,ie,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},zr=Ks,Ur=Y("Slider",{value:0,minValue:0,maxValue:1,direction:Ks.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function $r(e,t,n,s,i,r){const o=hi(s,i)*n.worldScale.x,a=ui(s,i)*n.worldScale.y,l=Ui(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case Ks.LeftToRight:return o>0?(f-g)/o:0;case Ks.RightToLeft:return o>0?1-(f-g)/o:0;case Ks.BottomToTop:return a>0?(p-y)/a:0;case Ks.TopToBottom:return a>0?1-(p-y)/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 Ks.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Ks.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Ks.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Ks.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Lr{build(e){Q("Slider",Ur);const t=e.world;let n=null;e.addSystemToSchedule(ht.PreUpdate,ft([Pe(xt),Pe(St),Pe(Gi)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([Ur,Qs]);for(const o of r){const r=t.get(o,Ur),a=t.get(o,Qs);if(!er()||sr()){if(t.has(o,ie)){gi(t,o,Xi,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&gi(t,r.handleEntity,Xi,{enabled:!0,blockRaycast:!1});const l=t.get(o,ie),c=t.has(o,Yi)?t.get(o,Yi):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Yi)&&(d=t.get(r.handleEntity,Yi).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=$r(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,Ur,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=hi(a,o),h=ui(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(ri(t,r.fillEntity,r.direction,c),yi(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Qs)){const e=t.get(r.handleEntity,Qs);Dr(e,r.direction,c),t.insert(r.handleEntity,Qs,e),yi(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Wr=new Lr;const Or=new class{build(e){Q("Focusable",cr);const t=e.world,n=new dr;e.insertResource(hr,n),e.addSystemToSchedule(ht.Update,ft([Pe(xt),Pe(Gi)],(e,s)=>{if(er()&&!sr())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([cr]);for(const e of i){if(!t.has(e,Yi))continue;t.get(e,Yi).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Xi)){if(!t.get(n,Xi).enabled)continue}const s=t.get(n,cr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,cr)){t.get(i,cr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,cr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Hr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Xr(){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){Q("SafeArea",Hr);const t=e.world;let n=Xr(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Xr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Xr(),s=!0});e.addSystemToSchedule(ht.PreUpdate,ft([Pe(St)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([Hr,Qs]);for(const e of d){const s=t.get(e,Hr),i=t.get(e,Qs),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,Qs,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},jr=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Nr=null;function Vr(e,t){if(!Nr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Nr.get(e);n?n.renderer=t:Nr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const Gr=new class{build(e){Q("ListView",jr);const t=e.world,n=new Map;Nr=n,e.addSystemToSchedule(ht.PostUpdate,ft([Pe(xt)],e=>{const s=er()&&!sr();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([jr,Qs]);for(const r of i){gi(t,r,Xi,{enabled:!0,blockRaycast:!0}),gi(t,r,ki,{enabled:!0,mode:Ci});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,jr),a=t.get(r,Qs),l=ui(a,r),c=hi(a,r);if(!s){const n=t.has(r,Yi)?t.get(r,Yi):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,ge,{value:`ListItem_${e}`}),t.insert(n,Qs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,ie)){const s=t.get(n,ie);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,ie,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},qr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Kr=new class{build(e){Q("Dropdown",qr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,ie))return;const n=t.get(e,ie);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,ie,{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,ae)){const n=t.get(e,ae);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,ae,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,ae),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*wi;t.insert(i,Qs,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,ie,{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,ae,{texture:k,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*wi;t.insert(r,ge,{value:`Option_${e}`}),t.insert(r,Qs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*wi},offsetMax:{x:0,y:0},size:{x:o,y:wi},pivot:{x:.5,y:.5}}),t.insert(r,ie,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,ae,{texture:k,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:wi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,Xi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,ie,{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,Mi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:vi.Left,verticalAlign:bi.Middle,wordWrap:!1,overflow:Si.Clip,lineHeight:1.2}),t.insert(c,Qs,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:wi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Mi))return;const s=t.get(n,Mi);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Mi,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,Xi)&&t.insert(e,Xi,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,ae))){const s=t.get(e,ae);t.insert(e,ae,{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,ae))continue;const i=n===e.highlightIndex?{...xi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,ae,{texture:k,color:i,size:{x:e.ddWidth,y:wi},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,Yi))continue;if(t.get(n,Yi).hovered)return!0}return!1}e.addSystemToSchedule(ht.Update,ft([Pe(xt),Pe(Gi)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=er()&&!sr(),p=t.getEntitiesWithComponents([qr]);for(const g of p){const p=t.get(g,qr);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;gi(t,g,Xi,{enabled:!0,blockRaycast:!0});const _=t.has(g,Yi)?t.get(g,Yi):null;if(_?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,Yi))continue;if(t.get(n,Yi).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,Yi))continue;if(t.get(s,Yi).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(_?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Jr=0,Qr=0,Zr=2,eo=Y("LayoutGroup",{direction:Jr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Qr,reverseOrder:!1});const to=new class{build(e){Q("LayoutGroup",eo);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,ft([],()=>{const e=t.getEntitiesWithComponents([eo,Qs,ue]);for(const n of e){const e=t.get(n,eo),s=t.get(n,Qs),i=t.get(n,ue);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,Qs)&&t.has(e,ie)&&r.push({entity:e,rect:t.get(e,Qs)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=hi(s,n),a=ui(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===Jr;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=hi(s.rect,s.entity),f=ui(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,_;h?(y=-l*o+d.left+u+p*i,_=e.childAlignment===Qr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===Zr?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===Qr?-l*o+d.left+p*i:e.childAlignment===Zr?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,_=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const m=t.get(s.entity,ie);m.position.x=y,m.position.y=_,t.insert(s.entity,ie,m)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};ee("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),ee("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class no{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ht.PostUpdate,ft([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const so=new no;async function io(e,t,n){const s=e.getResource(ks);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function ro(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 oo=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ao=Me(null,"PhysicsAPI");function lo(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function co(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ho{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(oo,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=ro(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([ce]);for(const n of t){const t=e.world.get(n,ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(ht.PostUpdate,ft([Pe(Ce)],a=>{const l=o.getEntitiesWithComponents([me,ie]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,me),l=o.get(i,ie);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=lo(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),uo(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===be.Kinematic){const e=lo(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,ie);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,he)){const t=e.world.get(o,he);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ie)){const n=e.world.get(t.entity,ie),s=lo(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=co(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,ie,d)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(oo,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(ao,fo._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function uo(e,t,n){const s=e.world;if(s.has(n,we)){const e=s.get(n,we);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,xe)){const e=s.get(n,xe);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,ve)){const e=s.get(n,ve);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 fo{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(fo.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 po={nearest:0,linear:1},go={repeat:0,clamp:1,mirror:2};function yo(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=po[s.filterMode??"linear"]??1,a=go[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function _o(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 mo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,_=l*u,m=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(_+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(m+x)*r,0,(y+v)*o,(m-x)*o,(1-(p+_))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function wo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Vt(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=yo(e,await n.loadPixels(r),!0,t)}catch{s[r]=0}}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let d={},h=null;if(i&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=Gt(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===un(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=_o(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=yo(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...P},fixedTimestep:o?.fixedTimestep??T,subStepCount:o?.subStepCount??4};new ho("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Vt(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=un(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=yo(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Vt(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=Ft.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Ft.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Vt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,u,f);const p=en(e.world,n);if(l&&e.hasResource(ks))for(const t of p.values())e.world.insert(t,ye,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=Gt(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=M);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,pe)?c.get(r,pe):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,ie)){const e=mo(c.get(r,ie),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),_=new Uint16Array(n.HEAPU8.buffer,d,r),m=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,m>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(_),t.renderer_submitTriangles(m,i,w,r,p,g,u),t._free(m),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(Mn);t&&t.setAddressableManifest(a)}}function xo(e,t,n){return{name:e,async setup(){await wo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class vo{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,n=new Set,s=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Gt(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===un(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Vt(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=un(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const bo="__preview__";class So{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(ks);t.register({name:bo,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(bo),this.loadPromise_=t.load(bo).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new vo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await wo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,bo)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([le]);for(const s of n){if(e.get(s,le).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([ce]);for(const i of s){const s=e.get(i,ce);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(ks).getScene(bo),r=i?i.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,ie,o);const a={isActive:!0,projectionType:te.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ne.ColorAndDepth};e.insert(r,le,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(ks);await e.switchTo(bo),console.log("[PreviewPlugin] Scene reloaded successfully")}catch(e){const t=e instanceof Error?e.message:String(e);console.error(`[PreviewPlugin] Failed to reload scene: ${t}`)}}}const Mo={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),n=vs.createRenderTarget(e.width,e.height,t);return{_handle:n,textureId:vs.getTargetTexture(n),width:e.width,height:e.height}},release(e){vs.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(vs.releaseRenderTarget(e._handle),Mo.create({width:t,height:n,depth:!0})),begin(e,t){vs.begin(t,e._handle)},end(){vs.end()},getDepthTexture:e=>vs.getTargetDepthTexture(e._handle)};var Po;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Po||(Po={}));class To{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Po[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Po.Debug:console.debug(t,n);break;case Po.Info:console.log(t,n);break;case Po.Warn:console.warn(t,n);break;case Po.Error:console.error(t,n)}}}class Eo{constructor(){this.handlers_=[],this.minLevel_=Po.Info,this.addHandler(new To)}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(Po.Debug,e,t,n)}info(e,t,n){this.log(Po.Info,e,t,n)}warn(e,t,n){this.log(Po.Warn,e,t,n)}error(e,t,n){this.log(Po.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 Ro=new Eo;function Co(){return Ro}function Ao(e){Ro.setMinLevel(e)}function ko(e,t,n){Ro.debug(e,t,n)}function Io(e,t,n){Ro.info(e,t,n)}function Fo(e,t,n){Ro.warn(e,t,n)}function Bo(e,t,n){Ro.error(e,t,n)}const zo=[Ri,Hi,Ki,wr,Er,ar,Ar,Br,Wr,br,fr,Or,Yr,Gr,Kr,to,so];function Uo(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(),Xn(e),At(e),os(e),hs(e),ws(e),Ss(e);const i=new Ts;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=Os(e,s,t,i));const o=n.getResource(St);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(St,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;vs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(vs.resize(t,l),ps.isInitialized()&&ps.getPassCount()>0&&!ps.isBypassed()&&ps.resize(t,l),n.hasResource(ks)){const e=n.getResource(ks).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Os(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:$s,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}vs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ht.First,l),n.addSystemToSchedule(ht.Last,c),n.addPlugin(Tn),n.addPlugin($n),n.addPlugin(bt),n.addPlugin(Bs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:zo,...t})}e=p;export{je as Added,zs as App,Pn as AssetPlugin,En as AssetRefCounter,Sn as AssetServer,Mn as Assets,Ht as AsyncCache,fe as BitmapText,Mt as BlendMode,be as BodyType,we as BoxCollider,Ni as Button,ji as ButtonState,le as Camera,ce as Canvas,ve as CapsuleCollider,Ne as Changed,ue as Children,xe as CircleCollider,ne as ClearFlags,tt as Commands,st as CommandsInstance,y as DEFAULT_DESIGN_HEIGHT,g as DEFAULT_DESIGN_WIDTH,M as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,P as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,_ as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,w as DEFAULT_SPRITE_SIZE,m as DEFAULT_TEXT_CANVAS_SIZE,ts as DataType,Cr as DragState,Rr as Draggable,Vn as Draw,qr as Dropdown,nt as EntityCommands,lt as EventReader,dt as EventReaderInstance,ot as EventRegistry,at as EventWriter,ct as EventWriterInstance,Ks as FillDirection,gr as FillMethod,yr as FillOrigin,hr as FocusManager,dr as FocusManagerState,cr as Focusable,Ps as GLDebug,cs as Geometry,A as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,k as INVALID_TEXTURE,_r as Image,pr as ImageType,xt as Input,vt as InputPlugin,wt as InputState,Xi as Interactable,jr as ListView,re as LocalTransform,Po as LogLevel,Eo as Logger,Ft as Material,Xt as MaterialLoader,Xe as Mut,ge as Name,he as Parent,fo as Physics,oo as PhysicsEvents,ho as PhysicsPlugin,ps as PostProcess,Bn as PrefabServer,zn as Prefabs,Un as PrefabsPlugin,So as PreviewPlugin,Mr as ProgressBar,Sr as ProgressBarDirection,Tr as ProgressBarPlugin,te as ProjectionType,Je as Query,Qe as QueryInstance,Ze as Removed,et as RemovedQueryInstance,Ts as RenderPipeline,ys as RenderStage,Mo as RenderTexture,vs as Renderer,Pe as Res,Te as ResMut,me as RigidBody,R as RuntimeConfig,Hr as SafeArea,se as ScaleMode,ks as SceneManager,As as SceneManagerState,ye as SceneOwner,ht as Schedule,kr as ScrollView,Ot as ShaderSources,Ur as Slider,zr as SliderDirection,Lr as SliderPlugin,pe as SpineAnimation,ae as Sprite,mt as SystemRunner,Mi as Text,vi as TextAlign,lr as TextInput,ur as TextInputPlugin,Si as TextOverflow,Ei as TextPlugin,Pi as TextRenderer,bi as TextVerticalAlign,Ce as Time,xr as Toggle,ie as Transform,St as UICameraInfo,Vi as UIEventQueue,Gi as UIEvents,Yi as UIInteraction,or as UIInteractionPlugin,qi as UILayoutPlugin,ki as UIMask,Oi as UIMaskPlugin,Qs as UIRect,no as UIRenderOrderPlugin,de as Velocity,vo as WebAssetProvider,He as World,oe as WorldTransform,yt as addStartupSystem,gt as addSystem,_t as addSystemToSchedule,ri as applyDirectionalFill,C as applyRuntimeConfig,Tn as assetPlugin,es as clearDrawCallbacks,V as clearUserComponents,$ as color,ni as computeFillAnchors,ii as computeFillSize,si as computeHandleAnchors,Js as computeUIRectLayout,Wi as createMaskProcessor,xo as createRuntimeSceneConfig,Uo as createWebApp,ko as debug,Y as defineComponent,it as defineEvent,Me as defineResource,ft as defineSystem,j as defineTag,Bo as error,on as findEntityByName,Us as flushPendingSystems,pn as getAddressableType,gn as getAddressableTypeByEditorType,_n as getAllAssetExtensions,vn as getAssetMimeType,un as getAssetTypeEntry,Z as getComponent,Vt as getComponentAssetFieldDescriptors,Nt as getComponentAssetFields,_e as getComponentDefaults,Jt as getComponentEntityFields,Gt as getComponentSpineFieldDescriptor,wn as getCustomExtensions,fn as getEditorType,Co as getLogger,t as getPlatform,s as getPlatformType,N as getUserComponent,xn as getWeChatPackOptions,Io as info,Xn as initDrawAPI,Ss as initGLDebugAPI,os as initGeometryAPI,At as initMaterialAPI,hs as initPostProcessAPI,ws as initRendererAPI,bt as inputPlugin,Cn as instantiatePrefab,Ii as intersectRects,Fi as invertMatrix4,K as isBuiltinComponent,bn as isCustomExtension,er as isEditor,yn as isKnownAssetExtension,n as isPlatformInitialized,sr as isPlayMode,tr as isRuntime,Pt as isTextureRef,i as isWeChat,r as isWeb,sn as loadComponent,ro as loadPhysicsModule,wo as loadRuntimeScene,en as loadSceneData,tn as loadSceneWithAssets,mn as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Di as pointInOBB,zi as pointInWorldRect,$n as prefabsPlugin,Er as progressBarPlugin,D as quat,Q as registerComponent,jt as registerComponentAssetFields,Kt as registerComponentEntityFields,Qn as registerDrawCallback,Rn as registerEmbeddedAssets,Wt as registerMaterialCallback,Qt as remapEntityFields,Bs as sceneManagerPlugin,Bi as screenToWorld,Zi as setEditorMode,Vr as setListViewRenderer,Ao as setLogLevel,nr as setPlayMode,Be as setWasmErrorHandler,Yn as shutdownDrawAPI,Ms as shutdownGLDebugAPI,as as shutdownGeometryAPI,kt as shutdownMaterialAPI,us as shutdownPostProcessAPI,xs as shutdownRendererAPI,Wr as sliderPlugin,fi as syncFillSpriteSize,fr as textInputPlugin,Ri as textPlugin,io as transitionTo,ar as uiInteractionPlugin,Ki as uiLayoutPlugin,Hi as uiMaskPlugin,zo as uiPlugins,so as uiRenderOrderPlugin,G as unregisterComponent,Zn as unregisterDrawCallback,rn as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,Fo as warn,Is 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 r(){return"web"===e?.name}async function o(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function d(e,n){return t().instantiateWasm(e,n)}function h(e,n){return t().createCanvas(e,n)}function u(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}const p=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const n=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),s={};return n.headers.forEach((e,t)=>{s[t]=e}),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text(),arrayBuffer:()=>n.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async instantiateWasm(e,t){let n;n="string"==typeof e?await this.readFile(e):e;const s=await WebAssembly.instantiate(n,t);return{instance:s.instance,module:s.module}}createImage(){return new Image}createCanvas(e,t){let n;return n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),n.width=e,n.height=t,n}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t??document.querySelector("canvas")??document.body,s=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),r=t=>{const n=t;e.onPointerMove(n.offsetX,n.offsetY)},o=t=>{const n=t;e.onPointerDown(n.button,n.offsetX,n.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerDown(0,s.clientX-t.left,s.clientY-t.top)}},c=t=>{const s=t.touches[0];if(s){const t=n.getBoundingClientRect();e.onPointerMove(s.clientX-t.left,s.clientY-t.top)}},d=()=>{e.onPointerUp(0)},h=t=>{const n=t;let s=n.deltaX,i=n.deltaY;1===n.deltaMode?(s*=16,i*=16):2===n.deltaMode&&(s*=window.innerWidth,i*=window.innerHeight),e.onWheel(s,i)};document.addEventListener("keydown",s),document.addEventListener("keyup",i),n.addEventListener("mousemove",r),n.addEventListener("mousedown",o),document.addEventListener("mouseup",a),n.addEventListener("touchstart",l),n.addEventListener("touchmove",c),n.addEventListener("touchend",d),n.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",s),document.removeEventListener("keyup",i),n.removeEventListener("mousemove",r),n.removeEventListener("mousedown",o),document.removeEventListener("mouseup",a),n.removeEventListener("touchstart",l),n.removeEventListener("touchmove",c),n.removeEventListener("touchend",d),n.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},g=1920,y=1080,_=100,m=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",R={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function C(e){e.Text&&(e.Text._default.fontFamily=R.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=R.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=R.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=R.canvasMatchWidthOrHeight)}const A=0,k=4294967295,I=4294967295,F=0,B=(e=0,t=0)=>({x:e,y:t}),z=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),U=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),$=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),D=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function L(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(L);const t={};for(const n in e)t[n]=L(e[n]);return t}let W=0;function O(e,t){const n=++W,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?{...L(t),...e}:L(t):e?{...t,...e}:{...t}}}const H=new Map;function X(){return"undefined"==typeof window?H:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function Y(e,t){const n=J.get(e)??X().get(e);if(n)return n;const s=O(e,t);return X().set(e,s),J.set(e,s),q(e,t,!1),s}function j(e){const t=J.get(e)??X().get(e);if(t)return t;const n=O(e,{});return X().set(e,n),J.set(e,n),q(e,{},!0),n}function N(e){return X().get(e)}function V(){const e=X();for(const t of e.keys())J.delete(t);e.clear()}function G(e){X().delete(e),J.delete(e)}function q(e,t,n){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,n)}function K(e){return!0===e._builtin}const J=new Map;function Q(e,t){J.set(e,t)}function Z(e){return J.get(e)??N(e)}function ee(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return J.set(e,n),n}const te={Perspective:0,Orthographic:1},ne={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},se={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ie=ee("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=ie,oe=ie,ae=ee("Sprite",{texture:k,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}),le=ee("Camera",{projectionType:te.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:ne.ColorAndDepth}),ce=ee("Canvas",{designResolution:{x:g,y:y},pixelsPerUnit:100,scaleMode:se.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),de=ee("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),he=ee("Parent",{entity:0}),ue=ee("Children",{entities:[]}),fe=ee("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:I,enabled:!0}),pe=ee("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ge=Y("Name",{value:""}),ye=Y("SceneOwner",{scene:"",persistent:!1});function _e(e){const t=Z(e);return t?L(t._default):null}const me=ee("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),we=ee("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),xe=ee("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ve=ee("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),be={Static:0,Kinematic:1,Dynamic:2};let Se=0;function Me(e,t){const n=++Se;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function Pe(e){return{_type:"res",_resource:e}}function Te(e){return{_type:"res_mut",_resource:e}}class Ee{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 Ee(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Ce=Me({delta:0,elapsed:0,frameCount:0},"Time");function Ae(e,t,n){const s=[];for(const[e,i]of Object.entries(n)){if(!(e in t)){s.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const n=ke(t[e]),r=ke(i);"null"!==n&&"undefined"!==n&&(n!==r&&null!=i&&s.push({field:e,expected:n,actual:r,value:i}))}return s}function ke(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ie(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 Fe=null;function Be(e){Fe=e}function ze(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Fe&&Fe(e,t)}function Ue(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 $e=1;const De=new WeakMap;function Le(e){let t=De.get(e);return void 0===t&&(t=$e++,De.set(e,t)),t}const We=[];function Oe(e,t=[],n=[]){We.length=0;for(const t of e)We.push(Le(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(Le(e));We.sort((e,t)=>e-t),s+="|+"+We.join(",")}if(n.length>0){We.length=0;for(const e of n)We.push(Le(e));We.sort((e,t)=>e-t),s+="|-"+We.join(",")}return s}class He{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.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 ze(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_;return this.entities_.set(e,t),this.worldVersion_++,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){ze(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)}}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){ze(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){ze(t,`removeParent(entity=${e})`)}}insert(e,t,n){return K(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(K(t)){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,Ue(n))}catch(n){ze(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 K(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return K(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(K(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return ze(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.");K(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],r=n[`has${e}`],o=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&(s[e]=t);const e=Ae(t._name,t._default,s);if(e.length>0)throw new Error(Ie(t._name,e))}const i={...t._default,...s};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Ue(i))}catch(n){ze(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],r=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==r||"object"!=typeof r||Array.isArray(r))s[n]=i;else{const e=i,t=r;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return ze(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 ze(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){ze(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=Ae(t._name,t._default,e);if(i.length>0)throw new Error(Ie(t._name,i));s=e}const i=t.create(s),r=this.getStorage(t),o=!r.has(e);r.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),o&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of J)if(K(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=X();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??Oe(e,t,n),r=this.queryCache_.get(i);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const t of e)if(!K(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=o?o.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Xe(e){return{_type:"mut",_component:e}}function Ye(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function je(e){return{_filterType:"added",_component:e}}function Ne(e){return{_filterType:"changed",_component:e}}function Ve(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Ge(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function qe(e){return Ye(e)||Ve(e)||Ge(e)?e._component:e}function Ke(e,t=[],n=[]){const s=[],i=[],r=[];return e.forEach((e,t)=>{Ye(e)&&s.push(t),Ve(e)?i.push({index:t,component:e._component}):Ge(e)&&r.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:r,with:(...s)=>Ke(e,[...t,...s],n),without:(...s)=>Ke(e,t,[...n,...s])}}function Je(...e){return Ke(e)}class Qe{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(qe),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_=Oe(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const d of n)if(!r||this.passesChangeFilters_(d)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}o[0]=d;for(let e=0;e<s;e++)o[e+1]=this.world_.get(d,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=o[e[t]+1];c=d}yield o}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Ze(e){return{_type:"removed",_component:e}}class et{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 tt(){return{_type:"commands"}}class nt{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=K(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 st{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new nt(this,null);return this.spawned_.push(e),e}entity(e){return new nt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const n of e.components)this.world_.insert(t,n.component,n.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function it(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 ot{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 at(e){return{_type:"event_writer",_event:e}}function lt(e){return{_type:"event_reader",_event:e}}class ct{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class dt{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ht;function ut(){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"}(ht||(ht={}));let ft=0;function pt(e,t,n){const s=++ft;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function gt(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function yt(e){gt().push({schedule:ht.Update,system:e})}function _t(e){gt().push({schedule:ht.Startup,system:e})}function mt(e,t){gt().push({schedule:e,system:t})}class wt{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 st&&t[e].flush()}finally{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 st(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 ct(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(n)}case"removed":{const t=e;return new et(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class xt{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 vt=Me(new xt,"Input");class bt{constructor(e){this.target_=e??null}build(e){const n=new xt;e.insertResource(vt,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(ht.Last,pt([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const St=new bt,Mt=Me({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var Pt;function Tt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}!function(e){e[e.Normal=0]="Normal",e[e.Additive=1]="Additive",e[e.Multiply=2]="Multiply",e[e.Screen=3]="Screen",e[e.PremultipliedAlpha=4]="PremultipliedAlpha"}(Pt||(Pt={}));let Et=null,Rt=null,Ct=1;const At=new Map;function kt(e){Et=e,Rt=e.getResourceManager(),Ot()}function It(){0!==Ut&&Et&&(Et._free(Ut),Ut=0),At.clear(),Ct=1,zt=!1,Dt.clear(),Lt=null,Rt=null,Et=null}function Ft(){if(!Rt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Rt}const Bt={createShader:(e,t)=>Ft().createShader(e,t),releaseShader(e){e>0&&Ft().releaseShader(e)},create(e){const t=Ct++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Pt.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 At.set(t,n),t},get:e=>At.get(e),setUniform(e,t,n){const s=At.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,Et?.invalidateMaterialCache(e))},getUniform(e,t){const n=At.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=At.get(e);n&&(n.blendMode=t,Et?.invalidateMaterialCache(e))},getBlendMode(e){const t=At.get(e);return t?.blendMode??Pt.Normal},setDepthTest(e,t){const n=At.get(e);n&&(n.depthTest=t,Et?.invalidateMaterialCache(e))},getShader(e){const t=At.get(e);return t?.shader??0},release(e){At.delete(e),Et?.invalidateMaterialCache(e)},isValid:e=>At.has(e),releaseAll(){At.clear(),Et?.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??Pt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=At.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=Ct++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return At.set(n,s),n},toAssetData(e,t){const n=At.get(e);if(!n)return null;const s={};for(const[e,t]of n.uniforms)s[e]=t;return{version:"1.0",type:"material",shader:t,blendMode:n.blendMode,depthTest:n.depthTest,properties:s}},getUniforms(e){const t=At.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let zt=!1,Ut=0;const $t=16384,Dt=new Map;let Lt=null;function Wt(e){const t=(0===Ut&&Et&&(Ut=Et._malloc($t)),Ut);if(0===t||!Et)return{ptr:0,count:0};let n=0,s=0;const i=Et.HEAPU8,r=Et.HEAPU32,o=Et.HEAPF32;for(const[a,l]of e){if(Tt(l))continue;let e=Dt.get(a);e||(Lt||(Lt=new TextEncoder),e=Lt.encode(a),Dt.set(a,e));const c=e.length,d=4*Math.ceil(c/4);if(n+(4+d+4+16)>$t){console.warn(`[ESEngine] Material uniform buffer full (${n}/${$t} bytes), skipping remaining uniforms`);break}r[t+n>>2]=c,n+=4,i.set(e,t+n),n+=d;let h=0,u=[0,0,0,0];if("number"==typeof l)h=0,u[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)u[e]=l[e]}else"w"in l?(h=3,u=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,u=[l.x,l.y,l.z,0]):"y"in l&&(h=1,u=[l.x,l.y,0,0]);r[t+n>>2]=h,n+=4;for(let e=0;e<4;e++)o[t+n>>2]=u[e],n+=4;s++}return{ptr:t,count:s}}function Ot(){if(!Et||zt)return;Et.materialDataProvider=(e,t,n,s,i)=>{const r=At.get(e);if(!r)return Et.HEAPU32[t>>2]=0,Et.HEAPU32[n>>2]=0,Et.HEAPU32[s>>2]=0,void(Et.HEAPU32[i>>2]=0);Et.HEAPU32[t>>2]=r.shader,Et.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Wt(r.uniforms);Et.HEAPU32[s>>2]=o,Et.HEAPU32[i>>2]=a},zt=!0}const Ht={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Xt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,n=3e4){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.pending_.get(e);if(i&&!i.aborted)return i.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const s=t(),i=await(n>0?Promise.race([s,new Promise((t,s)=>setTimeout(()=>{r.aborted=!0,s(new Error(`AsyncCache timeout: ${e} (${n}ms)`))},n))]):s);return r.aborted||this.cache_.set(e,i),this.pending_.delete(e),i})(),this.pending_.set(e,r);try{return await r.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Yt{constructor(e,t=""){this.cache_=new Xt,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&&(Bt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Bt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),r=await this.shaderLoader_.load(i);return{handle:Bt.createFromAsset(s,r),shaderHandle:r,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}const jt=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"}]}]]);function Nt(e,t){jt.set(e,t)}function Vt(e){const t=jt.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 Gt(e){return jt.get(e)?.fields??[]}function qt(e){return jt.get(e)?.spine??null}const Kt=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Jt(e,t){Kt.set(e,t)}function Qt(e){return Kt.get(e)}function Zt(e,t){const n=Kt.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const r=t.get(n);void 0===r&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==r?r:0}}}function en(e,t){const n=new Map;for(const s of t.entities){if(!1===s.visible)continue;const t=e.spawn();n.set(s.id,t),e.insert(t,ge,{value:s.name})}for(const s of t.entities){if(!1===s.visible)continue;const t=n.get(s.id);for(const i of s.components)Zt(i,n),rn(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 tn(e,t){return en(e,t)}async function nn(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl,r=new Map;s&&await async function(e,t,n,s,i){e=JSON.parse(JSON.stringify(e));const r=new Map;for(const e of sn.keys())r.set(e,new Set);const o=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=jt.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),o.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&r.get(e.type)?.add(t)}}const l=new Map,c=[...sn.entries()].map(async([e,i])=>{const o=await i.load(r.get(e),t,n,s);l.set(e,o)}),d=o.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...d]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=r.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=jt.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&(n[e.field]=l.get(e.type)?.get(t)??0)}}}(t,s,i,r,n?.collectAssets);const o=en(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=r.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return o}const sn=new Map([["texture",{async load(e,t,n,s){const i=new Map,r=[...e].map(async e=>{try{const r=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(r);i.set(e,o.handle),s.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(r),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}]]);function rn(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=Z(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 on(e,t){const n=e.getEntitiesWithComponents([le]);for(const s of n){const n=e.get(s,le);n&&(n.aspectRatio=t,e.insert(s,le,n))}}function an(e,t){const n=e.getEntitiesWithComponents([ge]);for(const s of n){const n=e.get(s,ge);if(n&&n.value===t)return s}return null}const ln=[{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}],cn={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",bmfont:"application/json",fnt:"text/plain"},dn=new Map,hn=new Set;for(const e of ln)for(const t of e.extensions)dn.set(t,e),hn.add(t);function un(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function fn(e){return dn.get(un(e))}function pn(e){return fn(e)?.editorType??"unknown"}function gn(e){return fn(e)?.addressableType??null}function yn(e){for(const t of ln)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function _n(e){return hn.has(e.toLowerCase())}function mn(){return hn}function wn(e){return"string"==typeof e&&(!!e.includes("/")&&_n(un(e)))}function xn(){const e=[];for(const t of ln)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function vn(){return xn().map(e=>({type:"suffix",value:e}))}function bn(e){return cn[e.toLowerCase()]}function Sn(e){const t=fn(e);return t?.wechatPackInclude??!1}class Mn{constructor(e){this.textureCache_=new Xt,this.shaderCache_=new Xt,this.jsonCache_=new Xt,this.textCache_=new Xt,this.binaryCache_=new Xt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Xt,this.prefabCache_=new Xt,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.module_=e,this.canvas_=h(R.textCanvasSize,R.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new Yt(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const r=(this.textureRefCounts_.get(s)??1)-1;r<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,r)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Bt.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),r=await this.fetchText(i);if(!this.writeToVirtualFS(t,r))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(r),l=[];for(const e of a){const t=o?`${o}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),d="binary"===fn(e)?.contentType,h=d?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(h,r,d);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=fn(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),r=i?`${i}/${s}`:s,o=await this.loadTextureRaw(r);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return nn(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 n=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(n);if(this.embeddedOnly_&&!s)throw new Error(`Asset not embedded: ${e}`);const i=s??n;return new Promise((n,s)=>{const r=t().createImage();r.crossOrigin="anonymous",r.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(r,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(r)},r.onerror=()=>s(new Error(`Failed to load image: ${e}`)),r.src=i})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=r;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),r=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(r);const o=this.module_.getResourceManager(),a=this.module_._malloc(r.length);this.module_.HEAPU8.set(r,a);const l=o.createTexture(t,n,a,r.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(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 Bt.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:r}=this.parseEsShader(s);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return Bt.createShader(i,r)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.embedded_.get(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Pn=Me(null,"Assets");class Tn{build(e){const t=e.wasmModule;t?e.insertResource(Pn,new Mn(t)):console.warn("AssetPlugin: No WASM module available")}}const En=new Tn;class Rn{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 Cn(e,t){const n=e.getResource(Pn);n&&n.registerEmbeddedAssets(t)}async function An(e,t,n){const{entities:s,rootId:i}=await In(t,n?.overrides??[],n,void 0,new Set),r={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},o=await nn(e,r,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=o.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:o}}const kn=10;async function In(e,t,n,s,i,r=0){if(r>kn)throw new Error(`Prefab nesting depth exceeded ${kn}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await In(e,s.nestedPrefab.overrides,n,a,i,r+1);o.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?o.get(s.parent)??null:null),l.push(...t.entities);continue}const c=o.get(s.prefabEntityId),d=s.prefabEntityId===e.rootEntityId,h={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:d?null:null!==s.parent?o.get(s.parent)??null:null,children:s.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Fn(h.components,o),Bn(h,t),l.push(h)}const c=o.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Fn(e,t){for(const n of e){const e=Qt(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 Bn(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 zn{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 An(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Un=Me(null,"Prefabs");class $n{constructor(){this.name="PrefabsPlugin",this.dependencies=[Pn]}build(e){const t=e.getResource(Pn);e.insertResource(Un,new zn(e.world,t))}}const Dn=new $n;let Ln=null,Wn=0,On=0,Hn=0;const Xn=new Float32Array(256);function Yn(e){Ln=e,Wn=Ln._malloc(64),On=Ln._malloc(64),Hn=Ln._malloc(1024)}function jn(){Ln&&(Wn&&(Ln._free(Wn),Wn=0),On&&(Ln._free(On),On=0),Hn&&(Ln._free(Hn),Hn=0)),Ln=null}function Nn(){if(!Ln)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Ln}const Vn={r:1,g:1,b:1,a:1},Gn={begin(e){const t=Nn();try{t.HEAPF32.set(e,Wn/4),t.draw_begin(Wn)}catch(e){ze(e,"Draw.begin")}},end(){try{Nn().draw_end()}catch(e){ze(e,"Draw.end")}},line(e,t,n,s=1){try{Nn().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.line")}},rect(e,t,n,s=!0){try{Nn().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{Nn().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){ze(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{Nn().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{Nn().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){ze(e,"Draw.circleOutline")}},texture(e,t,n,s=Vn){try{Nn().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){ze(e,"Draw.texture")}},textureRotated(e,t,n,s,i=Vn){try{Nn().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){ze(e,"Draw.textureRotated")}},setLayer(e){Nn().draw_setLayer(e)},setDepth(e){Nn().draw_setDepth(e)},getDrawCallCount:()=>Ln?Ln.draw_getDrawCallCount():0,getPrimitiveCount:()=>Ln?Ln.draw_getPrimitiveCount():0,setBlendMode(e){Nn().draw_setBlendMode(e)},setDepthTest(e){Nn().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=Nn();s.HEAPF32.set(n,On/4),s.draw_mesh(e,t,On)}catch(n){ze(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=Nn(),i=Bt.get(t);if(!i)return;if(Gn.setBlendMode(i.blendMode),Gn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Gn.drawMesh(e,i.shader,n);let r;if(s.HEAPF32.set(n,On/4),!i.dirty_&&i.cachedBuffer_)r=i.cachedIdx_;else{r=0;let e=0;for(const[t,n]of i.uniforms){const s=Jn(t);if(!(s<0)){if(Tt(n))Xn[r++]=10,Xn[r++]=s,Xn[r++]=n.slot??e++,Xn[r++]=n.textureId;else if("number"==typeof n)Xn[r++]=1,Xn[r++]=s,Xn[r++]=n;else if(Array.isArray(n)){Xn[r++]=n.length,Xn[r++]=s;for(let e=0;e<n.length;e++)Xn[r++]=n[e]}else"w"in n?(Xn[r++]=4,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y,Xn[r++]=n.z,Xn[r++]=n.w):"z"in n?(Xn[r++]=3,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y,Xn[r++]=n.z):(Xn[r++]=2,Xn[r++]=s,Xn[r++]=n.x,Xn[r++]=n.y);if(r>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<r)&&(i.cachedBuffer_=new Float32Array(r)),i.cachedBuffer_.set(Xn.subarray(0,r)),i.cachedIdx_=r,i.dirty_=!1}if(0===r)return void s.draw_mesh(e,i.shader,On);s.HEAPF32.set(i.cachedBuffer_.subarray(0,r),Hn/4),s.draw_meshWithUniforms(e,i.shader,On,Hn,r)}catch(n){ze(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},qn={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},Kn=new Set;function Jn(e){const t=qn[e];return void 0!==t?t:(Kn.has(e)||(Kn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(qn).join(", ")}`)),-1)}const Qn=new Map;function Zn(e,t,n){Qn.set(e,{fn:t,scene:n??""})}function es(e){Qn.delete(e)}function ts(){Qn.clear()}var ns;!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"}(ns||(ns={}));let ss=null,is=0,rs=0,os=0;function as(e){ss=e,is=ss._malloc(262144),rs=ss._malloc(65536),os=ss._malloc(256)}function ls(){ss&&(is&&ss._free(is),rs&&ss._free(rs),os&&ss._free(os),is=0,rs=0,os=0),ss=null}function cs(){if(!ss)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return ss}const ds={create(e){const t=cs(),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,is/4);const i=e.layout.length,r=new Int32Array(i);for(let t=0;t<i;t++)r[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,os,i).set(r),t.geometry_init(n,is,s,os,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,rs,s).set(e.indices),t.geometry_setIndices16(n,rs,s)}else{new Uint32Array(t.HEAPU8.buffer,rs,s).set(e.indices),t.geometry_setIndices32(n,rs,s)}}return n},updateVertices(e,t,n=0){const s=cs(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,is/4),s.geometry_updateVertices(e,is,i,n)},release(e){e>0&&cs().geometry_release(e)},isValid:e=>!(!ss||e<=0)&&ss.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return ds.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:ns.Float2},{name:"a_texCoord",type:ns.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,r=Math.cos(i)*e,o=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(r,o,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return ds.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:ns.Float2},{name:"a_texCoord",type:ns.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of e)t=Math.min(t,r.x),n=Math.min(n,r.y),s=Math.max(s,r.x),i=Math.max(i,r.y);const r=[];for(const o of e){const e=(o.x-t)/(s-t),a=(o.y-n)/(i-n);r.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ds.create({vertices:new Float32Array(r),layout:[{name:"a_position",type:ns.Float2},{name:"a_texCoord",type:ns.Float2}],indices:new Uint16Array(o)})}};let hs=null;function us(e){hs=e}function fs(){hs&&gs.isInitialized()&&gs.shutdown(),hs=null}function ps(){if(!hs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return hs}const gs={init(e,t){try{return ps().postprocess_init(e,t)}catch(n){return ze(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{ps().postprocess_shutdown()}catch(e){ze(e,"PostProcess.shutdown")}},resize(e,t){try{ps().postprocess_resize(e,t)}catch(n){ze(n,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return ps().postprocess_addPass(e,t)}catch(t){return ze(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{ps().postprocess_removePass(e)}catch(t){ze(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{ps().postprocess_setPassEnabled(e,t)}catch(t){ze(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return ps().postprocess_isPassEnabled(e)}catch(t){return ze(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,n){try{ps().postprocess_setUniformFloat(e,t,n)}catch(n){ze(n,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,n){try{ps().postprocess_setUniformVec4(e,t,n.x,n.y,n.z,n.w)}catch(n){ze(n,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{ps().postprocess_begin()}catch(e){ze(e,"PostProcess.begin")}},end(){try{ps().postprocess_end()}catch(e){ze(e,"PostProcess.end")}},getPassCount(){try{return ps().postprocess_getPassCount()}catch(e){return ze(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!hs)return!1;try{return hs.postprocess_isInitialized()}catch(e){return ze(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{ps().postprocess_setBypass(e)}catch(e){ze(e,"PostProcess.setBypass")}},isBypassed(){if(!hs)return!0;try{return hs.postprocess_isBypassed()}catch(e){return ze(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Bt.createShader(ys,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Bt.createShader(ys,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Bt.createShader(ys,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Bt.createShader(ys,"#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")},ys="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var _s;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(_s||(_s={}));let ms=null,ws=0;function xs(e){ms=e,ws=ms._malloc(64)}function vs(){ms&&ws&&(ms._free(ws),ws=0),ms=null}const bs={init(e,t){ms?.renderer_init(e,t)},resize(e,t){ms?.renderer_resize(e,t)},begin(e,t){if(ms&&ws)try{ms.HEAPF32.set(e,ws/4),ms.renderer_begin(ws,t??0)}catch(e){ze(e,"Renderer.begin")}},flush(){try{ms?.renderer_flush()}catch(e){ze(e,"Renderer.flush")}},end(){try{ms?.renderer_end()}catch(e){ze(e,"Renderer.end")}},submitSprites(e){if(ms)try{ms.renderer_submitSprites(e._cpp)}catch(e){ze(e,"Renderer.submitSprites")}},submitBitmapText(e){if(ms)try{ms.renderer_submitBitmapText(e._cpp)}catch(e){ze(e,"Renderer.submitBitmapText")}},submitSpine(e){if(ms)try{ms.renderer_submitSpine?.(e._cpp)}catch(e){ze(e,"Renderer.submitSpine")}},setStage(e){ms?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>ms?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){ms?.renderer_releaseTarget(e)},getTargetTexture:e=>ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){ms?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){ms?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){ms?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>ms?ms.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>ms?{drawCalls:ms.renderer_getDrawCalls(),triangles:ms.renderer_getTriangles(),sprites:ms.renderer_getSprites(),text:ms.renderer_getText(),spine:ms.renderer_getSpine?.()??0,meshes:ms.renderer_getMeshes(),culled:ms.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Ss=null;function Ms(e){Ss=e}function Ps(){Ss=null}const Ts={enable(){Ss?.gl_enableErrorCheck(!0)},disable(){Ss?.gl_enableErrorCheck(!1)},check:e=>Ss?.gl_checkErrors(e)??0,diagnose(){Ss?.renderer_diagnose()}};class Es{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:r}=e;s===this.lastWidth_&&i===this.lastHeight_||(bs.resize(s,i),gs.isInitialized()&&gs.getPassCount()>0&&gs.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,r):bs.submitSpine(t),bs.flush(),this.executeDrawCallbacks(n,r),bs.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:r}=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,r):bs.submitSpine(t),bs.flush(),this.executeDrawCallbacks(n,r),bs.end()}executeDrawCallbacks(e,t){const n=Qn;if(n.size>0){Gn.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)}Gn.end();for(const e of s)es(e)}}}const Rs="__scene_transition_overlay__";class Cs{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 As{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,ye,{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),Zn(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const n=gs.addPass(e,t);return this.instance_.postProcessPasses.push(e),n}removePostProcessPass(e){gs.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,ye)){const n=this.app_.world.get(e,ye);n.persistent=t,this.app_.world.insert(e,ye,n)}}}class ks{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_||this.switching_)return void console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${e}")`);if("fade"!==(t?.transition??"none")){this.switching_=!0;try{this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)}finally{this.switching_=!1}}else await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(n=>{const s=t.duration??R.sceneTransitionDuration,i=t.color??{...R.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},Zn(Rs,()=>{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;Gn.setLayer(9999),Gn.setDepth(9999),Gn.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,es(Rs),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,es(Rs),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 Cs(t);this.scenes_.set(e,n);const s=new As(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Pn)?this.app_.getResource(Pn):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 Cs(t);this.scenes_.set(e,n);const s=new As(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Pn)?this.app_.getResource(Pn):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,ye)){if(this.app_.world.get(e,ye).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())es(e);n.drawCallbacks.clear();for(const e of n.postProcessPasses)try{gs.removePass(e)}catch{}n.postProcessPasses.length=0,this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const r=this.loadOrder_.indexOf(e);-1!==r&&this.loadOrder_.splice(r,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Pn)&&(i.assetServer=this.app_.getResource(Pn));const r=await nn(this.app_.world,s,i);e.loadedAssets=n;for(const n of r.values())e.entities.add(n),this.app_.world.insert(n,ye,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=Fs(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(Pn)?this.app_.getResource(Pn):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)Bt.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,ae)){const t=n.get(e,ae);s.sprite=t.color.a,t.color.a=0,n.insert(e,ae,t),i=!0}if(n.has(e,pe)){const t=n.get(e,pe);s.spine=t.color.a,t.color.a=0,n.insert(e,pe,t),i=!0}if(n.has(e,fe)){const t=n.get(e,fe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,fe,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,ae)){const t=n.get(e,ae);t.color.a=s.sprite,n.insert(e,ae,t)}if(void 0!==s.spine&&n.has(e,pe)){const t=n.get(e,pe);t.color.a=s.spine,n.insert(e,pe,t)}if(void 0!==s.bitmapText&&n.has(e,fe)){const t=n.get(e,fe);t.color.a=s.bitmapText,n.insert(e,fe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessPasses)try{gs.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 Is=Me(null,"SceneManager");function Fs(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(Is).getSceneStatus(t)&&n._fn(...s)}}}const Bs=pt([Te(Is),Pe(Ce)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),zs={name:"SceneManager",build(e){const t=new ks(e);e.insertResource(Is,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Is),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ht.Startup,n),e.addSystemToSchedule(ht.Last,Bs)}};class Us{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 ot,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=u(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(ht.Last);else{this.runSchedule(ht.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ht.FixedPreUpdate),this.runSchedule(ht.FixedUpdate),this.runSchedule(ht.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new He,this.resources_=new Re;for(const e of Object.values(ht))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Us}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(ht.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ht.Startup,e)}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 Be(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(Is).register(e),this}setInitialScene(e){return this.getResource(Is).setInitial(e),this}tick(e){this.runner_||(this.runner_=new wt(this.world_,this.resources_,this.eventRegistry_),this.resources_.has(Ce)||this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(ht.First),this.runSchedule(ht.PreUpdate),this.runSchedule(ht.Update),this.runSchedule(ht.PostUpdate),this.runSchedule(ht.Last);this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new wt(this.world_,this.resources_,this.eventRegistry_),this.resources_.insert(Ce,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ht.Startup),this.lastTime_=u(),this.mainLoop())}quit(){this.running_=!1,ts();for(let e=this.installed_plugins_.length-1;e>=0;e--)try{this.installed_plugins_[e].cleanup?.(this)}catch(e){console.error("[ESEngine] Plugin cleanup error:",e)}this.installed_plugins_.length=0,this.installedPluginSet_.clear(),this.installedPluginNames_.clear();const e=[Ps,vs,fs,ls,It,jn];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,r=o=>{if(s.has(o))return;if(i.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&r(n)}i.delete(o),s.add(o),n.push(a)};for(let t=0;t<e.length;t++)r(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));for(const e of n)try{this.runner_.run(e.system)}catch(t){const n=e.system._name;if(console.error(`[ESEngine] System "${n}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,n),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,n))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Ce);t.delta=e,t.elapsed+=e,t.frameCount++}}function $s(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const Ds=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ls(e,t,n,s,i){const r=e*t/n,o=e;switch(s){case se.FixedWidth:return r;case se.FixedHeight:return o;case se.Expand:return Math.max(r,o);case se.Shrink:return Math.min(r,o);case se.Match:{const e=i;return Math.pow(r,1-e)*Math.pow(o,e)}default:return o}}const Ws=[];function Os(e){if(e<Ws.length)return Ws[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 Ws.push(t),t}function Hs(e,t,n,s,i,r){if(0===n||0===s)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=r&&i?o.filter(e=>{const t=i.tryGet(e,ye);return!t||""===t.scene||r.has(t.scene)}):o;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),r=t.getTransform(e),o=i.viewportW*n/(i.viewportH*s);let a,d=0,h=0;if(i.projectionType===te.Orthographic){if(h=i.orthoSize,l){h=Ls(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,o,l.scaleMode,l.matchWidthOrHeight)}d=h*o,a=Ys(-d,d,-h,h,-i.farPlane,i.farPlane)}else a=Ns(i.fov*Math.PI/180,o,i.nearPlane,i.farPlane);const u=Gs(r.position.x,r.position.y,r.position.z),f=Os(c.length);f.entity=e,f.viewProjection.set(Ks(a,u)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=d,f.halfH=h,f.cameraX=r.position.x,f.cameraY=r.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const Xs=new Float32Array(16);function Ys(e,t,n,s,i,r){const o=Xs;o.fill(0);const a=t-e,l=s-n,c=r-i;return o[0]=2/a,o[5]=2/l,o[10]=-2/c,o[12]=-(t+e)/a,o[13]=-(s+n)/l,o[14]=-(r+i)/c,o[15]=1,o}const js=new Float32Array(16);function Ns(e,t,n,s){const i=js;i.fill(0);const r=1/Math.tan(e/2),o=n-s;return i[0]=r/t,i[5]=r,i[10]=(s+n)/o,i[11]=-1,i[14]=2*s*n/o,i}const Vs=new Float32Array(16);function Gs(e,t,n){const s=Vs;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 qs=new Float32Array(16);function Ks(e,t){const n=qs;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 Js={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Qs(e,t,n,s,i,r,o={x:.5,y:.5}){const a=r.right-r.left,l=r.top-r.bottom,c=r.left+e.x*a,d=r.left+t.x*a,h=r.bottom+e.y*l,u=r.bottom+t.y*l;let f,p,g,y;e.x===t.x?(f=c+n.x-i.x*o.x,g=f+i.x):(f=c+n.x,g=d+s.x),e.y===t.y?(p=h+n.y-i.y*o.y,y=p+i.y):(p=h+n.y,y=u+s.y);const _=Math.max(0,g-f),m=Math.max(0,y-p);return{originX:f+o.x*_,originY:p+o.y*m,width:_,height:m,rect:{left:f,bottom:p,right:g,top:y}}}const Zs=ee("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 ei=null,ti=null;function ni(e,t){e.has(t,ae)||e.insert(t,ae,{texture:k,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 si(e,t){switch(e){case Js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Js.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Js.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 ii(e,t){switch(e){case Js.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Js.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Js.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 ri(e,t,n,s){switch(e){case Js.BottomToTop:case Js.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function oi(e,t,n,s){if(!e.has(t,Zs))return;const i=e.get(t,Zs),r=si(n,s);i.anchorMin=r.anchorMin,i.anchorMax=r.anchorMax,r.anchorMin.x===r.anchorMax.x&&(i.size={...i.size,x:0}),r.anchorMin.y===r.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Zs,i)}function ai(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function li(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function ci(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let r=0;r<t.length;r++){const o=t[r],a=s+o;if(e.measureText(a).width>n&&s){if(li(o.charCodeAt(0))&&s.length>0&&li(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!li(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+o):(i.push(s),s=o)}else i.push(s),s=o}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function di(e){let t=1;for(;t<e;)t*=2;return t}function hi(e,t){let n=0,s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;n++,s=t}return n}function ui(e,t){if(ei&&ti){const e=ei.getUIRectComputedWidth(ti,t);if(e>0)return e}return e.size.x}function fi(e,t){if(ei&&ti){const e=ei.getUIRectComputedHeight(ti,t);if(e>0)return e}return e.size.y}function pi(e,t,n,s,i,r){if(!e.has(t,ae))return;const o=e.get(t,ae);let a,l;switch(n){case Js.BottomToTop:case Js.TopToBottom:a=i,l=r*s;break;default:a=i*s,l=r}o.size.x===a&&o.size.y===l||(o.size.x=a,o.size.y=l,e.insert(t,ae,o))}function gi(e,t,n){let s=t;for(;e.has(s,he);){const t=e.get(s,he).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function yi(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function _i(e,t,n,s,i){if(!e.has(t,Zs))return;const r=e.get(t,Zs),o=Qs(r.anchorMin,r.anchorMax,r.offsetMin,r.offsetMax,r.size,n,r.pivot),a=o.rect.right-o.rect.left,l=o.rect.top-o.rect.bottom;if(e.has(t,ae)){const n=e.get(t,ae);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie);n.position.x=o.originX-s,n.position.y=o.originY-i,e.insert(t,ie,n)}}function mi(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 wi=.1,xi=30,vi={r:.3,g:.5,b:.8,a:1},bi={Left:0,Center:1,Right:2},Si={Top:0,Middle:1,Bottom:2},Mi={Visible:0,Clip:1,Ellipsis:2},Pi=Y("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:bi.Left,verticalAlign:Si.Top,wordWrap:!0,overflow:Mi.Visible,lineHeight:1.2});class Ti{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(R.textCanvasSize,R.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,di(this.frameMaxW_)),e.height=Math.max(e.height,di(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=di(this.frameMaxW_),e.height=di(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,r=i?t.size.x:0,o=i?t.size.y:0,a=e.wordWrap&&i;let l=ci(n,e.content,a?r:0);const c=Math.ceil(e.fontSize*e.lineHeight),d=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),u=Math.ceil(l.length*c),f=i?Math.ceil(r):h+2*d,p=i?Math.ceil(o):u+2*d;if(i&&e.overflow===Mi.Ellipsis&&u>o){const e=Math.floor(o/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,r)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,di(f)),s.height=Math.max(s.height,di(p)));const g=Math.round(255*e.color.r),y=Math.round(255*e.color.g),_=Math.round(255*e.color.b),m=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${g}, ${y}, ${_}, ${m})`,i&&e.overflow===Mi.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 Si.Top:x=d;break;case Si.Middle:x=d+(p-2*d-w)/2;break;case Si.Bottom:x=p-w-d;break;default:x=d}else x=d;let v=x;for(const t of l){let s;switch(e.align){case bi.Left:s=d;break;case bi.Center:s=f/2;break;case bi.Right:s=f-d;break;default:s=d}n.fillText(t,s,v),v+=c}i&&e.overflow===Mi.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 Ei=mi({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?ui(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?fi(e.uiRect,e.entity):0});class Ri{build(e){Q("Text",Pi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new Ti(t),s=e.world,i=new Map;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,Pi));for(const e of i.keys())if(!s.valid(e)||!s.has(e,Pi)){if(s.valid(e)&&s.has(e,ae)){const t=s.get(e,ae);s.insert(e,ae,{texture:k,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([Pi]);for(const t of e){const e=s.get(t,Pi),r=s.has(t,Zs)?s.get(t,Zs):null,o={text:e,uiRect:r,entity:t},a=i.get(t);if(a&&!Ei.changed(a,o)){if(s.has(t,ae)&&s.get(t,ae).texture!==k)continue}ni(s,t);const l=r?{size:{x:ui(r,t),y:fi(r,t)}}:null,c=n.renderForEntity(t,e,l),d=s.get(t,ae);s.insert(t,ae,{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,Ei.take(o))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ci=new Ri,Ai=0,ki=1,Ii=ee("UIMask",{enabled:!0,mode:Ai});function Fi(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),r=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,r-s)}}function Bi(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],r=e[2],o=e[3],a=e[4],l=e[5],c=e[6],d=e[7],h=e[8],u=e[9],f=e[10],p=e[11],g=e[12],y=e[13],_=e[14],m=e[15],w=s*l-i*a,x=s*c-r*a,v=s*d-o*a,b=i*c-r*l,S=i*d-o*l,M=r*d-o*c,P=h*y-u*g,T=h*_-f*g,E=h*m-p*g,R=u*_-f*y,C=u*m-p*y,A=f*m-p*_;let k=w*A-x*C+v*R+b*E-S*T+M*P;return 0===k||(k=1/k,n[0]=(l*A-c*C+d*R)*k,n[1]=(r*C-i*A-o*R)*k,n[2]=(y*M-_*S+m*b)*k,n[3]=(f*S-u*M-p*b)*k,n[4]=(c*E-a*A-d*T)*k,n[5]=(s*A-r*E+o*T)*k,n[6]=(_*v-g*M-m*x)*k,n[7]=(h*M-f*v+p*x)*k,n[8]=(a*C-l*E+d*P)*k,n[9]=(i*E-s*C-o*P)*k,n[10]=(g*S-y*v+m*w)*k,n[11]=(u*v-h*S-p*w)*k,n[12]=(l*T-a*R-c*P)*k,n[13]=(s*R-i*T+r*P)*k,n[14]=(y*x-g*b-_*w)*k,n[15]=(h*b-u*x+f*w)*k),n}function zi(e,t,n,s,i,r,o){const a=(e-s)/r*2-1,l=(t-i)/o*2-1,c=n[0]*a+n[4]*l+n[12],d=n[1]*a+n[5]*l+n[13],h=n[3]*a+n[7]*l+n[15];return{x:c/h,y:d/h}}function Ui(e,t,n,s,i,r,o,a){return e>=n-i*o&&e<=n+i*(1-o)&&t>=s-r*a&&t<=s+r*(1-a)}function $i(e,t){return 2*Math.atan2(e,t)}function Di(e,t,n,s,i,r,o){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*r,i+(.5*(l/c)+.5)*o]}function Li(e,t,n,s,i,r,o,a,l,c){const d=$i(l,c),h=Math.sin(-d),u=Math.cos(-d),f=e-n,p=t-s,g=f*u-p*h+n,y=f*h+p*u+s;return g>=n-i*o&&g<=n+i*(1-o)&&y>=s-r*a&&y<=s+r*(1-a)}function Wi(e,t,n,s,i,r,o){if(!e.has(t,Zs)||!e.has(t,ie))return null;const a=e.get(t,Zs),l=e.get(t,ie),c=ui(a,t)*l.worldScale.x,d=fi(a,t)*l.worldScale.y,h=l.worldPosition.x,u=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,g=-c*f,y=c*(1-f),_=-d*p,m=d*(1-p),w=$i(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+g*x-_*v,u+g*v+_*x],[h+y*x-_*v,u+y*v+_*x],[h+y*x-m*v,u+y*v+m*x],[h+g*x-m*v,u+g*v+m*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=Di(e,t,n,s,i,r,o);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 Oi(e,t){return(n,s,i,r,o,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Ii]);if(0===l.length)return;const c=[],d=[],h=new Set,u=new Set;for(const e of l){const n=t.get(e,Ii);n.enabled&&(h.add(e),n.mode===ki?(d.push(e),u.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,r,o,a,l,c){const d=[];for(const e of s){let n=!0;gi(t,e,e=>{if(i.has(e)){if(t.get(e,Ii).mode===Ai)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,Ii).mode===Ai){const e=Wi(t,n,r,o,a,l,c);e&&(s=Fi(d,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),h(n,s)}}for(const e of d){const n=Wi(t,e,r,o,a,l,c);n&&h(e,n)}}(e,t,n,c,h,s,i,r,o,a),d.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const r=[];for(const e of s){let n=!0;gi(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&r.push(e)}let o=1,a=!1;function l(){return o>255?(a||console.warn("Stencil mask overflow"),a=!0,null):o++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}function d(t,s){if(a)return;const r=e.getChildEntities(n,t);for(const t of r)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),d(t,s)}for(const e of r){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,d,u)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class Hi{build(e){if(Q("UIMask",Ii),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Oi(e.wasmModule,e.world))}}const Xi=new Hi,Yi=ee("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),ji=ee("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Ni={Normal:0,Hovered:1,Pressed:2,Disabled:3},Vi=Y("Button",{state:Ni.Normal,transition:null});class Gi{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 qi=Me(new Gi,"UIEvents");class Ki{build(e){Q("UIRect",Zs);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){ei=e,ti=t}(n,s);e.addSystemToSchedule(ht.PreUpdate,pt([Pe(Mt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s),n.transform_update(s))},{name:"UILayoutSystem"})),e.addSystemToSchedule(ht.PostUpdate,pt([Pe(Mt)],e=>{e.valid&&(n.uiLayout_update(s,e.worldLeft,e.worldBottom,e.worldRight,e.worldTop),n.uiFlexLayout_update(s))},{name:"UILayoutLateSystem"}),{runBefore:["UIRenderOrderSystem"]}),e.addSystemToSchedule(ht.PostUpdate,pt([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ji=new Ki;let Qi=!1,Zi=!1;function er(e){Qi=e}function tr(){return Qi}function nr(){return!Qi}function sr(e){Zi=e}function ir(){return Zi}const rr=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&&(Bi(t,e),n=!1),e)}}();function or(e,t,n,s){t.emit(n,s,n),gi(e,n,i=>{if(!e.has(i,Yi))return!1;const r=e.get(i,Yi);return r.enabled&&t.emit(i,s,n),r.blockRaycast})}class ar{build(e){Q("Interactable",Yi),Q("Button",Vi);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Gi;e.insertResource(qi,i);let r=null,o=null;e.addSystemToSchedule(ht.PreUpdate,pt([Pe(vt),Pe(Mt)],(e,a)=>{if(i.drain(),tr()&&!ir())return;const l=t.getEntitiesWithComponents([ji]);for(const e of l){const n=t.get(e,ji);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,ji,n))}if(!a.valid)return;const c=f(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;rr.update(a.viewProjection);const u=zi(d,h,rr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=u.x,a.worldMouseY=u.y;const p=e.isMouseButtonDown(0),g=e.isMouseButtonPressed(0),y=e.isMouseButtonReleased(0);n.uiHitTest_update(s,u.x,u.y,p,g,y);const _=n.uiHitTest_getHitEntity(),m=4294967295===_?null:_;if(null===r||t.valid(r)||(r=null),r!==m){if(null!==r&&t.valid(r)&&t.has(r,ji)){const e=t.get(r,ji);e.hovered=!1,t.insert(r,ji,e),i.emit(r,"hover_exit")}if(null!==m){yi(t,m,ji);const e=t.get(m,ji);e.hovered=!0,t.insert(m,ji,e),i.emit(m,"hover_enter")}r=m}if(g&&null!==m){const e=t.get(m,ji);e.pressed=!0,e.justPressed=!0,t.insert(m,ji,e),o=m,or(t,i,m,"press")}if(y&&null!==o){if(t.valid(o)&&t.has(o,ji)){const e=t.get(o,ji);e.pressed=!1,e.justReleased=!0,t.insert(o,ji,e),or(t,i,o,"release"),o===r&&or(t,i,o,"click")}o=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(ht.Update,pt([],()=>{const e=t.getEntitiesWithComponents([Vi]);for(const n of e){if(yi(t,n,Yi,{enabled:!0}),!t.has(n,ji))continue;const e=t.get(n,ji),s=t.get(n,Vi),i=t.get(n,Yi),r=!a.has(n),o=s.state;if(i.enabled?e.pressed?s.state=Ni.Pressed:e.hovered?s.state=Ni.Hovered:s.state=Ni.Normal:s.state=Ni.Disabled,r&&a.add(n),(r||o!==s.state)&&s.transition&&t.has(n,ae)){const r=t.get(n,ae);r.color=ai(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,ae,r)}}},{name:"ButtonSystem"}))}}const lr=new ar,cr=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}),dr=Y("Focusable",{tabIndex:0,isFocused:!1});class hr{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 ur=Me(new hr,"FocusManager");class fr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(Q("TextInput",cr),tr()&&!ir())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const n=e.world,s=new Map,i=h(R.textCanvasSize,64),r=i.getContext("2d",{willReadFrequently:!0});let o=0,a=0,l=!1,c=!0,d=0,u=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function g(){const t=e.getResource(ur);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,cr)?s:null}const y=()=>{l||null===g()||v()},_=()=>{l=!0},m=()=>{l=!1,v()},w=t=>{const s=g();if(null===s)return;if("Escape"===t.key)return void b();const i=n.get(s,cr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(qi).emit(s,"submit"),void b()}let r=i.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?r=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=i.value.length),r!==i.cursorPos&&(i.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,i.dirty=!0,S())},x=()=>{const t=g();if(null!==t){const s=n.get(t,cr);s.focused=!1,s.dirty=!0;e.getResource(ur).blur()}};function v(){const t=g();if(null===t)return;const s=n.get(t,cr);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(qi).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function b(){const t=g();if(null!==t){const e=n.get(t,cr);e.focused=!1,e.dirty=!0}e.getResource(ur).blur(),p.blur()}function S(){c=!0,d=0}p.addEventListener("input",y),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",m),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",y),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",m),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==o&&(t._free(o),o=0,a=0)};let M=null;function P(e,l,d,h){(i.width<d||i.height<h)&&(i.width=di(Math.max(i.width,d)),i.height=di(Math.max(i.height,h))),r.clearRect(0,0,i.width,i.height);const u=l.backgroundColor;r.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,r.fillRect(0,0,d,h),r.save(),r.beginPath(),r.rect(l.padding,0,d-2*l.padding,h),r.clip(),r.font=`${l.fontSize}px ${l.fontFamily}`,r.textBaseline="top",r.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,g=f?l.placeholderColor:l.color;r.fillStyle=`rgba(${Math.round(255*g.r)}, ${Math.round(255*g.g)}, ${Math.round(255*g.b)}, ${g.a})`;const y=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=ci(r,p,d-2*_);let t=_;for(const n of e)r.fillText(n,_,t),t+=y}else{const e=(h-l.fontSize)/2;r.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=ci(r,l.value,d-2*_);let i=0,o=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){o=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,o=t+1,a=0}const c=o<e.length?e[o].substring(0,a):"";t=_+r.measureText(c).width,n=_+o*y,s=y}else t=_+r.measureText(e).width,n=(h-l.fontSize)/2,s=l.fontSize;r.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,r.fillRect(t,n,2,s)}r.restore();const m=r.getImageData(0,0,d,h),w=new Uint8Array(m.data.buffer),x=t.getResourceManager();w.length>a&&(0!==o&&t._free(o),o=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,o);const v=s.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(d,h,o,w.length,1,!0);s.set(e,b);const S=n.get(e,ae);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,ae,S)}e.addSystemToSchedule(ht.Update,pt([Pe(ur)],e=>{const t=n.getEntitiesWithComponents([cr]);for(const e of t)yi(n,e,dr,{tabIndex:0,isFocused:!1}),yi(n,e,Yi,{enabled:!0,blockRaycast:!0});const s=g();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,cr)){const e=n.get(M,cr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,cr);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(ht.PreUpdate,pt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===u?0:(e-u)/1e3;u=e,i=Math.min(i,.1);const r=g();if(null!==r&&(d+=i,d>=.5)){d-=.5,c=!c;n.get(r,cr).dirty=!0}const o=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,cr)||(o.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([cr,Zs]);for(const e of a){const t=n.get(e,cr);if(!t.dirty)continue;const s=n.get(e,Zs),i=Math.ceil(s.size.x),r=Math.ceil(s.size.y);i<=0||r<=0||(ni(n,e),P(e,t,i,r),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const pr=new fr,gr={Simple:0,Sliced:1,Tiled:2,Filled:3},yr={Horizontal:0,Vertical:1},_r={Left:0,Right:1,Bottom:2,Top:3},mr=Y("Image",{texture:k,color:{r:1,g:1,b:1,a:1},imageType:gr.Simple,fillMethod:yr.Horizontal,fillOrigin:_r.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),wr=mi({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?ui(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?fi(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});const xr=new class{build(e){Q("Image",mr);const t=e.world,n=new Map;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,mr)||n.delete(e);const e=t.getEntitiesWithComponents([mr]);for(const s of e){const e=t.get(s,mr),i=t.has(s,Zs)?t.get(s,Zs):null,r={image:e,uiRect:i,entity:s},o=n.get(s);if(o&&!wr.changed(o,r))continue;ni(t,s);const a=t.get(s,ae);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=ui(i,s),a.size.y=fi(i,s)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===gr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),n=a.size.x,s=a.size.y;e.fillMethod===yr.Horizontal?e.fillOrigin===_r.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===_r.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===gr.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,ae,a),n.set(s,wr.take(r))}else a.color.a=0,t.insert(s,ae,a),n.set(s,wr.take(r))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}},vr=Y("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),br=Y("ToggleGroup",{allowSwitchOff:!1});const Sr=new class{build(e){Q("Toggle",vr),Q("ToggleGroup",br);const t=e.world,n=new Set;e.addSystemToSchedule(ht.Update,pt([Pe(qi)],e=>{const s=t.getEntitiesWithComponents([vr]);if(!tr()||ir()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,vr);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,vr,s)):i.set(s.group,e))}const r=new Map;for(const e of s){const n=t.get(e,vr);if(0!==n.group&&t.valid(n.group)){let t=r.get(n.group);t||(t=[],r.set(n.group,t)),t.push(e)}}for(const n of s){if(yi(t,n,Yi,{enabled:!0}),!t.has(n,ji))continue;const s=t.get(n,ji),i=t.get(n,vr),o=t.get(n,Yi);if(s.justPressed&&o.enabled){const s=i.group,o=0!==s&&t.valid(s)&&t.has(s,br);if(i.isOn&&o){if(!t.get(s,br).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,vr,i),i.isOn&&o){const i=r.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,vr);i.isOn&&(i.isOn=!1,t.insert(s,vr,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,ae)){const e=t.get(n,ae);e.color=ai(i.transition,o.enabled,s.pressed,s.hovered),t.insert(n,ae,e)}}}for(const e of s){const n=t.get(e,vr);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,ae)){const e=t.get(n.graphicEntity,ae);e.enabled=n.isOn,t.insert(n.graphicEntity,ae,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}},Mr=Js,Pr=Y("ProgressBar",{value:0,fillEntity:0,direction:Js.LeftToRight});function Tr(e,t,n,s){if(!e.has(t,Zs))return;const i=e.get(t,Zs),r=n/2,o=s/2,a={left:-r,bottom:-o,right:r,top:o},l=Qs(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ae)){const n=e.get(t,ae);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,ae,n))}if(e.has(t,ie)){const n=e.get(t,ie),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,ie,n))}}class Er{build(e){Q("ProgressBar",Pr);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([Pr,Zs]);for(const n of e){const e=t.get(n,Pr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Zs),i=Math.max(0,Math.min(1,e.value));oi(t,e.fillEntity,e.direction,i);const r=ui(s,n),o=fi(s,n);Tr(t,e.fillEntity,r,o)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Rr=new Er,Cr=Y("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ar=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 kr=new class{build(e){Q("Draggable",Cr),Q("DragState",Ar);const t=e.world,n=e.getResource(qi);let s=null,i={x:0,y:0},r=null;e.addSystemToSchedule(ht.PreUpdate,pt([Pe(vt),Pe(Mt)],(e,o)=>{if(tr()&&!ir())return;if(!o.valid)return;const a={x:o.worldMouseX,y:o.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Cr,ji]);let n=null,r=-1/0,o=-1;for(const s of e){if(!t.get(s,Cr).enabled)continue;if(t.get(s,ji).hovered){let e=0;t.has(s,ae)&&(e=t.get(s,ae).layer);const i=hi(t,s);(e>r||e===r&&i>=o)&&(r=e,o=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,Ar)||t.insert(n,Ar);const e=t.get(n,Ar),r=t.get(n,ie);e.startWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.currentWorldPos={x:r.worldPosition.x,y:r.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,Ar)){t.get(s,Ar).isDragging=!1}s=null}if(null!==s&&null===r){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),d=t.get(s,Cr);if(c*(o.vpW/(o.worldRight-o.worldLeft))>=d.dragThreshold){r=s,s=null;t.get(r,Ar).isDragging=!0,n.emit(r,"drag_start")}}if(null!==r){if(!t.valid(r)||!t.has(r,Ar))return void(r=null);const s=t.get(r,Ar),i=t.get(r,Cr),o=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+o,d=s.startWorldPos.y+l;const h=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,r=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),r=Math.max(r,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),r=Math.min(r,e.constraintMax.y)),{x:i,y:r}}(i,s,c,d);c=h.x,d=h.y;const u=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-u,y:d-f},s.currentWorldPos={x:c,y:d},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:d-s.startWorldPos.y},t.has(r,ie)){const e=function(e,t,n,s){if(!e.has(t,he))return{x:n,y:s};const i=e.get(t,he).entity;if(!e.valid(i)||!e.has(i,ie))return{x:n,y:s};const r=e.get(i,ie),o=0!==r.worldScale.x?r.worldScale.x:1,a=0!==r.worldScale.y?r.worldScale.y:1,l=$i(r.worldRotation.z,r.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l);return{x:(n*d-s*c)/o,y:(n*c+s*d)/a}}(t,r,s.deltaWorld.x,s.deltaWorld.y),n=t.get(r,ie);n.position.x+=e.x,n.position.y+=e.y,t.insert(r,ie,n)}n.emit(r,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(r,"drag_end"),r=null)}},{name:"DragSystem"}))}},Ir=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 Fr(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 Br(e,t,n,s,i){const r=2/(s=Math.max(1e-4,s)),o=r*i,a=1/(1+o+.48*o*o+.235*o*o*o),l=e-t,c=(n+r*l)*i,d=t+(l+c)*a;return t-e>0==d>t?{value:t,velocity:0}:{value:d,velocity:(n-r*c)*a}}const zr=new class{build(e){Q("ScrollView",Ir);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(ht.PostUpdate,pt([Pe(vt),Pe(Mt),Pe(Ce)],(e,i,r)=>{const o=tr()&&!ir(),a=Math.min(r.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Ir,Zs]);for(const r of l){yi(t,r,Ii,{enabled:!0,mode:Ai});const l=t.get(r,Ir),c=t.get(r,Zs);let d=n.get(r);d||(d={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(r,d));const h=ui(c,r),u=fi(c,r);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue).entities;let n=0,s=0,i=0,r=0;for(const o of e){if(!t.valid(o)||!t.has(o,ie))continue;const e=t.get(o,ie);let a=0,l=0,c=.5,d=.5;if(t.has(o,Zs)){const e=t.get(o,Zs);a=ui(e,o)||e.size.x,l=fi(e,o)||e.size.y,c=e.pivot.x,d=e.pivot.y}else if(t.has(o,ae)){const e=t.get(o,ae);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,u=e.position.x+a*(1-c),f=e.position.y-l*d,p=e.position.y+l*(1-d);h<n&&(n=h),u>s&&(s=u),f<i&&(i=f),p>r&&(r=p)}0===f&&(f=s-n),0===p&&(p=r-i)}const g=Math.max(0,f-h),y=Math.max(0,p-u);if(!o&&i.valid){yi(t,r,Yi,{enabled:!0,blockRaycast:!0});const n=t.has(r,ji)?t.get(r,ji):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=Fr(l.scrollX,0,g,h);if(l.scrollX-=e*t,0===e)d.velocityX=0;else{const s=a>0?-e*t/a:0;d.velocityX+=(s-d.velocityX)*n}}if(l.verticalEnabled){const e=Fr(l.scrollY,0,y,u);if(l.scrollY+=t*e,0===t)d.velocityY=0;else{const s=a>0?t*e/a:0;d.velocityY+=(s-d.velocityY)*n}}d.lastWorldX=s.x,d.lastWorldY=s.y}if(d.isDragging&&e.isMouseButtonReleased(0)){d.isDragging=!1;const e=5*h,t=5*u;d.velocityX=Math.max(-e,Math.min(d.velocityX,e)),d.velocityY=Math.max(-t,Math.min(d.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=Fr(l.scrollY,0,y,u);l.scrollY+=t.y*l.wheelSensitivity*e,d.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Fr(l.scrollX,0,g,h);l.scrollX+=t.x*l.wheelSensitivity*e,d.velocityX=0}}}if(!d.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>g,t=l.scrollY<0||l.scrollY>y;if(l.elastic&&e){const e=l.scrollX<0?0:g,t=Br(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)<wi&&(l.scrollX=e,d.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(d.velocityX)>wi?(d.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=d.velocityX*a):d.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:y,t=Br(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)<wi&&(l.scrollY=e,d.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(d.velocityY)>wi?(d.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=d.velocityY*a):d.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,g)),l.scrollY=Math.max(0,Math.min(l.scrollY,y)),l.scrollX!==e&&(d.velocityX=0),l.scrollY!==t&&(d.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*u;l.scrollX=Math.max(-e,Math.min(l.scrollX,g+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,y+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ie)){const e=t.get(l.contentEntity,ie),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,ie,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Ur=Js,$r=Y("Slider",{value:0,minValue:0,maxValue:1,direction:Js.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Dr(e,t,n,s,i,r){const o=ui(s,i)*n.worldScale.x,a=fi(s,i)*n.worldScale.y,l=$i(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),d=Math.cos(-l),h=e-n.worldPosition.x,u=t-n.worldPosition.y,f=h*d-u*c,p=h*c+u*d,g=-s.pivot.x*o,y=-s.pivot.y*a;switch(r){case Js.LeftToRight:return o>0?(f-g)/o:0;case Js.RightToLeft:return o>0?1-(f-g)/o:0;case Js.BottomToTop:return a>0?(p-y)/a:0;case Js.TopToBottom:return a>0?1-(p-y)/a:0}}function Lr(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Js.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Js.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Js.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Js.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Wr{build(e){Q("Slider",$r);const t=e.world;let n=null;e.addSystemToSchedule(ht.PreUpdate,pt([Pe(vt),Pe(Mt),Pe(qi)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const r=t.getEntitiesWithComponents([$r,Zs]);for(const o of r){const r=t.get(o,$r),a=t.get(o,Zs);if(!tr()||ir()){if(t.has(o,ie)){yi(t,o,Yi,{enabled:!0,blockRaycast:!0}),0!==r.handleEntity&&t.valid(r.handleEntity)&&yi(t,r.handleEntity,Yi,{enabled:!0,blockRaycast:!1});const l=t.get(o,ie),c=t.has(o,ji)?t.get(o,ji):null;let d=c?.justPressed??!1;if(!d&&0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,ji)&&(d=t.get(r.handleEntity,ji).justPressed),d&&(n=o),n===o&&e.isMouseButtonDown(0)){let e=Dr(s.worldMouseX,s.worldMouseY,l,a,o,r.direction);e=Math.max(0,Math.min(1,e));let n=r.minValue+e*(r.maxValue-r.minValue);r.wholeNumbers&&(n=Math.round(n));const c=r.value;r.value=Math.max(r.minValue,Math.min(r.maxValue,n)),t.insert(o,$r,r),r.value!==c&&i.emit(o,"change")}n===o&&e.isMouseButtonReleased(0)&&(n=null)}}const l=r.maxValue-r.minValue,c=l>0?(r.value-r.minValue)/l:0,d=ui(a,o),h=fi(a,o),u={left:-d/2,bottom:-h/2,right:d/2,top:h/2};if(0!==r.fillEntity&&t.valid(r.fillEntity)&&(oi(t,r.fillEntity,r.direction,c),_i(t,r.fillEntity,u,0,0)),0!==r.handleEntity&&t.valid(r.handleEntity)&&t.has(r.handleEntity,Zs)){const e=t.get(r.handleEntity,Zs);Lr(e,r.direction,c),t.insert(r.handleEntity,Zs,e),_i(t,r.handleEntity,u,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Or=new Wr;const Hr=new class{build(e){Q("Focusable",dr);const t=e.world,n=new hr;e.insertResource(ur,n),e.addSystemToSchedule(ht.Update,pt([Pe(vt),Pe(qi)],(e,s)=>{if(tr()&&!ir())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([dr]);for(const e of i){if(!t.has(e,ji))continue;t.get(e,ji).justPressed&&r(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Yi)){if(!t.get(n,Yi).enabled)continue}const s=t.get(n,dr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const o=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===o?a?s.length-1:0:a?(o-1+s.length)%s.length:(o+1)%s.length,r(s[l])}function r(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,dr)){t.get(i,dr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,dr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}},Xr=Y("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Yr(){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 jr=new class{build(e){Q("SafeArea",Xr);const t=e.world;let n=Yr(),s=!0,r=0,o=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Yr(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Yr(),s=!0});e.addSystemToSchedule(ht.PreUpdate,pt([Pe(Mt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===r&&a===o||(r=e.screenH,o=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([Xr,Zs]);for(const e of d){const s=t.get(e,Xr),i=t.get(e,Zs),r=s.applyTop?n.top*c:0,o=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let d=!1;i.offsetMin.x===a&&i.offsetMin.y===o||(i.offsetMin={x:a,y:o},d=!0),i.offsetMax.x===-l&&i.offsetMax.y===-r||(i.offsetMax={x:-l,y:-r},d=!0),d&&t.insert(e,Zs,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}},Nr=Y("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Vr=null;function Gr(e,t){if(!Vr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Vr.get(e);n?n.renderer=t:Vr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}const qr=new class{build(e){Q("ListView",Nr);const t=e.world,n=new Map;Vr=n,e.addSystemToSchedule(ht.PostUpdate,pt([Pe(vt)],e=>{const s=tr()&&!ir();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([Nr,Zs]);for(const r of i){yi(t,r,Yi,{enabled:!0,blockRaycast:!0}),yi(t,r,Ii,{enabled:!0,mode:Ai});let i=n.get(r);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(r,i));const o=t.get(r,Nr),a=t.get(r,Zs),l=fi(a,r),c=ui(a,r);if(!s){const n=t.has(r,ji)?t.get(r,ji):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(o.scrollY+=.1*t.y)}}const d=Math.max(0,o.itemCount*o.itemHeight-l);o.scrollY=Math.max(0,Math.min(o.scrollY,d));const h=Math.max(0,Math.floor(o.scrollY/o.itemHeight)-o.overscan),u=Math.min(o.itemCount,Math.ceil((o.scrollY+l)/o.itemHeight)+o.overscan);for(const[e,n]of i.itemEntities)(e<h||e>=u)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=h;e<u;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,ge,{value:`ListItem_${e}`}),t.insert(n,Zs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:o.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,r),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,ie)){const s=t.get(n,ie);s.position.y=-(e*o.itemHeight-o.scrollY),t.insert(n,ie,s)}}i.visibleStart=h,i.visibleEnd=u}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}},Kr=Y("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});const Jr=new class{build(e){Q("Dropdown",Kr);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,ie))return;const n=t.get(e,ie);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,ie,{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,ae)){const n=t.get(e,ae);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,ae,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function r(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;d(i,!0),c(s);const r=t.get(e,ae),o=r.size.x,a=r.size.y;s.ddWidth=o;const l=n.options.length*xi;t.insert(i,Zs,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:l},pivot:{x:.5,y:.5}}),t.insert(i,ie,{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,ae,{texture:k,color:{r:1,g:1,b:1,a:1},size:{x:o,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const r=t.spawn(),a=l/2-(e+.5)*xi;t.insert(r,ge,{value:`Option_${e}`}),t.insert(r,Zs,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*xi},offsetMax:{x:0,y:0},size:{x:o,y:xi},pivot:{x:.5,y:.5}}),t.insert(r,ie,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(r,ae,{texture:k,color:{r:.95,g:.95,b:.95,a:1},size:{x:o,y:xi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(r,Yi,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(r,i),s.optionEntities.push(r);const c=t.spawn();t.insert(c,ie,{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,Pi,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:bi.Left,verticalAlign:Si.Middle,wordWrap:!1,overflow:Mi.Clip,lineHeight:1.2}),t.insert(c,Zs,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:o,y:xi},pivot:{x:.5,y:.5}}),t.setParent(c,r),s.textEntities.push(c)}h(s)}function o(e,t,n){t.isOpen=!1,c(n),d(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,o(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,Pi))return;const s=t.get(n,Pi);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},r=s.content,o=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},o=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];r!==t&&(r=t,o=!0)}o&&t.insert(n,Pi,{content:r,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function d(e,n){if(0!==e&&t.valid(e)&&(t.has(e,Yi)&&t.insert(e,Yi,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,ae))){const s=t.get(e,ae);t.insert(e,ae,{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,ae))continue;const i=n===e.highlightIndex?{...vi}:{r:.95,g:.95,b:.95,a:1};t.insert(s,ae,{texture:k,color:i,size:{x:e.ddWidth,y:xi},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,ji))continue;if(t.get(n,ji).hovered)return!0}return!1}e.addSystemToSchedule(ht.Update,pt([Pe(vt),Pe(qi)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=tr()&&!ir(),p=t.getEntitiesWithComponents([Kr]);for(const g of p){const p=t.get(g,Kr);let y=n.get(g);if(y||(y={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(g,y)),s(p.listEntity),i(g),p.isOpen||d(p.listEntity,!1),l(p),f)continue;yi(t,g,Yi,{enabled:!0,blockRaycast:!0});const _=t.has(g,ji)?t.get(g,ji):null;if(_?.justPressed&&(p.isOpen?o(g,p,y):r(g,p,y)),p.isOpen){for(let e=0;e<y.optionEntities.length;e++){const n=y.optionEntities[e];if(!t.valid(n)||!t.has(n,ji))continue;if(t.get(n,ji).justPressed){a(g,p,y,e,c);break}}let n=-1;for(let e=0;e<y.optionEntities.length;e++){const s=y.optionEntities[e];if(!t.valid(s)||!t.has(s,ji))continue;if(t.get(s,ji).hovered){n=e;break}}n>=0&&n!==y.highlightIndex&&(y.highlightIndex=n,h(y)),e.isKeyPressed("ArrowDown")?(y.highlightIndex>=p.options.length-1?y.highlightIndex=0:y.highlightIndex++,h(y)):e.isKeyPressed("ArrowUp")?(y.highlightIndex<=0?y.highlightIndex=p.options.length-1:y.highlightIndex--,h(y)):e.isKeyPressed("Enter")&&y.highlightIndex>=0?a(g,p,y,y.highlightIndex,c):e.isKeyPressed("Escape")&&o(g,p,y),e.isMouseButtonPressed(0)&&(_?.hovered||u(y)||o(g,p,y))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}},Qr=0,Zr=0,eo=2,to=Y("LayoutGroup",{direction:Qr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Zr,reverseOrder:!1});const no=new class{build(e){Q("LayoutGroup",to);const t=e.world;e.addSystemToSchedule(ht.PreUpdate,pt([],()=>{const e=t.getEntitiesWithComponents([to,Zs,ue]);for(const n of e){const e=t.get(n,to),s=t.get(n,Zs),i=t.get(n,ue);if(!i.entities||0===i.entities.length)continue;const r=[];for(const e of i.entities)t.valid(e)&&t.has(e,Zs)&&t.has(e,ie)&&r.push({entity:e,rect:t.get(e,Zs)});if(0===r.length)continue;e.reverseOrder&&r.reverse();const o=ui(s,n),a=fi(s,n),l=s.pivot.x,c=s.pivot.y,d=e.padding,h=e.direction===Qr;let u=0;for(let n=0;n<r.length;n++){const s=r[n],i=ui(s.rect,s.entity),f=fi(s.rect,s.entity),p=s.rect.pivot.x,g=s.rect.pivot.y;let y,_;h?(y=-l*o+d.left+u+p*i,_=e.childAlignment===Zr?(1-c)*a-d.top-(1-g)*f:e.childAlignment===eo?-c*a+d.bottom+g*f:(.5-c)*a+.5*(d.bottom-d.top)+(g-.5)*f,u+=i,n<r.length-1&&(u+=e.spacing)):(y=e.childAlignment===Zr?-l*o+d.left+p*i:e.childAlignment===eo?(1-l)*o-d.right-(1-p)*i:(.5-l)*o+.5*(d.left-d.right)+(p-.5)*i,_=(1-c)*a-d.top-u-(1-g)*f,u+=f,n<r.length-1&&(u+=e.spacing));const m=t.get(s.entity,ie);m.position.x=y,m.position.y=_,t.insert(s.entity,ie,m)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}};ee("FlexContainer",{direction:0,wrap:0,justifyContent:0,alignItems:3,gap:{x:0,y:0},padding:{x:0,y:0,z:0,w:0}}),ee("FlexItem",{flexGrow:0,flexShrink:1,flexBasis:-1,order:0});class so{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(ht.PostUpdate,pt([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const io=new so;async function ro(e,t,n){const s=e.getResource(Is);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function oo(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 ao=Me({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),lo=Me(null,"PhysicsAPI");function co(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ho(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class uo{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(ao,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=oo(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([ce]);for(const n of t){const t=e.world.get(n,ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),r=1/i,o=e.world;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(ht.PostUpdate,pt([Pe(Ce)],a=>{const l=o.getEntitiesWithComponents([me,ie]),c=new Set;for(const i of l){c.add(i);const a=o.get(i,me),l=o.get(i,ie);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=co(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*r,l.worldPosition.y*r,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),fo(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===be.Kinematic){const e=co(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*r,l.worldPosition.y*r,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),r=i>>2;for(let i=0;i<s;i++){const s=r+4*i,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,ie);if(!d)continue;let h=a,u=l,f=c;if(e.world.has(o,he)){const t=e.world.get(o,he);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ie)){const n=e.world.get(t.entity,ie),s=co(n.worldRotation),i=a-n.worldPosition.x,r=l-n.worldPosition.y,o=Math.cos(-s),d=Math.sin(-s);h=(i*o-r*d)/(0!==n.worldScale.x?n.worldScale.x:1),u=(i*d+r*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}d.position.x=h,d.position.y=u;const p=ho(f);d.rotation.w=p.w,d.rotation.x=p.x,d.rotation.y=p.y,d.rotation.z=p.z,e.world.insert(o,ie,d)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let r=0;r<i;r++){const i=e+6*r;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;r.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],d=t._physics_getSensorExitCount();if(d>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<d;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(ao,{collisionEnters:s,collisionExits:r,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(lo,po._fromModule(s)),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function fo(e,t,n){const s=e.world;if(s.has(n,we)){const e=s.get(n,we);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,xe)){const e=s.get(n,xe);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,ve)){const e=s.get(n,ve);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 po{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(po.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 go={nearest:0,linear:1},yo={repeat:0,clamp:1,mirror:2};function _o(e,t,n=!0,s){const i=e.getResourceManager(),r=e._malloc(t.pixels.length);let o;if(e.HEAPU8.set(t.pixels,r),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=go[s.filterMode??"linear"]??1,a=yo[s.wrapMode??"clamp"]??1;o=i.createTextureEx(t.width,t.height,r,t.pixels.length,1,n,e,a)}else o=i.createTexture(t.width,t.height,r,t.pixels.length,1,n);return e._free(r),o}function mo(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 wo(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),r=e.worldScale.y*t*(s?-1:1),o=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,d=e.worldRotation.w,h=a+a,u=l+l,f=c+c,p=a*h,g=a*u,y=a*f,_=l*u,m=l*f,w=c*f,x=d*h,v=d*u,b=d*f;return new Float32Array([(1-(_+w))*i,(g+b)*i,(y-v)*i,0,(g-b)*r,(1-(p+w))*r,(m+x)*r,0,(y+v)*o,(m-x)*o,(1-(p+_))*o,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function xo(e,t,n,s,i,r,o,a,l){const c=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const r of t.entities)for(const t of r.components){const r=Gt(t.type);for(const o of r){if("texture"!==o.type)continue;const r=t.data[o.field];if("string"==typeof r&&r&&void 0===s[r])try{const t=i?.[r];s[r]=_o(e,await n.loadPixels(r),!0,t)}catch{s[r]=0}}}return s}(t,n,s);!function(e,t,n){if(!t.textureMetadata)return;const s=e.getResourceManager();for(const e in t.textureMetadata){const i=n[e];if(i&&i>0){const n=t.textureMetadata[e];if(n?.sliceBorder){const e=n.sliceBorder;s.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(t,n,c);let d={},h=null;if(i&&(h=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(i),d=await async function(e,t,n,s,i){const r={};for(const o of s.entities)for(const s of o.components){const o=qt(s.type);if(!o||!s.data)continue;const a=s.data[o.skeletonField],l=s.data[o.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),d=i.resolvePath(l);try{const s=await i.readText(l),o="binary"===fn(c)?.contentType;let h,u;if(o){const e=await i.readBinary(a);u=e.length,h=t._malloc(u),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);u=n.length,h=t._malloc(u+1),t.HEAPU8.set(n,h),t.HEAPU8[h+u]=0}const f=n.loadSkeleton(h,u,s,s.length,o);if(t._free(h),f<0)continue;r[a]=f;const p=mo(s),g=d.substring(0,d.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=g+"/"+p[t];try{const r=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),o=_o(e,r,!1),a=e.getResourceManager().getTextureGLId(o);n.setAtlasPageTexture(f,t,a,r.width,r.height)}catch{}}}catch{}}return r}(t,i,h,n,s)),r){const t={gravity:o?.gravity??{...P},fixedTimestep:o?.fixedTimestep??T,subStepCount:o?.subStepCount??4};new uo("",t,()=>Promise.resolve(r)).build(e)}const u=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=Gt(t.type).find(e=>"font"===e.type);if(!i)continue;const r=t.data[i.field];if("string"==typeof r&&r&&void 0===s[r])try{let t,i;const o=fn(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await n.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){s[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),l=a?`${a}/${o}`:o;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[r]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),d=_o(e,c,!1),h=e.getResourceManager();s[r]=h.loadBitmapFont(t,d,c.width,c.height)}catch{s[r]=0}}return s}(t,n,s),f=await async function(e,t){const n={},s={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Gt(e.type).find(e=>"material"===e.type);if(!i)continue;const r=e.data[i.field];if("string"==typeof r&&r&&void 0===n[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){n[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=s[i];o||(o=Bt.createShader(e.vertexSource,e.fragmentSource),s[i]=o),n[r]=Bt.createFromAsset(e,o)}catch{n[r]=0}}return n}(n,s);!function(e,t,n,s){const i={texture:t,material:s,font:n};for(const t of e.entities)for(const e of t.components){const t=Gt(e.type);if(0===t.length)continue;const n=e.data;for(const e of t)"string"==typeof n[e.field]&&(n[e.field]=i[e.type][n[e.field]]||0)}}(n,c,u,f);const p=tn(e.world,n);if(l&&e.hasResource(Is))for(const t of p.values())e.world.insert(t,ye,{scene:l,persistent:!1});if(i&&h){const s=function(e,t,n,s){const i={};for(const r of t.entities)if(!1!==r.visible)for(const t of r.components){const o=qt(t.type);if(!o||!t.data)continue;const a=n[t.data[o.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(r.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,p);!function(e,t,n,s,i){let r=0;e.setSpineRenderer((o,a)=>{let l=a-r;r=a,(l<=0||l>.5)&&(l=M);const c=e.world;for(const e in i){const r=Number(e),o=i[e],a=c.has(r,pe)?c.get(r,pe):null,d=!1!==a?.playing,h=a?.timeScale??1;d&&s.update(o,l*h);let u=0;if(c.has(r,ie)){const e=wo(c.get(r,ie),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);u=t._malloc(64),t.HEAPF32.set(e,u>>2)}const f=s.getMeshBatchCount(o);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(o,e),r=s.getMeshBatchIndexCount(o,e);if(!i||!r)continue;const a=8*i*4,l=2*r,c=n._malloc(a),d=n._malloc(l),h=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(o,e,c,d,h,f);const p=n.HEAPU32[h>>2],g=n.HEAPU32[f>>2],y=new Float32Array(n.HEAPF32.buffer,c,8*i),_=new Uint16Array(n.HEAPU8.buffer,d,r),m=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(y,m>>2),new Uint16Array(t.HEAPU8.buffer,w,r).set(_),t.renderer_submitTriangles(m,i,w,r,p,g,u),t._free(m),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(Pn);t&&t.setAddressableManifest(a)}}function vo(e,t,n){return{name:e,async setup(){await xo(n.app,n.module,t,n.provider,n.spineModule,n.physicsModule,n.physicsConfig,n.manifest,e)}}}class bo{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=qt(e.type);if(i){const s=e.data[i.skeletonField],r=e.data[i.atlasField];s&&("binary"===fn(s)?.contentType?n.add(s):t.add(s)),r&&t.add(r)}const r=Gt(e.type);for(const n of r){const i=e.data[n.field];"string"==typeof i&&i&&("font"===n.type?(s.add(i),t.add(i)):"material"===n.type&&t.add(i))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const r=[];for(const e of s){const t=fn(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||r.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}r.length>0&&await Promise.all(r)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),r=new OffscreenCanvas(i.width,i.height).getContext("2d");r.drawImage(i,0,0);const o=r.getImageData(0,0,i.width,i.height);return i.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const So="__preview__";class Mo{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(Is);t.register({name:So,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(So),this.loadPromise_=t.load(So).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new bo(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await xo(this.app_,this.app_.wasmModule,t,n,s,null,void 0,null,So)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([le]);for(const s of n){if(e.get(s,le).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([ce]);for(const i of s){const s=e.get(i,ce);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(Is).getScene(So),r=i?i.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(r,ie,o);const a={isActive:!0,projectionType:te.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:ne.ColorAndDepth};e.insert(r,le,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(Is);await e.switchTo(So),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 Po={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),Po.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 To;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(To||(To={}));class Eo{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${To[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case To.Debug:console.debug(t,n);break;case To.Info:console.log(t,n);break;case To.Warn:console.warn(t,n);break;case To.Error:console.error(t,n)}}}class Ro{constructor(){this.handlers_=[],this.minLevel_=To.Info,this.addHandler(new Eo)}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(To.Debug,e,t,n)}info(e,t,n){this.log(To.Info,e,t,n)}warn(e,t,n){this.log(To.Warn,e,t,n)}error(e,t,n){this.log(To.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 Co=new Ro;function Ao(){return Co}function ko(e){Co.setMinLevel(e)}function Io(e,t,n){Co.debug(e,t,n)}function Fo(e,t,n){Co.info(e,t,n)}function Bo(e,t,n){Co.warn(e,t,n)}function zo(e,t,n){Co.error(e,t,n)}const Uo=[Ci,Xi,Ji,xr,Rr,lr,kr,zr,Or,Sr,pr,Hr,jr,qr,Jr,no,io];function $o(e,t){return function(e,t){const n=Us.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Yn(e),kt(e),as(e),us(e),xs(e),Ms(e);const i=new Es;n.setPipeline(i);let r=u();const o=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,r){r||(r=Hs(e,s,t,i));const o=n.getResource(Mt);if(r.length>0){const e=r[0],n=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(n.x*t),o.vpY=Math.round((1-n.y-n.h)*i),o.vpW=Math.round(n.w*t),o.vpH=Math.round(n.h*i),o.screenW=t,o.screenH=i,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}n.insertResource(Mt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=o();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;bs.setClearColor(e.x,e.y,e.z,e.w)}const d=(u()-r)/1e3;let h;if(bs.resize(t,l),gs.isInitialized()&&gs.getPassCount()>0&&!gs.isBypassed()&&gs.resize(t,l),n.hasResource(Is)){const e=n.getResource(Is).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Hs(e,s,t,l,n.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:Ds,width:t,height:l,elapsed:d});else{for(const e of f){const n=e.viewportRect,r=Math.round(n.x*t),o=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:r,y:o,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}bs.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(ht.First,l),n.addSystemToSchedule(ht.Last,c),n.addPlugin(En),n.addPlugin(Dn),n.addPlugin(St),n.addPlugin(zs),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Uo,...t})}e=p;export{je as Added,Us as App,Tn as AssetPlugin,Rn as AssetRefCounter,Mn as AssetServer,Pn as Assets,Xt as AsyncCache,fe as BitmapText,Pt as BlendMode,be as BodyType,we as BoxCollider,Vi as Button,Ni as ButtonState,le as Camera,ce as Canvas,ve as CapsuleCollider,Ne as Changed,ue as Children,xe as CircleCollider,ne as ClearFlags,tt as Commands,st as CommandsInstance,y as DEFAULT_DESIGN_HEIGHT,g as DEFAULT_DESIGN_WIDTH,M as DEFAULT_FALLBACK_DT,T as DEFAULT_FIXED_TIMESTEP,x as DEFAULT_FONT_FAMILY,v as DEFAULT_FONT_SIZE,P as DEFAULT_GRAVITY,b as DEFAULT_LINE_HEIGHT,S as DEFAULT_MAX_DELTA_TIME,_ as DEFAULT_PIXELS_PER_UNIT,E as DEFAULT_SPINE_SKIN,w as DEFAULT_SPRITE_SIZE,m as DEFAULT_TEXT_CANVAS_SIZE,ns as DataType,Ar as DragState,Cr as Draggable,Gn as Draw,Kr as Dropdown,nt as EntityCommands,lt as EventReader,dt as EventReaderInstance,ot as EventRegistry,at as EventWriter,ct as EventWriterInstance,Js as FillDirection,yr as FillMethod,_r as FillOrigin,ur as FocusManager,hr as FocusManagerState,dr as Focusable,Ts as GLDebug,ds as Geometry,ut as GetWorld,A as INVALID_ENTITY,I as INVALID_FONT,F as INVALID_MATERIAL,k as INVALID_TEXTURE,mr as Image,gr as ImageType,vt as Input,bt as InputPlugin,xt as InputState,Yi as Interactable,Nr as ListView,re as LocalTransform,To as LogLevel,Ro as Logger,Bt as Material,Yt as MaterialLoader,Xe as Mut,ge as Name,he as Parent,po as Physics,ao as PhysicsEvents,uo as PhysicsPlugin,gs as PostProcess,zn as PrefabServer,Un as Prefabs,$n as PrefabsPlugin,Mo as PreviewPlugin,Pr as ProgressBar,Mr as ProgressBarDirection,Er as ProgressBarPlugin,te as ProjectionType,Je as Query,Qe as QueryInstance,Ze as Removed,et as RemovedQueryInstance,Es as RenderPipeline,_s as RenderStage,Po as RenderTexture,bs as Renderer,Pe as Res,Te as ResMut,me as RigidBody,R as RuntimeConfig,Xr as SafeArea,se as ScaleMode,Is as SceneManager,ks as SceneManagerState,ye as SceneOwner,ht as Schedule,Ir as ScrollView,Ht as ShaderSources,$r as Slider,Ur as SliderDirection,Wr as SliderPlugin,pe as SpineAnimation,ae as Sprite,wt as SystemRunner,Pi as Text,bi as TextAlign,cr as TextInput,fr as TextInputPlugin,Mi as TextOverflow,Ri as TextPlugin,Ti as TextRenderer,Si as TextVerticalAlign,Ce as Time,vr as Toggle,ie as Transform,Mt as UICameraInfo,Gi as UIEventQueue,qi as UIEvents,ji as UIInteraction,ar as UIInteractionPlugin,Ki as UILayoutPlugin,Ii as UIMask,Hi as UIMaskPlugin,Zs as UIRect,so as UIRenderOrderPlugin,de as Velocity,bo as WebAssetProvider,He as World,oe as WorldTransform,_t as addStartupSystem,yt as addSystem,mt as addSystemToSchedule,oi as applyDirectionalFill,C as applyRuntimeConfig,En as assetPlugin,ts as clearDrawCallbacks,V as clearUserComponents,$ as color,si as computeFillAnchors,ri as computeFillSize,ii as computeHandleAnchors,Qs as computeUIRectLayout,Oi as createMaskProcessor,vo as createRuntimeSceneConfig,$o as createWebApp,Io as debug,Y as defineComponent,it as defineEvent,Me as defineResource,pt as defineSystem,j as defineTag,zo as error,an as findEntityByName,$s as flushPendingSystems,gn as getAddressableType,yn as getAddressableTypeByEditorType,mn as getAllAssetExtensions,bn as getAssetMimeType,fn as getAssetTypeEntry,Z as getComponent,Gt as getComponentAssetFieldDescriptors,Vt as getComponentAssetFields,_e as getComponentDefaults,Qt as getComponentEntityFields,qt as getComponentSpineFieldDescriptor,xn as getCustomExtensions,pn as getEditorType,Ao as getLogger,t as getPlatform,s as getPlatformType,N as getUserComponent,vn as getWeChatPackOptions,Fo as info,Yn as initDrawAPI,Ms as initGLDebugAPI,as as initGeometryAPI,kt as initMaterialAPI,us as initPostProcessAPI,xs as initRendererAPI,St as inputPlugin,An as instantiatePrefab,Fi as intersectRects,Bi as invertMatrix4,K as isBuiltinComponent,Sn as isCustomExtension,tr as isEditor,_n as isKnownAssetExtension,n as isPlatformInitialized,ir as isPlayMode,nr as isRuntime,Tt as isTextureRef,i as isWeChat,r as isWeb,rn as loadComponent,oo as loadPhysicsModule,xo as loadRuntimeScene,tn as loadSceneData,nn as loadSceneWithAssets,wn as looksLikeAssetPath,o as platformFetch,c as platformFileExists,d as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,Li as pointInOBB,Ui as pointInWorldRect,Dn as prefabsPlugin,Rr as progressBarPlugin,D as quat,Q as registerComponent,Nt as registerComponentAssetFields,Jt as registerComponentEntityFields,Zn as registerDrawCallback,Cn as registerEmbeddedAssets,Ot as registerMaterialCallback,Zt as remapEntityFields,zs as sceneManagerPlugin,zi as screenToWorld,er as setEditorMode,Gr as setListViewRenderer,ko as setLogLevel,sr as setPlayMode,Be as setWasmErrorHandler,jn as shutdownDrawAPI,Ps as shutdownGLDebugAPI,ls as shutdownGeometryAPI,It as shutdownMaterialAPI,fs as shutdownPostProcessAPI,vs as shutdownRendererAPI,Or as sliderPlugin,pi as syncFillSpriteSize,pr as textInputPlugin,Ci as textPlugin,ro as transitionTo,lr as uiInteractionPlugin,Ji as uiLayoutPlugin,Xi as uiMaskPlugin,Uo as uiPlugins,io as uiRenderOrderPlugin,G as unregisterComponent,es as unregisterDrawCallback,on as updateCameraAspectRatio,B as vec2,z as vec3,U as vec4,Bo as warn,Fs 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 dedbb695f..f76b43ce1 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -689,8 +689,11 @@ declare enum Schedule {
FixedUpdate = 11,
FixedPostUpdate = 12
}
+interface GetWorldDescriptor {
+ readonly _type: 'get_world';
+}
type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
-type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef>;
+type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
interface SystemDef {
readonly _id: symbol;
readonly _params: readonly SystemParam[];
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 1beaa4cbf..9b7fbb88d 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -641,8 +641,11 @@ declare enum Schedule {
FixedUpdate = 11,
FixedPostUpdate = 12
}
+interface GetWorldDescriptor {
+ readonly _type: 'get_world';
+}
type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
-type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef>;
+type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
interface SystemDef {
readonly _id: symbol;
readonly _params: readonly SystemParam[];
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 54de442ea..ace34a6ee 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -84,7 +84,11 @@ export default defineConfig({
label: 'UI',
translations: { 'zh-CN': 'UI' },
items: [
- { label: 'UI & Text', translations: { 'zh-CN': 'UI 与文本' }, slug: 'guides/ui' },
+ { label: 'Layout', translations: { 'zh-CN': '布局' }, slug: 'guides/ui' },
+ { label: 'Text & Image', translations: { 'zh-CN': '文本与图片' }, slug: 'guides/ui-text' },
+ { label: 'Interaction', translations: { 'zh-CN': '交互' }, slug: 'guides/ui-interaction' },
+ { label: 'Widgets', translations: { 'zh-CN': '控件' }, slug: 'guides/ui-widgets' },
+ { label: 'Masking & SafeArea', translations: { 'zh-CN': '遮罩与安全区' }, slug: 'guides/ui-masking' },
],
},
{ label: 'Asset Loading', translations: { 'zh-CN': '资源加载' }, slug: 'guides/assets' },
diff --git a/docs/astro/src/content/docs/core-concepts/components.mdx b/docs/astro/src/content/docs/core-concepts/components.mdx
index a1dedda90..e63d6a866 100644
--- a/docs/astro/src/content/docs/core-concepts/components.mdx
+++ b/docs/astro/src/content/docs/core-concepts/components.mdx
@@ -100,7 +100,7 @@ GPU-rendered text using pre-baked bitmap font atlases (BMFont format). Requires
### Text
-UI text rendering. Works with `UIRect` and `Sprite` to display text. See [UI & Text guide](/microes/guides/ui/) for full details.
+UI text rendering. Works with `UIRect` and `Sprite` to display text. See [Text & Image](/microes/guides/ui-text/) for full details.
| Property | Type | Description |
|----------|------|-------------|
@@ -129,7 +129,7 @@ UI layout rectangle. Defines anchored layout for UI elements.
### UIMask
-Clips child entities to the parent's `UIRect` bounds. Requires `UIRect` and `Transform` on the same entity. See [UI & Text guide](/microes/guides/ui/) for details.
+Clips child entities to the parent's `UIRect` bounds. Requires `UIRect` and `Transform` on the same entity. See [Masking & SafeArea](/microes/guides/ui-masking/) for details.
| Property | Type | Default | Description |
|----------|------|---------|-------------|
diff --git a/docs/astro/src/content/docs/core-concepts/resources.mdx b/docs/astro/src/content/docs/core-concepts/resources.mdx
index 14bf8440f..076681bc4 100644
--- a/docs/astro/src/content/docs/core-concepts/resources.mdx
+++ b/docs/astro/src/content/docs/core-concepts/resources.mdx
@@ -103,7 +103,7 @@ defineSystem([Res(UIEvents)], (events) => {
});
```
-See [UI & Text](/microes/guides/ui/) for the full list of event types.
+See [UI Interaction](/microes/guides/ui-interaction/) for the full list of event types.
## Custom Resources
diff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdx
index e65af7865..120bd0784 100644
--- a/docs/astro/src/content/docs/core-concepts/systems.mdx
+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx
@@ -27,7 +27,7 @@ This system automatically processes every entity in the scene that has both `Tra
`defineSystem` takes two arguments:
-1. **Parameters** — an array of `Query`, `Res`, `ResMut`, `Commands`, `EventWriter`, or `EventReader` descriptors
+1. **Parameters** — an array of `Query`, `Res`, `ResMut`, `Commands`, `GetWorld`, `EventWriter`, or `EventReader` descriptors
2. **Function** — receives the resolved parameters in the same order
## Registering Systems
@@ -222,12 +222,43 @@ defineSystem([EventReader(DamageEvent)], (reader) => {
See [Events](/microes/core-concepts/events/) for the full API.
+### GetWorld
+
+Direct access to the ECS World. Use it with `world.get()` / `world.set()` for O(1) component access by entity ID, or with utility functions like `findEntityByName()`:
+
+```typescript
+import { GetWorld, findEntityByName, ProgressBar } from 'esengine';
+
+defineSystem([GetWorld()], (world) => {
+ const entity = findEntityByName(world, 'HealthBar');
+ if (entity) {
+ const bar = world.get(entity, ProgressBar);
+ bar.value = playerHealth / maxHealth;
+ world.set(entity, ProgressBar, bar);
+ }
+});
+```
+
+#### World API
+
+| Method | Returns | Description |
+|--------|---------|-------------|
+| `world.get(entity, Component)` | component data | Read a component (O(1)) |
+| `world.set(entity, Component, data)` | void | Write a component (O(1)) |
+| `world.has(entity, Component)` | boolean | Check if entity has component |
+| `world.tryGet(entity, Component)` | data \| null | Safe read, returns null if missing |
+| `world.valid(entity)` | boolean | Check if entity is alive |
+
+<Aside type="tip">
+ Prefer `Query` + `Mut()` when iterating multiple entities — it handles auto-writeback. Use `GetWorld()` when you need to access a **known entity by ID** without iteration, e.g. after `findEntityByName()`.
+</Aside>
+
### Combining Parameters
```typescript
defineSystem(
- [Commands(), Res(Time), Res(Input), Query(Mut(Transform), Velocity)],
- (cmds, time, input, query) => {
+ [Commands(), Res(Time), Res(Input), GetWorld(), Query(Mut(Transform), Velocity)],
+ (cmds, time, input, world, query) => {
// All parameters available
}
);
diff --git a/docs/astro/src/content/docs/guides/bitmap-text.mdx b/docs/astro/src/content/docs/guides/bitmap-text.mdx
index e92fbb1a1..75b0cd6f1 100644
--- a/docs/astro/src/content/docs/guides/bitmap-text.mdx
+++ b/docs/astro/src/content/docs/guides/bitmap-text.mdx
@@ -144,6 +144,6 @@ BitmapText follows the same draw ordering as Sprite:
## Next Steps
- [Asset Loading](/microes/guides/assets/) — loading bitmap fonts and other assets
-- [UI & Text](/microes/guides/ui/) — Canvas 2D text and UI layout
+- [Text & Image](/microes/guides/ui-text/) — Canvas 2D text and UI layout
- [Rendering](/microes/guides/rendering/) — camera, transform, and render order
- [Components](/microes/core-concepts/components/) — all builtin components
diff --git a/docs/astro/src/content/docs/guides/input.mdx b/docs/astro/src/content/docs/guides/input.mdx
index 27fb2533a..5f1eeb4ff 100644
--- a/docs/astro/src/content/docs/guides/input.mdx
+++ b/docs/astro/src/content/docs/guides/input.mdx
@@ -175,6 +175,6 @@ addSystem(defineSystem(
## Next Steps
-- [UI & Text](/microes/guides/ui/) — UI interaction events (click, hover, press)
+- [UI Interaction](/microes/guides/ui-interaction/) — UI interaction events (click, hover, press)
- [Physics](/microes/guides/physics/) — physics-driven movement and collision
- [Systems](/microes/core-concepts/systems/) — defining and scheduling systems
diff --git a/docs/astro/src/content/docs/guides/ui-interaction.mdx b/docs/astro/src/content/docs/guides/ui-interaction.mdx
new file mode 100644
index 000000000..1f44d7e86
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-interaction.mdx
@@ -0,0 +1,74 @@
+---
+title: UI Interaction
+description: Pointer events, focus, and drag for UI elements in ESEngine
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## Interactable
+
+Marks a UI entity as interactive (receives pointer events). Required for all interactive widgets.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `enabled` | boolean | `true` | Whether interaction is active |
+| `blockRaycast` | boolean | `true` | Block events from reaching elements behind |
+
+## UIInteraction
+
+Automatically added by the plugin to entities with `Interactable`. Provides per-entity state:
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `hovered` | boolean | Pointer is over this entity |
+| `pressed` | boolean | Entity is being pressed |
+| `justPressed` | boolean | Press started this frame |
+| `justReleased` | boolean | Press released this frame |
+
+## UIEvents
+
+The `UIEvents` resource collects interaction events each frame:
+
+```typescript
+import { defineSystem, addSystem, Res } from 'esengine';
+import { UIEvents } from 'esengine';
+
+addSystem(defineSystem(
+ [Res(UIEvents)],
+ (events) => {
+ for (const e of events.query('click')) {
+ console.log('Clicked:', e.entity);
+ }
+ }
+));
+```
+
+**Event types:** `click`, `press`, `release`, `hover_enter`, `hover_exit`, `focus`, `blur`, `submit`, `change`, `drag_start`, `drag_move`, `drag_end`, `scroll`
+
+Events bubble up the entity hierarchy. If a parent has `Interactable` with `blockRaycast: true`, bubbling stops there.
+
+## Focusable
+
+Enables keyboard focus and Tab navigation.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `tabIndex` | number | `0` | Focus order (lower = earlier) |
+| `isFocused` | boolean | `false` | Current focus state |
+
+## Draggable
+
+Enables drag-to-move on a UI element.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `enabled` | boolean | `true` | Enable dragging |
+| `dragThreshold` | number | `5` | Pixels before drag starts |
+| `lockX` | boolean | `false` | Lock horizontal movement |
+| `lockY` | boolean | `false` | Lock vertical movement |
+
+## Next Steps
+
+- [Widgets](/microes/guides/ui-widgets/) — buttons, sliders, toggles, and more
+- [UI Layout](/microes/guides/ui/) — anchors, flex, and grid layout
+- [Input Handling](/microes/guides/input/) — keyboard, mouse, and touch input
diff --git a/docs/astro/src/content/docs/guides/ui-masking.mdx b/docs/astro/src/content/docs/guides/ui-masking.mdx
new file mode 100644
index 000000000..b7f77633a
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-masking.mdx
@@ -0,0 +1,38 @@
+---
+title: Masking & SafeArea
+description: UI clipping and device safe area adaptation in ESEngine
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## UIMask
+
+Clips child entities to the parent's `UIRect` bounds.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `enabled` | boolean | `true` | Whether clipping is active |
+| `mode` | MaskMode | `Scissor` | `Scissor` (0), `Stencil` (1) |
+
+Nested `UIMask` entities clip to the intersection of all parent masks.
+
+<Aside type="caution">
+ `UIMask` only clips **child** entities — the entity with UIMask itself is not clipped.
+</Aside>
+
+## SafeArea
+
+Adapts layout to device safe areas (notches, rounded corners). Useful for mobile and WeChat MiniGame.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `applyTop` | boolean | `true` | Apply to top edge |
+| `applyBottom` | boolean | `true` | Apply to bottom edge |
+| `applyLeft` | boolean | `true` | Apply to left edge |
+| `applyRight` | boolean | `true` | Apply to right edge |
+
+## Next Steps
+
+- [UI Layout](/microes/guides/ui/) — anchors, flex, and grid layout
+- [Widgets](/microes/guides/ui-widgets/) — buttons, sliders, toggles, and more
+- [WeChat MiniGame](/microes/guides/wechat/) — platform-specific considerations
diff --git a/docs/astro/src/content/docs/guides/ui-text.mdx b/docs/astro/src/content/docs/guides/ui-text.mdx
new file mode 100644
index 000000000..ef5ab254d
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-text.mdx
@@ -0,0 +1,88 @@
+---
+title: Text & Image
+description: Text rendering and image display for UI in ESEngine
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## Text
+
+Renders styled text into a `Sprite` texture automatically via `TextPlugin`.
+
+**Setup:** Add `Transform`, `Sprite`, `UIRect`, and `Text` to an entity.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `content` | string | `''` | Text content |
+| `fontFamily` | string | `'Arial'` | Font family name |
+| `fontSize` | number | `24` | Font size in pixels |
+| `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color RGBA |
+| `align` | TextAlign | `Left` | `Left` (0), `Center` (1), `Right` (2) |
+| `verticalAlign` | TextVerticalAlign | `Top` | `Top` (0), `Middle` (1), `Bottom` (2) |
+| `wordWrap` | boolean | `true` | Enable word wrapping |
+| `overflow` | TextOverflow | `Visible` | `Visible` (0), `Clip` (1), `Ellipsis` (2) |
+| `lineHeight` | number | `1.2` | Line height multiplier |
+
+<Aside type="note">
+ You don't need to configure the Sprite manually. `TextPlugin` creates and updates the texture from the Text content.
+</Aside>
+
+### Modifying Text at Runtime
+
+```typescript
+import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';
+
+addSystem(defineSystem(
+ [Query(Mut(Text))],
+ (query) => {
+ for (const [entity, text] of query) {
+ text.content = 'Updated!';
+ text.fontSize = 32;
+ }
+ }
+));
+```
+
+## Image
+
+Displays images with support for slicing, tiling, and fill modes.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `texture` | number | — | Texture asset handle |
+| `color` | Color | `{r:1, g:1, b:1, a:1}` | Color tint |
+| `imageType` | ImageType | `Simple` | `Simple` (0), `Sliced` (1), `Tiled` (2), `Filled` (3) |
+| `fillMethod` | FillMethod | `Horizontal` | `Horizontal` (0), `Vertical` (1) |
+| `fillOrigin` | FillOrigin | `Left` | `Left` (0), `Right` (1), `Bottom` (2), `Top` (3) |
+| `fillAmount` | number | `1` | Fill progress 0–1 |
+| `preserveAspect` | boolean | `false` | Maintain aspect ratio |
+| `enabled` | boolean | `true` | Visibility toggle |
+
+## Example: Score Display
+
+```typescript
+import { defineTag, defineComponent, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';
+
+const ScoreDisplay = defineTag('ScoreDisplay');
+const GameState = defineComponent('GameState', { score: 0 });
+
+addSystem(defineSystem(
+ [Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],
+ (displays, stateQuery) => {
+ if (stateQuery.isEmpty()) return;
+ const [, state] = stateQuery.single()!;
+ for (const [, text] of displays) {
+ text.content = `Score: ${state.score}`;
+ }
+ }
+));
+```
+
+Uses [Change Detection](/microes/core-concepts/change-detection/) to only update text when the score actually changes.
+
+## Next Steps
+
+- [UI Layout](/microes/guides/ui/) — anchors, flex, and grid layout
+- [Interaction](/microes/guides/ui-interaction/) — pointer events, focus, and drag
+- [Bitmap Text](/microes/guides/bitmap-text/) — GPU-rendered bitmap font text
+- [Sprite](/microes/guides/sprite/) — sprite rendering details
diff --git a/docs/astro/src/content/docs/guides/ui-widgets.mdx b/docs/astro/src/content/docs/guides/ui-widgets.mdx
new file mode 100644
index 000000000..337c910d7
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-widgets.mdx
@@ -0,0 +1,305 @@
+---
+title: UI Widgets
+description: Buttons, sliders, toggles, dropdowns, and other UI widgets in ESEngine
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+All widgets require `Interactable` and `UIRect` on the same entity. See [UI Interaction](/microes/guides/ui-interaction/) for event handling.
+
+## Getting a Specific Widget
+
+When you place multiple widgets in a scene, use **Query** to find a specific one.
+
+### By Tag (Recommended)
+
+Define a tag and attach it to the entity in the editor. Then use `query.single()` to get the one matching entity directly:
+
+```typescript
+import { defineTag, defineSystem, addSystem, Query, Mut, ProgressBar } from 'esengine';
+
+const HealthBar = defineTag('HealthBar');
+
+addSystem(defineSystem(
+ [Query(Mut(ProgressBar), HealthBar)],
+ (query) => {
+ const [, bar] = query.single()!;
+ bar.value = playerHealth / maxHealth;
+ }
+));
+```
+
+<Aside type="note">
+ `Mut()` enables auto-writeback — mutating `bar.value` automatically persists the change. No need to write it back manually.
+</Aside>
+
+### By Name
+
+Every entity has a `Name` component set in the editor. Query it together with the widget component:
+
+```typescript
+addSystem(defineSystem(
+ [Query(Mut(ProgressBar), Name)],
+ (query) => {
+ for (const [, bar, name] of query) {
+ if (name.value === 'HealthBar') bar.value = playerHealth / maxHealth;
+ if (name.value === 'ManaBar') bar.value = playerMana / maxMana;
+ if (name.value === 'ExpBar') bar.value = playerExp / expToNextLevel;
+ }
+ }
+));
+```
+
+<Aside type="tip">
+ Prefer tags for production code — they match by type (no string comparison) and catch typos at compile time. Use `Name` for quick prototyping.
+</Aside>
+
+### By `findEntityByName` + Direct Access
+
+Use `GetWorld()` to access the World directly. `findEntityByName()` looks up an entity by its editor name, then `world.get()` / `world.set()` read/write components in O(1):
+
+```typescript
+import { GetWorld, findEntityByName, ProgressBar } from 'esengine';
+
+addSystem(defineSystem(
+ [GetWorld()],
+ (world) => {
+ const entity = findEntityByName(world, 'HealthBar');
+ if (entity) {
+ const bar = world.get(entity, ProgressBar);
+ bar.value = playerHealth / maxHealth;
+ world.set(entity, ProgressBar, bar);
+ }
+ }
+));
+```
+
+---
+
+## Handling Events on a Specific Widget
+
+### With Tag + `hasEvent`
+
+Combine `query.single()` to get the entity ID, then use `UIEvents.hasEvent()` to check directly — no loop:
+
+```typescript
+import { defineTag, defineSystem, addSystem, Res, Query } from 'esengine';
+import { UIEvents, Button } from 'esengine';
+
+const StartButton = defineTag('StartButton');
+
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Button, StartButton)],
+ (events, query) => {
+ const match = query.single();
+ if (match && events.hasEvent(match[0], 'click')) {
+ startGame();
+ }
+ }
+));
+```
+
+### With UIInteraction (No UIEvents Needed)
+
+For simple press/release checks, read the `UIInteraction` component directly:
+
+```typescript
+import { UIInteraction } from 'esengine';
+
+const StartButton = defineTag('StartButton');
+
+addSystem(defineSystem(
+ [Query(UIInteraction, StartButton)],
+ (query) => {
+ const match = query.single();
+ if (match) {
+ const [, interaction] = match;
+ if (interaction.justPressed) startGame();
+ }
+ }
+));
+```
+
+### Matching Events by Name
+
+When handling events from multiple widgets in one system:
+
+```typescript
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Button, Name)],
+ (events, query) => {
+ for (const e of events.query('click')) {
+ for (const [entity, , name] of query) {
+ if (entity === e.entity) {
+ console.log('Clicked:', name.value);
+ }
+ }
+ }
+ }
+));
+```
+
+---
+
+## Button
+
+State machine on top of `Interactable` with optional color transitions.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `state` | ButtonState | `Normal` | `Normal` (0), `Hovered` (1), `Pressed` (2), `Disabled` (3) |
+| `transition` | ColorTransition \| null | `null` | Color per state |
+
+```typescript
+cmds.entity(button).insert(Button, {
+ state: 0,
+ transition: {
+ normalColor: { r: 1, g: 1, b: 1, a: 1 },
+ hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },
+ pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },
+ disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },
+ },
+});
+```
+
+## Toggle
+
+Checkbox with optional group for mutual exclusion.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `isOn` | boolean | `true` | Toggle state |
+| `graphicEntity` | Entity | `0` | Child entity to show/hide (checkmark) |
+| `group` | Entity | `0` | ToggleGroup entity for radio-button behavior |
+| `transition` | ColorTransition \| null | `null` | Color transition |
+
+**ToggleGroup** — attach to a parent entity to make child toggles mutually exclusive:
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `allowSwitchOff` | boolean | `false` | Allow all toggles to be off |
+
+Listen for toggle changes:
+
+```typescript
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Toggle, Name)],
+ (events, query) => {
+ for (const e of events.query('change')) {
+ for (const [entity, toggle, name] of query) {
+ if (entity === e.entity) {
+ console.log(name.value, 'is now:', toggle.isOn);
+ }
+ }
+ }
+ }
+));
+```
+
+## Slider
+
+Interactive value slider with a fill and optional draggable handle.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `value` | number | `0` | Current value |
+| `minValue` | number | `0` | Minimum value |
+| `maxValue` | number | `1` | Maximum value |
+| `direction` | FillDirection | `LeftToRight` | `LeftToRight` (0), `RightToLeft` (1), `BottomToTop` (2), `TopToBottom` (3) |
+| `fillEntity` | Entity | `0` | Child entity for fill visualization |
+| `handleEntity` | Entity | `0` | Child entity for draggable handle |
+| `wholeNumbers` | boolean | `false` | Snap to integers |
+
+Listen for slider changes:
+
+```typescript
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Slider, Name)],
+ (events, query) => {
+ for (const e of events.query('change')) {
+ for (const [entity, slider, name] of query) {
+ if (entity === e.entity) {
+ if (name.value === 'VolumeSlider') setVolume(slider.value);
+ if (name.value === 'BrightnessSlider') setBrightness(slider.value);
+ }
+ }
+ }
+ }
+));
+```
+
+## ProgressBar
+
+Non-interactive progress display.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `value` | number | `0` | Progress 0–1 |
+| `fillEntity` | Entity | `0` | Child entity for fill |
+| `direction` | FillDirection | `LeftToRight` | Fill direction |
+
+## Dropdown
+
+Dropdown list selector.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `options` | string[] | `[]` | Option labels |
+| `selectedIndex` | number | `-1` | Selected option index |
+| `isOpen` | boolean | `false` | List visibility |
+| `listEntity` | Entity | `0` | Child entity for dropdown list |
+| `labelEntity` | Entity | `0` | Child entity for selected label |
+
+## ScrollView
+
+Scrollable container with momentum and elastic bounce.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `contentEntity` | Entity | `0` | Child holding scrollable content |
+| `horizontalEnabled` | boolean | `false` | Enable horizontal scroll |
+| `verticalEnabled` | boolean | `true` | Enable vertical scroll |
+| `scrollX` | number | `0` | Current horizontal offset |
+| `scrollY` | number | `0` | Current vertical offset |
+| `inertia` | boolean | `true` | Enable momentum scrolling |
+| `decelerationRate` | number | `0.135` | Momentum friction |
+| `elastic` | boolean | `true` | Bounce at edges |
+| `wheelSensitivity` | number | `0.1` | Mouse wheel amount |
+
+## ListView
+
+Virtual scrolling for large lists — only visible items are rendered.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `itemHeight` | number | `40` | Fixed item height |
+| `itemCount` | number | `0` | Total items |
+| `scrollY` | number | `0` | Scroll position |
+| `overscan` | number | `2` | Extra items above/below viewport |
+
+## TextInput
+
+Editable text field with cursor, selection, and placeholder.
+
+| Property | Type | Default | Description |
+|----------|------|---------|-------------|
+| `value` | string | `''` | Current text |
+| `placeholder` | string | `''` | Hint when empty |
+| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | Placeholder color |
+| `fontFamily` | string | `'Arial'` | Font family |
+| `fontSize` | number | `16` | Font size |
+| `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color |
+| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | Background color |
+| `padding` | number | `6` | Internal padding |
+| `maxLength` | number | `0` | Max characters (0 = unlimited) |
+| `multiline` | boolean | `false` | Allow line breaks |
+| `password` | boolean | `false` | Mask text |
+| `readOnly` | boolean | `false` | Prevent editing |
+
+**Events:** `change` (value changed), `submit` (Enter pressed in single-line mode)
+
+## Next Steps
+
+- [UI Interaction](/microes/guides/ui-interaction/) — pointer events, focus, and drag
+- [Masking & SafeArea](/microes/guides/ui-masking/) — clipping and device safe areas
+- [UI Layout](/microes/guides/ui/) — anchors, flex, and grid layout
diff --git a/docs/astro/src/content/docs/guides/ui.mdx b/docs/astro/src/content/docs/guides/ui.mdx
index 8daa6856c..73855bef4 100644
--- a/docs/astro/src/content/docs/guides/ui.mdx
+++ b/docs/astro/src/content/docs/guides/ui.mdx
@@ -1,6 +1,6 @@
---
-title: UI & Text
-description: UI components, layout, interaction, and text rendering in ESEngine
+title: UI Layout
+description: UI layout system with anchors, flex, and grid in ESEngine
---
import { Aside } from '@astrojs/starlight/components';
@@ -35,9 +35,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {
}));
```
-## Layout
-
-### UIRect
+## UIRect
Every UI element needs a `UIRect` to participate in layout. It defines position and size relative to the parent using an anchor-based system.
@@ -52,7 +50,7 @@ Every UI element needs a `UIRect` to participate in layout. It defines position
When `anchorMin` equals `anchorMax`, the element has a fixed `size` at the anchor point. When they differ, the element stretches between anchors and size is computed automatically.
-### FlexContainer
+## FlexContainer
CSS Flexbox-like layout for automatic child arrangement.
@@ -65,7 +63,7 @@ CSS Flexbox-like layout for automatic child arrangement.
| `gap` | Vec2 | `{0, 0}` | Spacing between items |
| `padding` | Vec4 | `{0, 0, 0, 0}` | Top, Right, Bottom, Left padding |
-### FlexItem
+## FlexItem
Child properties for entities inside a `FlexContainer`.
@@ -76,7 +74,7 @@ Child properties for entities inside a `FlexContainer`.
| `flexBasis` | number | `-1` | Base size before grow/shrink (-1 = auto) |
| `order` | number | `0` | Display order override |
-### LayoutGroup
+## LayoutGroup
Grid-like layout with direction, spacing, and alignment.
@@ -88,331 +86,9 @@ Grid-like layout with direction, spacing, and alignment.
| `childAlignment` | ChildAlignment | `Start` | `Start`, `Center`, `End` |
| `reverseOrder` | boolean | `false` | Reverse layout order |
-## Text
-
-### Text Component
-
-Renders styled text into a `Sprite` texture automatically via `TextPlugin`.
-
-**Setup:** Add `Transform`, `Sprite`, `UIRect`, and `Text` to an entity.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `content` | string | `''` | Text content |
-| `fontFamily` | string | `'Arial'` | Font family name |
-| `fontSize` | number | `24` | Font size in pixels |
-| `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color RGBA |
-| `align` | TextAlign | `Left` | `Left` (0), `Center` (1), `Right` (2) |
-| `verticalAlign` | TextVerticalAlign | `Top` | `Top` (0), `Middle` (1), `Bottom` (2) |
-| `wordWrap` | boolean | `true` | Enable word wrapping |
-| `overflow` | TextOverflow | `Visible` | `Visible` (0), `Clip` (1), `Ellipsis` (2) |
-| `lineHeight` | number | `1.2` | Line height multiplier |
-
-<Aside type="note">
- You don't need to configure the Sprite manually. `TextPlugin` creates and updates the texture from the Text content.
-</Aside>
-
-### Modifying Text at Runtime
-
-```typescript
-import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';
-
-addSystem(defineSystem(
- [Query(Mut(Text))],
- (query) => {
- for (const [entity, text] of query) {
- text.content = 'Updated!';
- text.fontSize = 32;
- }
- }
-));
-```
-
-### Image
-
-Displays images with support for slicing, tiling, and fill modes.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `texture` | number | — | Texture asset handle |
-| `color` | Color | `{r:1, g:1, b:1, a:1}` | Color tint |
-| `imageType` | ImageType | `Simple` | `Simple` (0), `Sliced` (1), `Tiled` (2), `Filled` (3) |
-| `fillMethod` | FillMethod | `Horizontal` | `Horizontal` (0), `Vertical` (1) |
-| `fillOrigin` | FillOrigin | `Left` | `Left` (0), `Right` (1), `Bottom` (2), `Top` (3) |
-| `fillAmount` | number | `1` | Fill progress 0–1 |
-| `preserveAspect` | boolean | `false` | Maintain aspect ratio |
-| `enabled` | boolean | `true` | Visibility toggle |
-
-## Interaction
-
-### Interactable
-
-Marks a UI entity as interactive (receives pointer events). Required for all interactive widgets.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `enabled` | boolean | `true` | Whether interaction is active |
-| `blockRaycast` | boolean | `true` | Block events from reaching elements behind |
-
-### UIInteraction
-
-Automatically added by the plugin to entities with `Interactable`. Provides per-entity state:
-
-| Property | Type | Description |
-|----------|------|-------------|
-| `hovered` | boolean | Pointer is over this entity |
-| `pressed` | boolean | Entity is being pressed |
-| `justPressed` | boolean | Press started this frame |
-| `justReleased` | boolean | Press released this frame |
-
-### UIEvents
-
-The `UIEvents` resource collects interaction events each frame:
-
-```typescript
-import { defineSystem, addSystem, Res } from 'esengine';
-import { UIEvents } from 'esengine';
-
-addSystem(defineSystem(
- [Res(UIEvents)],
- (events) => {
- for (const e of events.query('click')) {
- console.log('Clicked:', e.entity);
- }
- }
-));
-```
-
-**Event types:** `click`, `press`, `release`, `hover_enter`, `hover_exit`, `focus`, `blur`, `submit`, `change`, `drag_start`, `drag_move`, `drag_end`, `scroll`
-
-Events bubble up the entity hierarchy. If a parent has `Interactable` with `blockRaycast: true`, bubbling stops there.
-
-### Focusable
-
-Enables keyboard focus and Tab navigation.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `tabIndex` | number | `0` | Focus order (lower = earlier) |
-| `isFocused` | boolean | `false` | Current focus state |
-
-## Widgets
-
-### Button
-
-State machine on top of `Interactable` with optional color transitions.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `state` | ButtonState | `Normal` | `Normal` (0), `Hovered` (1), `Pressed` (2), `Disabled` (3) |
-| `transition` | ColorTransition \| null | `null` | Color per state |
-
-```typescript
-cmds.entity(button).insert(Button, {
- state: 0,
- transition: {
- normalColor: { r: 1, g: 1, b: 1, a: 1 },
- hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },
- pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },
- disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },
- },
-});
-```
-
-### Toggle
-
-Checkbox with optional group for mutual exclusion.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `isOn` | boolean | `true` | Toggle state |
-| `graphicEntity` | Entity | `0` | Child entity to show/hide (checkmark) |
-| `group` | Entity | `0` | ToggleGroup entity for radio-button behavior |
-| `transition` | ColorTransition \| null | `null` | Color transition |
-
-**ToggleGroup** — attach to a parent entity to make child toggles mutually exclusive:
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `allowSwitchOff` | boolean | `false` | Allow all toggles to be off |
-
-### Slider
-
-Interactive value slider with a fill and optional draggable handle.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `value` | number | `0` | Current value |
-| `minValue` | number | `0` | Minimum value |
-| `maxValue` | number | `1` | Maximum value |
-| `direction` | FillDirection | `LeftToRight` | `LeftToRight` (0), `RightToLeft` (1), `BottomToTop` (2), `TopToBottom` (3) |
-| `fillEntity` | Entity | `0` | Child entity for fill visualization |
-| `handleEntity` | Entity | `0` | Child entity for draggable handle |
-| `wholeNumbers` | boolean | `false` | Snap to integers |
-
-Listen for value changes:
-
-```typescript
-addSystem(defineSystem(
- [Res(UIEvents), Query(Slider)],
- (events, query) => {
- for (const e of events.query('change')) {
- for (const [entity, slider] of query) {
- if (entity === e.entity) {
- console.log('Slider value:', slider.value);
- }
- }
- }
- }
-));
-```
-
-### ProgressBar
-
-Non-interactive progress display.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `value` | number | `0` | Progress 0–1 |
-| `fillEntity` | Entity | `0` | Child entity for fill |
-| `direction` | FillDirection | `LeftToRight` | Fill direction |
-
-```typescript
-// Update progress
-addSystem(defineSystem(
- [Res(Time), Query(Mut(ProgressBar))],
- (time, query) => {
- for (const [entity, bar] of query) {
- bar.value = Math.min(1, bar.value + time.delta * 0.1);
- }
- }
-));
-```
-
-### Dropdown
-
-Dropdown list selector.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `options` | string[] | `[]` | Option labels |
-| `selectedIndex` | number | `-1` | Selected option index |
-| `isOpen` | boolean | `false` | List visibility |
-| `listEntity` | Entity | `0` | Child entity for dropdown list |
-| `labelEntity` | Entity | `0` | Child entity for selected label |
-
-### ScrollView
-
-Scrollable container with momentum and elastic bounce.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `contentEntity` | Entity | `0` | Child holding scrollable content |
-| `horizontalEnabled` | boolean | `false` | Enable horizontal scroll |
-| `verticalEnabled` | boolean | `true` | Enable vertical scroll |
-| `scrollX` | number | `0` | Current horizontal offset |
-| `scrollY` | number | `0` | Current vertical offset |
-| `inertia` | boolean | `true` | Enable momentum scrolling |
-| `decelerationRate` | number | `0.135` | Momentum friction |
-| `elastic` | boolean | `true` | Bounce at edges |
-| `wheelSensitivity` | number | `0.1` | Mouse wheel amount |
-
-### ListView
-
-Virtual scrolling for large lists — only visible items are rendered.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `itemHeight` | number | `40` | Fixed item height |
-| `itemCount` | number | `0` | Total items |
-| `scrollY` | number | `0` | Scroll position |
-| `overscan` | number | `2` | Extra items above/below viewport |
-
-### TextInput
-
-Editable text field with cursor, selection, and placeholder.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `value` | string | `''` | Current text |
-| `placeholder` | string | `''` | Hint when empty |
-| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | Placeholder color |
-| `fontFamily` | string | `'Arial'` | Font family |
-| `fontSize` | number | `16` | Font size |
-| `color` | Color | `{r:1, g:1, b:1, a:1}` | Text color |
-| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | Background color |
-| `padding` | number | `6` | Internal padding |
-| `maxLength` | number | `0` | Max characters (0 = unlimited) |
-| `multiline` | boolean | `false` | Allow line breaks |
-| `password` | boolean | `false` | Mask text |
-| `readOnly` | boolean | `false` | Prevent editing |
-
-**Events:** `change` (value changed), `submit` (Enter pressed in single-line mode)
-
-### Draggable
-
-Enables drag-to-move on a UI element.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `enabled` | boolean | `true` | Enable dragging |
-| `dragThreshold` | number | `5` | Pixels before drag starts |
-| `lockX` | boolean | `false` | Lock horizontal movement |
-| `lockY` | boolean | `false` | Lock vertical movement |
-
-## Masking
-
-### UIMask
-
-Clips child entities to the parent's `UIRect` bounds.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `enabled` | boolean | `true` | Whether clipping is active |
-| `mode` | MaskMode | `Scissor` | `Scissor` (0), `Stencil` (1) |
-
-Nested `UIMask` entities clip to the intersection of all parent masks.
-
-<Aside type="caution">
- `UIMask` only clips **child** entities — the entity with UIMask itself is not clipped.
-</Aside>
-
-## SafeArea
-
-Adapts layout to device safe areas (notches, rounded corners). Useful for mobile and WeChat MiniGame.
-
-| Property | Type | Default | Description |
-|----------|------|---------|-------------|
-| `applyTop` | boolean | `true` | Apply to top edge |
-| `applyBottom` | boolean | `true` | Apply to bottom edge |
-| `applyLeft` | boolean | `true` | Apply to left edge |
-| `applyRight` | boolean | `true` | Apply to right edge |
-
-## Example: Score Display
-
-```typescript
-import { defineTag, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';
-
-const ScoreDisplay = defineTag('ScoreDisplay');
-const GameState = defineComponent('GameState', { score: 0 });
-
-addSystem(defineSystem(
- [Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],
- (displays, stateQuery) => {
- if (stateQuery.isEmpty()) return;
- const [, state] = stateQuery.single()!;
- for (const [, text] of displays) {
- text.content = `Score: ${state.score}`;
- }
- }
-));
-```
-
-Uses [Change Detection](/microes/core-concepts/change-detection/) to only update text when the score actually changes.
-
## Next Steps
-- [Components](/microes/core-concepts/components/) — all builtin components
-- [Sprite](/microes/guides/sprite/) — sprite rendering details
-- [Bitmap Text](/microes/guides/bitmap-text/) — GPU-rendered bitmap font text
-- [Input Handling](/microes/guides/input/) — keyboard, mouse, and touch input
+- [Text & Image](/microes/guides/ui-text/) — text rendering and image display
+- [Interaction](/microes/guides/ui-interaction/) — pointer events, focus, and drag
+- [Widgets](/microes/guides/ui-widgets/) — buttons, sliders, toggles, and more
+- [Masking & SafeArea](/microes/guides/ui-masking/) — clipping and device safe areas
diff --git a/docs/astro/src/content/docs/zh/core-concepts/components.mdx b/docs/astro/src/content/docs/zh/core-concepts/components.mdx
index 73af14915..fdc116e6c 100644
--- a/docs/astro/src/content/docs/zh/core-concepts/components.mdx
+++ b/docs/astro/src/content/docs/zh/core-concepts/components.mdx
@@ -100,7 +100,7 @@ Spine 骨骼动画播放。需要 `Transform`。详见 [Spine 动画指南](/mic
### Text
-UI 文本渲染。配合 `UIRect` 和 `Sprite` 组件显示文本。详见 [UI 与文本指南](/microes/zh/guides/ui/)。
+UI 文本渲染。配合 `UIRect` 和 `Sprite` 组件显示文本。详见[文本与图片](/microes/zh/guides/ui-text/)。
| 属性 | 类型 | 说明 |
|------|------|------|
@@ -129,7 +129,7 @@ UI 布局矩形。定义 UI 元素的锚点布局。
### UIMask
-将子实体裁剪到父级 `UIRect` 边界内。需要在同一实体上同时挂载 `UIRect` 和 `Transform`。详见 [UI 与文本指南](/microes/zh/guides/ui/)。
+将子实体裁剪到父级 `UIRect` 边界内。需要在同一实体上同时挂载 `UIRect` 和 `Transform`。详见[遮罩与安全区](/microes/zh/guides/ui-masking/)。
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
diff --git a/docs/astro/src/content/docs/zh/core-concepts/resources.mdx b/docs/astro/src/content/docs/zh/core-concepts/resources.mdx
index fed799f2d..e0818a758 100644
--- a/docs/astro/src/content/docs/zh/core-concepts/resources.mdx
+++ b/docs/astro/src/content/docs/zh/core-concepts/resources.mdx
@@ -103,7 +103,7 @@ defineSystem([Res(UIEvents)], (events) => {
});
```
-详见 [UI 与文本](/microes/zh/guides/ui/)了解完整的事件类型列表。
+详见 [UI 交互](/microes/zh/guides/ui-interaction/)了解完整的事件类型列表。
## 自定义资源
diff --git a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx
index 7c5d3e0b8..dfa509b65 100644
--- a/docs/astro/src/content/docs/zh/core-concepts/systems.mdx
+++ b/docs/astro/src/content/docs/zh/core-concepts/systems.mdx
@@ -27,7 +27,7 @@ const movementSystem = defineSystem(
`defineSystem` 接受两个参数:
-1. **参数列表** — `Query`、`Res`、`ResMut`、`Commands`、`EventWriter` 或 `EventReader` 描述符的数组
+1. **参数列表** — `Query`、`Res`、`ResMut`、`Commands`、`GetWorld`、`EventWriter` 或 `EventReader` 描述符的数组
2. **函数** — 按相同顺序接收解析后的参数
## 注册系统
@@ -222,12 +222,43 @@ defineSystem([EventReader(DamageEvent)], (reader) => {
详见[事件](/microes/zh/core-concepts/events/)。
+### GetWorld
+
+直接访问 ECS World。可用 `world.get()` / `world.set()` 按实体 ID 进行 O(1) 组件访问,或配合 `findEntityByName()` 等工具函数:
+
+```typescript
+import { GetWorld, findEntityByName, ProgressBar } from 'esengine';
+
+defineSystem([GetWorld()], (world) => {
+ const entity = findEntityByName(world, 'HealthBar');
+ if (entity) {
+ const bar = world.get(entity, ProgressBar);
+ bar.value = playerHealth / maxHealth;
+ world.set(entity, ProgressBar, bar);
+ }
+});
+```
+
+#### World API
+
+| 方法 | 返回值 | 说明 |
+|------|--------|------|
+| `world.get(entity, Component)` | 组件数据 | 读取组件(O(1)) |
+| `world.set(entity, Component, data)` | void | 写入组件(O(1)) |
+| `world.has(entity, Component)` | boolean | 检查实体是否有该组件 |
+| `world.tryGet(entity, Component)` | data \| null | 安全读取,不存在返回 null |
+| `world.valid(entity)` | boolean | 检查实体是否存活 |
+
+<Aside type="tip">
+ 遍历多个实体时优先用 `Query` + `Mut()`——它会自动回写。当你需要**按实体 ID 直接访问已知实体**(如 `findEntityByName()` 之后)时用 `GetWorld()`。
+</Aside>
+
### 组合参数
```typescript
defineSystem(
- [Commands(), Res(Time), Res(Input), Query(Mut(Transform), Velocity)],
- (cmds, time, input, query) => {
+ [Commands(), Res(Time), Res(Input), GetWorld(), Query(Mut(Transform), Velocity)],
+ (cmds, time, input, world, query) => {
// 所有参数都可用
}
);
diff --git a/docs/astro/src/content/docs/zh/guides/bitmap-text.mdx b/docs/astro/src/content/docs/zh/guides/bitmap-text.mdx
index 2986547ed..93042ab57 100644
--- a/docs/astro/src/content/docs/zh/guides/bitmap-text.mdx
+++ b/docs/astro/src/content/docs/zh/guides/bitmap-text.mdx
@@ -144,6 +144,6 @@ BitmapText 遵循与 Sprite 相同的绘制排序规则:
## 下一步
- [资源加载](/microes/zh/guides/assets/) — 加载位图字体和其他资源
-- [UI 与文本](/microes/zh/guides/ui/) — Canvas 2D 文本和 UI 布局
+- [文本与图片](/microes/zh/guides/ui-text/) — Canvas 2D 文本和 UI 布局
- [渲染](/microes/zh/guides/rendering/) — 相机、变换和渲染顺序
- [组件](/microes/zh/core-concepts/components/) — 所有内置组件
diff --git a/docs/astro/src/content/docs/zh/guides/input.mdx b/docs/astro/src/content/docs/zh/guides/input.mdx
index a55dac0e2..61def83db 100644
--- a/docs/astro/src/content/docs/zh/guides/input.mdx
+++ b/docs/astro/src/content/docs/zh/guides/input.mdx
@@ -175,6 +175,6 @@ addSystem(defineSystem(
## 下一步
-- [UI 与文本](/microes/zh/guides/ui/) — UI 交互事件(点击、悬停、按压)
+- [UI 交互](/microes/zh/guides/ui-interaction/) — UI 交互事件(点击、悬停、按压)
- [物理](/microes/zh/guides/physics/) — 物理驱动的运动和碰撞
- [系统](/microes/zh/core-concepts/systems/) — 定义和调度系统
diff --git a/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx b/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx
new file mode 100644
index 000000000..61e3354b8
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx
@@ -0,0 +1,74 @@
+---
+title: UI 交互
+description: ESEngine 中 UI 元素的指针事件、焦点和拖拽
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## Interactable
+
+将 UI 实体标记为可交互(接收指针事件)。所有交互控件都需要此组件。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `enabled` | boolean | `true` | 是否启用交互 |
+| `blockRaycast` | boolean | `true` | 阻止事件传递到后面的元素 |
+
+## UIInteraction
+
+由插件自动添加到拥有 `Interactable` 的实体上,提供逐实体状态:
+
+| 属性 | 类型 | 说明 |
+|------|------|------|
+| `hovered` | boolean | 指针悬停在此实体上 |
+| `pressed` | boolean | 实体正被按下 |
+| `justPressed` | boolean | 本帧开始按下 |
+| `justReleased` | boolean | 本帧释放按下 |
+
+## UIEvents
+
+`UIEvents` 资源收集每帧的交互事件:
+
+```typescript
+import { defineSystem, addSystem, Res } from 'esengine';
+import { UIEvents } from 'esengine';
+
+addSystem(defineSystem(
+ [Res(UIEvents)],
+ (events) => {
+ for (const e of events.query('click')) {
+ console.log('点击了:', e.entity);
+ }
+ }
+));
+```
+
+**事件类型:** `click`、`press`、`release`、`hover_enter`、`hover_exit`、`focus`、`blur`、`submit`、`change`、`drag_start`、`drag_move`、`drag_end`、`scroll`
+
+事件沿实体层级向上冒泡。如果父级的 `Interactable` 设置了 `blockRaycast: true`,冒泡在此停止。
+
+## Focusable
+
+启用键盘焦点和 Tab 导航。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `tabIndex` | number | `0` | 焦点顺序(越小越早) |
+| `isFocused` | boolean | `false` | 当前焦点状态 |
+
+## Draggable
+
+启用 UI 元素的拖拽移动。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `enabled` | boolean | `true` | 启用拖拽 |
+| `dragThreshold` | number | `5` | 开始拖拽前的像素移动距离 |
+| `lockX` | boolean | `false` | 锁定水平移动 |
+| `lockY` | boolean | `false` | 锁定垂直移动 |
+
+## 下一步
+
+- [控件](/microes/zh/guides/ui-widgets/) — 按钮、滑块、开关等
+- [UI 布局](/microes/zh/guides/ui/) — 锚点、Flex 和网格布局
+- [输入处理](/microes/zh/guides/input/) — 键盘、鼠标和触摸输入
diff --git a/docs/astro/src/content/docs/zh/guides/ui-masking.mdx b/docs/astro/src/content/docs/zh/guides/ui-masking.mdx
new file mode 100644
index 000000000..319d099b3
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/ui-masking.mdx
@@ -0,0 +1,38 @@
+---
+title: 遮罩与安全区
+description: ESEngine 中的 UI 裁剪和设备安全区域适配
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## UIMask
+
+将子实体裁剪到父级 `UIRect` 边界内。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `enabled` | boolean | `true` | 是否启用裁剪 |
+| `mode` | MaskMode | `Scissor` | `Scissor` (0)、`Stencil` (1) |
+
+嵌套 `UIMask` 实体会裁剪到所有父级遮罩的交集区域。
+
+<Aside type="caution">
+ `UIMask` 只裁剪**子**实体——拥有 UIMask 的实体本身不会被裁剪。
+</Aside>
+
+## SafeArea
+
+适配设备安全区域(刘海、圆角)。适用于移动端和微信小游戏。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `applyTop` | boolean | `true` | 应用到顶部 |
+| `applyBottom` | boolean | `true` | 应用到底部 |
+| `applyLeft` | boolean | `true` | 应用到左侧 |
+| `applyRight` | boolean | `true` | 应用到右侧 |
+
+## 下一步
+
+- [UI 布局](/microes/zh/guides/ui/) — 锚点、Flex 和网格布局
+- [控件](/microes/zh/guides/ui-widgets/) — 按钮、滑块、开关等
+- [微信小游戏](/microes/zh/guides/wechat/) — 平台特定注意事项
diff --git a/docs/astro/src/content/docs/zh/guides/ui-text.mdx b/docs/astro/src/content/docs/zh/guides/ui-text.mdx
new file mode 100644
index 000000000..9d4c1e9a7
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/ui-text.mdx
@@ -0,0 +1,88 @@
+---
+title: 文本与图片
+description: ESEngine 中的 UI 文本渲染和图片显示
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+## Text
+
+通过 `TextPlugin` 自动将样式化文本渲染为 `Sprite` 纹理。
+
+**设置:** 在实体上添加 `Transform`、`Sprite`、`UIRect` 和 `Text`。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `content` | string | `''` | 文本内容 |
+| `fontFamily` | string | `'Arial'` | 字体名称 |
+| `fontSize` | number | `24` | 字号(像素) |
+| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 RGBA |
+| `align` | TextAlign | `Left` | `Left` (0)、`Center` (1)、`Right` (2) |
+| `verticalAlign` | TextVerticalAlign | `Top` | `Top` (0)、`Middle` (1)、`Bottom` (2) |
+| `wordWrap` | boolean | `true` | 启用自动换行 |
+| `overflow` | TextOverflow | `Visible` | `Visible` (0)、`Clip` (1)、`Ellipsis` (2) |
+| `lineHeight` | number | `1.2` | 行高倍率 |
+
+<Aside type="note">
+ 无需手动配置 Sprite。`TextPlugin` 会自动从 Text 内容创建和更新纹理。
+</Aside>
+
+### 运行时修改文本
+
+```typescript
+import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';
+
+addSystem(defineSystem(
+ [Query(Mut(Text))],
+ (query) => {
+ for (const [entity, text] of query) {
+ text.content = '已更新!';
+ text.fontSize = 32;
+ }
+ }
+));
+```
+
+## Image
+
+显示图片,支持切片、平铺和填充模式。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `texture` | number | — | 纹理资产句柄 |
+| `color` | Color | `{r:1, g:1, b:1, a:1}` | 颜色着色 |
+| `imageType` | ImageType | `Simple` | `Simple` (0)、`Sliced` (1)、`Tiled` (2)、`Filled` (3) |
+| `fillMethod` | FillMethod | `Horizontal` | `Horizontal` (0)、`Vertical` (1) |
+| `fillOrigin` | FillOrigin | `Left` | `Left` (0)、`Right` (1)、`Bottom` (2)、`Top` (3) |
+| `fillAmount` | number | `1` | 填充进度 0–1 |
+| `preserveAspect` | boolean | `false` | 保持宽高比 |
+| `enabled` | boolean | `true` | 可见性开关 |
+
+## 示例:分数显示
+
+```typescript
+import { defineTag, defineComponent, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';
+
+const ScoreDisplay = defineTag('ScoreDisplay');
+const GameState = defineComponent('GameState', { score: 0 });
+
+addSystem(defineSystem(
+ [Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],
+ (displays, stateQuery) => {
+ if (stateQuery.isEmpty()) return;
+ const [, state] = stateQuery.single()!;
+ for (const [, text] of displays) {
+ text.content = `分数:${state.score}`;
+ }
+ }
+));
+```
+
+使用[变更检测](/microes/zh/core-concepts/change-detection/),仅在分数实际变化时更新文本。
+
+## 下一步
+
+- [UI 布局](/microes/zh/guides/ui/) — 锚点、Flex 和网格布局
+- [交互](/microes/zh/guides/ui-interaction/) — 指针事件、焦点和拖拽
+- [位图文本](/microes/zh/guides/bitmap-text/) — GPU 渲染的位图字体文本
+- [精灵](/microes/zh/guides/sprite/) — 精灵渲染详情
diff --git a/docs/astro/src/content/docs/zh/guides/ui-widgets.mdx b/docs/astro/src/content/docs/zh/guides/ui-widgets.mdx
new file mode 100644
index 000000000..db4dd82a2
--- /dev/null
+++ b/docs/astro/src/content/docs/zh/guides/ui-widgets.mdx
@@ -0,0 +1,305 @@
+---
+title: UI 控件
+description: ESEngine 中的按钮、滑块、开关、下拉框及其他 UI 控件
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+所有控件都需要在同一实体上添加 `Interactable` 和 `UIRect`。交互事件处理详见 [UI 交互](/microes/zh/guides/ui-interaction/)。
+
+## 获取特定控件
+
+当你在场景中放置了多个控件后,使用 **Query** 来查找特定的那一个。
+
+### 按标签查找(推荐)
+
+定义一个 Tag 并在编辑器中挂到实体上,然后用 `query.single()` 直接获取唯一匹配的实体:
+
+```typescript
+import { defineTag, defineSystem, addSystem, Query, Mut, ProgressBar } from 'esengine';
+
+const HealthBar = defineTag('HealthBar');
+
+addSystem(defineSystem(
+ [Query(Mut(ProgressBar), HealthBar)],
+ (query) => {
+ const [, bar] = query.single()!;
+ bar.value = playerHealth / maxHealth;
+ }
+));
+```
+
+<Aside type="note">
+ `Mut()` 启用自动回写——直接修改 `bar.value` 就会自动持久化,无需手动写回。
+</Aside>
+
+### 按名称查找
+
+编辑器中每个实体都有 `Name` 组件。将它和控件组件一起查询:
+
+```typescript
+addSystem(defineSystem(
+ [Query(Mut(ProgressBar), Name)],
+ (query) => {
+ for (const [, bar, name] of query) {
+ if (name.value === 'HealthBar') bar.value = playerHealth / maxHealth;
+ if (name.value === 'ManaBar') bar.value = playerMana / maxMana;
+ if (name.value === 'ExpBar') bar.value = playerExp / expToNextLevel;
+ }
+ }
+));
+```
+
+<Aside type="tip">
+ 正式项目用 Tag——按类型匹配(无字符串比较),拼写错误在编译时就能发现。快速原型用 `Name`。
+</Aside>
+
+### 用 `findEntityByName` + 直接访问
+
+使用 `GetWorld()` 获取 World 实例。`findEntityByName()` 按编辑器中的名称查找实体,然后 `world.get()` / `world.set()` 以 O(1) 读写组件:
+
+```typescript
+import { GetWorld, findEntityByName, ProgressBar } from 'esengine';
+
+addSystem(defineSystem(
+ [GetWorld()],
+ (world) => {
+ const entity = findEntityByName(world, 'HealthBar');
+ if (entity) {
+ const bar = world.get(entity, ProgressBar);
+ bar.value = playerHealth / maxHealth;
+ world.set(entity, ProgressBar, bar);
+ }
+ }
+));
+```
+
+---
+
+## 处理特定控件的事件
+
+### Tag + `hasEvent`
+
+先用 `query.single()` 获取实体 ID,然后用 `UIEvents.hasEvent()` 直接检查——无需循环:
+
+```typescript
+import { defineTag, defineSystem, addSystem, Res, Query } from 'esengine';
+import { UIEvents, Button } from 'esengine';
+
+const StartButton = defineTag('StartButton');
+
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Button, StartButton)],
+ (events, query) => {
+ const match = query.single();
+ if (match && events.hasEvent(match[0], 'click')) {
+ startGame();
+ }
+ }
+));
+```
+
+### 使用 UIInteraction(无需 UIEvents)
+
+对于简单的按下/释放检测,直接读取 `UIInteraction` 组件:
+
+```typescript
+import { UIInteraction } from 'esengine';
+
+const StartButton = defineTag('StartButton');
+
+addSystem(defineSystem(
+ [Query(UIInteraction, StartButton)],
+ (query) => {
+ const match = query.single();
+ if (match) {
+ const [, interaction] = match;
+ if (interaction.justPressed) startGame();
+ }
+ }
+));
+```
+
+### 按名称匹配事件
+
+当需要在一个系统中处理多个控件的事件时:
+
+```typescript
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Button, Name)],
+ (events, query) => {
+ for (const e of events.query('click')) {
+ for (const [entity, , name] of query) {
+ if (entity === e.entity) {
+ console.log('点击了:', name.value);
+ }
+ }
+ }
+ }
+));
+```
+
+---
+
+## Button
+
+在 `Interactable` 之上的状态机,支持可选颜色过渡。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `state` | ButtonState | `Normal` | `Normal` (0)、`Hovered` (1)、`Pressed` (2)、`Disabled` (3) |
+| `transition` | ColorTransition \| null | `null` | 各状态颜色 |
+
+```typescript
+cmds.entity(button).insert(Button, {
+ state: 0,
+ transition: {
+ normalColor: { r: 1, g: 1, b: 1, a: 1 },
+ hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },
+ pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },
+ disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },
+ },
+});
+```
+
+## Toggle
+
+复选框,可选分组实现互斥。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `isOn` | boolean | `true` | 开关状态 |
+| `graphicEntity` | Entity | `0` | 显示/隐藏的子实体(勾选标记) |
+| `group` | Entity | `0` | ToggleGroup 实体,实现单选按钮行为 |
+| `transition` | ColorTransition \| null | `null` | 颜色过渡 |
+
+**ToggleGroup** — 挂载到父实体使子级 Toggle 互斥:
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `allowSwitchOff` | boolean | `false` | 允许所有 Toggle 关闭 |
+
+监听开关变化:
+
+```typescript
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Toggle, Name)],
+ (events, query) => {
+ for (const e of events.query('change')) {
+ for (const [entity, toggle, name] of query) {
+ if (entity === e.entity) {
+ console.log(name.value, '现在是:', toggle.isOn);
+ }
+ }
+ }
+ }
+));
+```
+
+## Slider
+
+交互式数值滑块,带填充和可选可拖拽手柄。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `value` | number | `0` | 当前值 |
+| `minValue` | number | `0` | 最小值 |
+| `maxValue` | number | `1` | 最大值 |
+| `direction` | FillDirection | `LeftToRight` | `LeftToRight` (0)、`RightToLeft` (1)、`BottomToTop` (2)、`TopToBottom` (3) |
+| `fillEntity` | Entity | `0` | 填充可视化的子实体 |
+| `handleEntity` | Entity | `0` | 可拖拽手柄的子实体 |
+| `wholeNumbers` | boolean | `false` | 吸附到整数 |
+
+监听滑块变化:
+
+```typescript
+addSystem(defineSystem(
+ [Res(UIEvents), Query(Slider, Name)],
+ (events, query) => {
+ for (const e of events.query('change')) {
+ for (const [entity, slider, name] of query) {
+ if (entity === e.entity) {
+ if (name.value === 'VolumeSlider') setVolume(slider.value);
+ if (name.value === 'BrightnessSlider') setBrightness(slider.value);
+ }
+ }
+ }
+ }
+));
+```
+
+## ProgressBar
+
+非交互式进度条显示。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `value` | number | `0` | 进度 0–1 |
+| `fillEntity` | Entity | `0` | 填充的子实体 |
+| `direction` | FillDirection | `LeftToRight` | 填充方向 |
+
+## Dropdown
+
+下拉列表选择器。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `options` | string[] | `[]` | 选项标签 |
+| `selectedIndex` | number | `-1` | 选中项索引 |
+| `isOpen` | boolean | `false` | 列表可见性 |
+| `listEntity` | Entity | `0` | 下拉列表的子实体 |
+| `labelEntity` | Entity | `0` | 显示选中标签的子实体 |
+
+## ScrollView
+
+带惯性和弹性回弹的滚动容器。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `contentEntity` | Entity | `0` | 持有可滚动内容的子实体 |
+| `horizontalEnabled` | boolean | `false` | 启用水平滚动 |
+| `verticalEnabled` | boolean | `true` | 启用垂直滚动 |
+| `scrollX` | number | `0` | 当前水平偏移 |
+| `scrollY` | number | `0` | 当前垂直偏移 |
+| `inertia` | boolean | `true` | 启用惯性滚动 |
+| `decelerationRate` | number | `0.135` | 惯性摩擦力 |
+| `elastic` | boolean | `true` | 边缘回弹 |
+| `wheelSensitivity` | number | `0.1` | 鼠标滚轮灵敏度 |
+
+## ListView
+
+大列表虚拟滚动——仅渲染可见项目。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `itemHeight` | number | `40` | 固定项目高度 |
+| `itemCount` | number | `0` | 总项目数 |
+| `scrollY` | number | `0` | 滚动位置 |
+| `overscan` | number | `2` | 视口上下额外渲染的项目数 |
+
+## TextInput
+
+可编辑文本输入框,支持光标、选择和占位符。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `value` | string | `''` | 当前文本 |
+| `placeholder` | string | `''` | 为空时的提示 |
+| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | 占位符颜色 |
+| `fontFamily` | string | `'Arial'` | 字体 |
+| `fontSize` | number | `16` | 字号 |
+| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 |
+| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | 背景颜色 |
+| `padding` | number | `6` | 内边距 |
+| `maxLength` | number | `0` | 最大字符数(0 = 无限) |
+| `multiline` | boolean | `false` | 允许换行 |
+| `password` | boolean | `false` | 密码遮罩 |
+| `readOnly` | boolean | `false` | 禁止编辑 |
+
+**事件:** `change`(值变化)、`submit`(单行模式下按 Enter)
+
+## 下一步
+
+- [UI 交互](/microes/zh/guides/ui-interaction/) — 指针事件、焦点和拖拽
+- [遮罩与安全区](/microes/zh/guides/ui-masking/) — 裁剪和设备安全区域
+- [UI 布局](/microes/zh/guides/ui/) — 锚点、Flex 和网格布局
diff --git a/docs/astro/src/content/docs/zh/guides/ui.mdx b/docs/astro/src/content/docs/zh/guides/ui.mdx
index 59573ba3b..b9355029c 100644
--- a/docs/astro/src/content/docs/zh/guides/ui.mdx
+++ b/docs/astro/src/content/docs/zh/guides/ui.mdx
@@ -1,6 +1,6 @@
---
-title: UI 与文本
-description: ESEngine 中的 UI 组件、布局、交互和文本渲染
+title: UI 布局
+description: ESEngine 中的 UI 布局系统——锚点、Flex 和网格布局
---
import { Aside } from '@astrojs/starlight/components';
@@ -35,9 +35,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {
}));
```
-## 布局
-
-### UIRect
+## UIRect
每个 UI 元素都需要 `UIRect` 来参与布局。它使用锚点系统定义相对于父级的位置和尺寸。
@@ -52,7 +50,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {
当 `anchorMin` 等于 `anchorMax` 时,元素在锚点处具有固定 `size`。当两者不同时,元素在锚点之间拉伸,尺寸自动计算。
-### FlexContainer
+## FlexContainer
类似 CSS Flexbox 的自动子元素排列布局。
@@ -65,7 +63,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {
| `gap` | Vec2 | `{0, 0}` | 子元素间距 |
| `padding` | Vec4 | `{0, 0, 0, 0}` | 上、右、下、左内边距 |
-### FlexItem
+## FlexItem
`FlexContainer` 内子实体的 Flex 属性。
@@ -76,7 +74,7 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {
| `flexBasis` | number | `-1` | 扩展/收缩前的基础尺寸(-1 = 自动) |
| `order` | number | `0` | 显示顺序覆盖 |
-### LayoutGroup
+## LayoutGroup
带方向、间距和对齐的网格式布局。
@@ -88,330 +86,9 @@ addStartupSystem(defineSystem([Commands()], (cmds) => {
| `childAlignment` | ChildAlignment | `Start` | `Start`、`Center`、`End` |
| `reverseOrder` | boolean | `false` | 反向排列 |
-## 文本
-
-### Text 组件
-
-通过 `TextPlugin` 自动将样式化文本渲染为 `Sprite` 纹理。
-
-**设置:** 在实体上添加 `Transform`、`Sprite`、`UIRect` 和 `Text`。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `content` | string | `''` | 文本内容 |
-| `fontFamily` | string | `'Arial'` | 字体名称 |
-| `fontSize` | number | `24` | 字号(像素) |
-| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 RGBA |
-| `align` | TextAlign | `Left` | `Left` (0)、`Center` (1)、`Right` (2) |
-| `verticalAlign` | TextVerticalAlign | `Top` | `Top` (0)、`Middle` (1)、`Bottom` (2) |
-| `wordWrap` | boolean | `true` | 启用自动换行 |
-| `overflow` | TextOverflow | `Visible` | `Visible` (0)、`Clip` (1)、`Ellipsis` (2) |
-| `lineHeight` | number | `1.2` | 行高倍率 |
-
-<Aside type="note">
- 无需手动配置 Sprite。`TextPlugin` 会自动从 Text 内容创建和更新纹理。
-</Aside>
-
-### 运行时修改文本
-
-```typescript
-import { defineSystem, addSystem, Query, Mut, Text } from 'esengine';
-
-addSystem(defineSystem(
- [Query(Mut(Text))],
- (query) => {
- for (const [entity, text] of query) {
- text.content = '已更新!';
- text.fontSize = 32;
- }
- }
-));
-```
-
-### Image
-
-显示图片,支持切片、平铺和填充模式。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `texture` | number | — | 纹理资产句柄 |
-| `color` | Color | `{r:1, g:1, b:1, a:1}` | 颜色着色 |
-| `imageType` | ImageType | `Simple` | `Simple` (0)、`Sliced` (1)、`Tiled` (2)、`Filled` (3) |
-| `fillMethod` | FillMethod | `Horizontal` | `Horizontal` (0)、`Vertical` (1) |
-| `fillOrigin` | FillOrigin | `Left` | `Left` (0)、`Right` (1)、`Bottom` (2)、`Top` (3) |
-| `fillAmount` | number | `1` | 填充进度 0–1 |
-| `preserveAspect` | boolean | `false` | 保持宽高比 |
-| `enabled` | boolean | `true` | 可见性开关 |
-
-## 交互
-
-### Interactable
-
-将 UI 实体标记为可交互(接收指针事件)。所有交互控件都需要此组件。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `enabled` | boolean | `true` | 是否启用交互 |
-| `blockRaycast` | boolean | `true` | 阻止事件传递到后面的元素 |
-
-### UIInteraction
-
-由插件自动添加到拥有 `Interactable` 的实体上,提供逐实体状态:
-
-| 属性 | 类型 | 说明 |
-|------|------|------|
-| `hovered` | boolean | 指针悬停在此实体上 |
-| `pressed` | boolean | 实体正被按下 |
-| `justPressed` | boolean | 本帧开始按下 |
-| `justReleased` | boolean | 本帧释放按下 |
-
-### UIEvents
-
-`UIEvents` 资源收集每帧的交互事件:
-
-```typescript
-import { defineSystem, addSystem, Res } from 'esengine';
-import { UIEvents } from 'esengine';
-
-addSystem(defineSystem(
- [Res(UIEvents)],
- (events) => {
- for (const e of events.query('click')) {
- console.log('点击了:', e.entity);
- }
- }
-));
-```
-
-**事件类型:** `click`、`press`、`release`、`hover_enter`、`hover_exit`、`focus`、`blur`、`submit`、`change`、`drag_start`、`drag_move`、`drag_end`、`scroll`
-
-事件沿实体层级向上冒泡。如果父级的 `Interactable` 设置了 `blockRaycast: true`,冒泡在此停止。
-
-### Focusable
-
-启用键盘焦点和 Tab 导航。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `tabIndex` | number | `0` | 焦点顺序(越小越早) |
-| `isFocused` | boolean | `false` | 当前焦点状态 |
-
-## 控件
-
-### Button
-
-在 `Interactable` 之上的状态机,支持可选颜色过渡。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `state` | ButtonState | `Normal` | `Normal` (0)、`Hovered` (1)、`Pressed` (2)、`Disabled` (3) |
-| `transition` | ColorTransition \| null | `null` | 各状态颜色 |
-
-```typescript
-cmds.entity(button).insert(Button, {
- state: 0,
- transition: {
- normalColor: { r: 1, g: 1, b: 1, a: 1 },
- hoveredColor: { r: 0.9, g: 0.9, b: 0.9, a: 1 },
- pressedColor: { r: 0.7, g: 0.7, b: 0.7, a: 1 },
- disabledColor: { r: 0.5, g: 0.5, b: 0.5, a: 0.5 },
- },
-});
-```
-
-### Toggle
-
-复选框,可选分组实现互斥。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `isOn` | boolean | `true` | 开关状态 |
-| `graphicEntity` | Entity | `0` | 显示/隐藏的子实体(勾选标记) |
-| `group` | Entity | `0` | ToggleGroup 实体,实现单选按钮行为 |
-| `transition` | ColorTransition \| null | `null` | 颜色过渡 |
-
-**ToggleGroup** — 挂载到父实体使子级 Toggle 互斥:
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `allowSwitchOff` | boolean | `false` | 允许所有 Toggle 关闭 |
-
-### Slider
-
-交互式数值滑块,带填充和可选可拖拽手柄。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `value` | number | `0` | 当前值 |
-| `minValue` | number | `0` | 最小值 |
-| `maxValue` | number | `1` | 最大值 |
-| `direction` | FillDirection | `LeftToRight` | `LeftToRight` (0)、`RightToLeft` (1)、`BottomToTop` (2)、`TopToBottom` (3) |
-| `fillEntity` | Entity | `0` | 填充可视化的子实体 |
-| `handleEntity` | Entity | `0` | 可拖拽手柄的子实体 |
-| `wholeNumbers` | boolean | `false` | 吸附到整数 |
-
-监听值变化:
-
-```typescript
-addSystem(defineSystem(
- [Res(UIEvents), Query(Slider)],
- (events, query) => {
- for (const e of events.query('change')) {
- for (const [entity, slider] of query) {
- if (entity === e.entity) {
- console.log('滑块值:', slider.value);
- }
- }
- }
- }
-));
-```
-
-### ProgressBar
-
-非交互式进度条显示。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `value` | number | `0` | 进度 0–1 |
-| `fillEntity` | Entity | `0` | 填充的子实体 |
-| `direction` | FillDirection | `LeftToRight` | 填充方向 |
-
-```typescript
-addSystem(defineSystem(
- [Res(Time), Query(Mut(ProgressBar))],
- (time, query) => {
- for (const [entity, bar] of query) {
- bar.value = Math.min(1, bar.value + time.delta * 0.1);
- }
- }
-));
-```
-
-### Dropdown
-
-下拉列表选择器。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `options` | string[] | `[]` | 选项标签 |
-| `selectedIndex` | number | `-1` | 选中项索引 |
-| `isOpen` | boolean | `false` | 列表可见性 |
-| `listEntity` | Entity | `0` | 下拉列表的子实体 |
-| `labelEntity` | Entity | `0` | 显示选中标签的子实体 |
-
-### ScrollView
-
-带惯性和弹性回弹的滚动容器。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `contentEntity` | Entity | `0` | 持有可滚动内容的子实体 |
-| `horizontalEnabled` | boolean | `false` | 启用水平滚动 |
-| `verticalEnabled` | boolean | `true` | 启用垂直滚动 |
-| `scrollX` | number | `0` | 当前水平偏移 |
-| `scrollY` | number | `0` | 当前垂直偏移 |
-| `inertia` | boolean | `true` | 启用惯性滚动 |
-| `decelerationRate` | number | `0.135` | 惯性摩擦力 |
-| `elastic` | boolean | `true` | 边缘回弹 |
-| `wheelSensitivity` | number | `0.1` | 鼠标滚轮灵敏度 |
-
-### ListView
-
-大列表虚拟滚动——仅渲染可见项目。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `itemHeight` | number | `40` | 固定项目高度 |
-| `itemCount` | number | `0` | 总项目数 |
-| `scrollY` | number | `0` | 滚动位置 |
-| `overscan` | number | `2` | 视口上下额外渲染的项目数 |
-
-### TextInput
-
-可编辑文本输入框,支持光标、选择和占位符。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `value` | string | `''` | 当前文本 |
-| `placeholder` | string | `''` | 为空时的提示 |
-| `placeholderColor` | Color | `{r:0.6, g:0.6, b:0.6, a:1}` | 占位符颜色 |
-| `fontFamily` | string | `'Arial'` | 字体 |
-| `fontSize` | number | `16` | 字号 |
-| `color` | Color | `{r:1, g:1, b:1, a:1}` | 文本颜色 |
-| `backgroundColor` | Color | `{r:0.15, g:0.15, b:0.15, a:1}` | 背景颜色 |
-| `padding` | number | `6` | 内边距 |
-| `maxLength` | number | `0` | 最大字符数(0 = 无限) |
-| `multiline` | boolean | `false` | 允许换行 |
-| `password` | boolean | `false` | 密码遮罩 |
-| `readOnly` | boolean | `false` | 禁止编辑 |
-
-**事件:** `change`(值变化)、`submit`(单行模式下按 Enter)
-
-### Draggable
-
-启用 UI 元素的拖拽移动。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `enabled` | boolean | `true` | 启用拖拽 |
-| `dragThreshold` | number | `5` | 开始拖拽前的像素移动距离 |
-| `lockX` | boolean | `false` | 锁定水平移动 |
-| `lockY` | boolean | `false` | 锁定垂直移动 |
-
-## 遮罩
-
-### UIMask
-
-将子实体裁剪到父级 `UIRect` 边界内。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `enabled` | boolean | `true` | 是否启用裁剪 |
-| `mode` | MaskMode | `Scissor` | `Scissor` (0)、`Stencil` (1) |
-
-嵌套 `UIMask` 实体会裁剪到所有父级遮罩的交集区域。
-
-<Aside type="caution">
- `UIMask` 只裁剪**子**实体——拥有 UIMask 的实体本身不会被裁剪。
-</Aside>
-
-## SafeArea
-
-适配设备安全区域(刘海、圆角)。适用于移动端和微信小游戏。
-
-| 属性 | 类型 | 默认值 | 说明 |
-|------|------|--------|------|
-| `applyTop` | boolean | `true` | 应用到顶部 |
-| `applyBottom` | boolean | `true` | 应用到底部 |
-| `applyLeft` | boolean | `true` | 应用到左侧 |
-| `applyRight` | boolean | `true` | 应用到右侧 |
-
-## 示例:分数显示
-
-```typescript
-import { defineTag, defineComponent, defineSystem, addSystem, Query, Mut, Changed, Text } from 'esengine';
-
-const ScoreDisplay = defineTag('ScoreDisplay');
-const GameState = defineComponent('GameState', { score: 0 });
-
-addSystem(defineSystem(
- [Query(Mut(Text), ScoreDisplay), Query(Changed(GameState))],
- (displays, stateQuery) => {
- if (stateQuery.isEmpty()) return;
- const [, state] = stateQuery.single()!;
- for (const [, text] of displays) {
- text.content = `分数:${state.score}`;
- }
- }
-));
-```
-
-使用[变更检测](/microes/zh/core-concepts/change-detection/),仅在分数实际变化时更新文本。
-
## 下一步
-- [组件](/microes/zh/core-concepts/components/) — 所有内置组件
-- [精灵](/microes/zh/guides/sprite/) — 精灵渲染详情
-- [位图文本](/microes/zh/guides/bitmap-text/) — GPU 渲染的位图字体文本
-- [输入处理](/microes/zh/guides/input/) — 键盘、鼠标和触摸输入
+- [文本与图片](/microes/zh/guides/ui-text/) — 文本渲染和图片显示
+- [交互](/microes/zh/guides/ui-interaction/) — 指针事件、焦点和拖拽
+- [控件](/microes/zh/guides/ui-widgets/) — 按钮、滑块、开关等
+- [遮罩与安全区](/microes/zh/guides/ui-masking/) — 裁剪和设备安全区域
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 1e29bda48..e7461058e 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -191,7 +191,9 @@ export {
addSystem,
addStartupSystem,
addSystemToSchedule,
+ GetWorld,
SystemRunner,
+ type GetWorldDescriptor,
type SystemDef,
type SystemParam,
type SystemOptions,
diff --git a/sdk/src/system.ts b/sdk/src/system.ts
index 0c6676fcd..15a41dbdf 100644
--- a/sdk/src/system.ts
+++ b/sdk/src/system.ts
@@ -30,6 +30,18 @@ export enum Schedule {
FixedPostUpdate = 12,
}
+// =============================================================================
+// World Access Descriptor
+// =============================================================================
+
+export interface GetWorldDescriptor {
+ readonly _type: 'get_world';
+}
+
+export function GetWorld(): GetWorldDescriptor {
+ return { _type: 'get_world' };
+}
+
// =============================================================================
// System Parameter Types
// =============================================================================
@@ -43,7 +55,8 @@ export type SystemParam =
| CommandsDescriptor
| EventWriterDescriptor<unknown>
| EventReaderDescriptor<unknown>
- | RemovedQueryDescriptor<AnyComponentDef>;
+ | RemovedQueryDescriptor<AnyComponentDef>
+ | GetWorldDescriptor;
// =============================================================================
// Parameter Type Inference
@@ -57,6 +70,7 @@ export type InferParam<P> =
P extends EventWriterDescriptor<infer T> ? EventWriterInstance<T> :
P extends EventReaderDescriptor<infer T> ? EventReaderInstance<T> :
P extends RemovedQueryDescriptor<infer _T> ? RemovedQueryInstance<_T> :
+ P extends GetWorldDescriptor ? World :
never;
export type InferParams<P extends readonly SystemParam[]> = {
@@ -198,6 +212,9 @@ export class SystemRunner {
return new RemovedQueryInstance(this.world_, desc._component, this.currentLastRunTick_);
}
+ case 'get_world':
+ return this.world_;
+
default:
throw new Error('Unknown system parameter type');
}