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.

chore: sync SDK build output

esengineb227bc4960c0
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index a919bb913..2d3f290e0 100644
--- a/desktop/public/sdk/cjs/esengine.wechat.js
+++ b/desktop/public/sdk/cjs/esengine.wechat.js
@@ -1,2 +1,2 @@
-"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.onError(e=>{console.error(`[WeChatAudio] Playback error for "${s}":`,e.errMsg)}),n.src=s,n.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function m(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function b(e){return _.get(w(e))}function v(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let T=null;function C(){return T||(T=wx.getFileSystemManager()),T}function E(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function A(e){const t=C();try{return t.accessSync(e),!0}catch{return!1}}function R(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function I(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch{}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch{}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const s of t)s.startsWith(e)&&wx.removeStorageSync(s)}catch{}}},L=1920,D=1080,U={x:100,y:100},W=1/60,z={x:0,y:-9.81},$=1/60,O={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};const H={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function V(e,t){if(void 0!==t.maxDeltaTime&&(O.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(O.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(O.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(O.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(O.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");O.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(O.canvasScaleMode=H[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(O.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(O.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(O.assetFailureCooldown=t.assetFailureCooldown)}const N=4294967295,j=4294967295;function X(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(X);const t={};for(const s in e)t[s]=X(e[s]);return t}let Y=0;function G(e,t){const s=++Y,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?{...X(t),...e}:X(t):e?{...t,...e}:{...t}}}function q(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ee.get(e)??q().get(e);if(s)return s;const n=G(e,t);return q().set(e,n),ee.set(e,n),Q(e,t,!1),n}function J(e){return q().get(e)}function Q(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Z(e){return!0===e._builtin}const ee=new Map;function te(e,t){ee.set(e,t)}function se(e){return ee.get(e)??J(e)}function ne(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ee.set(e,s),s}const ie={Perspective:0,Orthographic:1},oe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},re={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ae=ne("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}}),le=ae,ce=ae,ue=ne("Sprite",{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:U.x,y:U.y},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),de=ne("Camera",{projectionType:ie.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:oe.ColorAndDepth}),he=ne("Canvas",{designResolution:{x:L,y:D},pixelsPerUnit:100,scaleMode:re.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),pe=ne("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),fe=ne("Parent",{entity:0}),me=ne("Children",{entities:[]}),ge=ne("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:j,enabled:!0}),ye=ne("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),_e={Point:0,Circle:1,Rectangle:2,Cone:3},xe={World:0,Local:1},we={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},be=ne("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:_e.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:we.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:we.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:N,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:xe.World,enabled:!0}),ve=K("Name",{value:""}),Se=K("SceneOwner",{scene:"",persistent:!1}),Pe=K("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Me=ne("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Te=ne("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ce=ne("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ee=ne("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ae={Static:0,Kinematic:1,Dynamic:2};let Re=0;function Ie(e,t){const s=++Re;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Fe(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Be{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 Le{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 Be(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const De=Ie({delta:0,elapsed:0,frameCount:0},"Time"),Ue="esengine:",We={getString(e,s){const n=t().getStorageItem(Ue+e);return null!==n?n:s},setString(e,s){t().setStorageItem(Ue+e,s)},getNumber(e,s){const n=t().getStorageItem(Ue+e);if(null===n)return s;const i=Number(n);return Number.isNaN(i)?s:i},setNumber(e,s){t().setStorageItem(Ue+e,String(s))},getBoolean(e,s){const n=t().getStorageItem(Ue+e);return null===n?s:"true"===n},setBoolean(e,s){t().setStorageItem(Ue+e,String(s))},getJSON(e,s){const n=t().getStorageItem(Ue+e);if(null===n)return s;try{return JSON.parse(n)}catch{return s}},setJSON(e,s){t().setStorageItem(Ue+e,JSON.stringify(s))},remove(e){t().removeStorageItem(Ue+e)},has:e=>null!==t().getStorageItem(Ue+e),clear(){t().clearStorage(Ue)}};function ze(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=$e(t[e]),o=$e(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Oe(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 He=null;function Ve(e){He=e}function Ne(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),He&&He(e,t)}function je(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 Xe=1;const Ye=new WeakMap;function Ge(e){let t=Ye.get(e);return void 0===t&&(t=Xe++,Ye.set(e,t)),t}const qe=[];function Ke(e,t=[],s=[]){qe.length=0;for(const t of e)qe.push(Ge(t));qe.sort((e,t)=>e-t);let n=qe.join(",");if(t.length>0){qe.length=0;for(const e of t)qe.push(Ge(e));qe.sort((e,t)=>e-t),n+="|+"+qe.join(",")}if(s.length>0){qe.length=0;for(const e of s)qe.push(Ge(e));qe.sort((e,t)=>e-t),n+="|-"+qe.join(",")}return n}class Je{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ne(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ne(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Ne(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ne(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Z(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Z(t)){if(this.cppRegistry_)try{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,je(o))}catch(s){Ne(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 Z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Z(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ne(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.");Z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=ze(t._name,n,i);if(e.length>0)throw new Error(Oe(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,je(o))}catch(s){Ne(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ne(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 Ne(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ne(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const i=ze(t._name,t._default,e);if(i.length>0)throw new Error(Oe(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of ee)if(Z(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=q();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Ke(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!Z(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Qe(e)||Ze(e)||et(e)?e._component:e}function st(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Qe(e)&&n.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>st(e,[...t,...n],s),without:(...n)=>st(e,t,[...s,...n])}}function nt(...e){return st(e)}class it{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(tt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Ke(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class ot{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 rt{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=Z(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 at{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new rt(this,null);return this.spawned_.push(e),e}entity(e){return new rt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class lt{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 ct{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new lt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new lt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class ut{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 pt(){return{_type:"get_world"}}exports.Schedule=void 0,(ht=exports.Schedule||(exports.Schedule={}))[ht.Startup=0]="Startup",ht[ht.First=1]="First",ht[ht.PreUpdate=2]="PreUpdate",ht[ht.Update=3]="Update",ht[ht.PostUpdate=4]="PostUpdate",ht[ht.Last=5]="Last",ht[ht.FixedPreUpdate=10]="FixedPreUpdate",ht[ht.FixedUpdate=11]="FixedUpdate",ht[ht.FixedPostUpdate=12]="FixedPostUpdate";let ft=0;function mt(e,t,s){const n=++ft;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function gt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class yt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof at&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new at(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 ut(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(s)}case"removed":{const t=e;return new ot(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class _t{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=Ie(new _t,"Input");class wt{constructor(e){this.target_=e??null}build(e){const s=new _t;e.insertResource(xt,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,mt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const bt=new wt,vt=Ie({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 St;function Pt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(St=exports.BlendMode||(exports.BlendMode={}))[St.Normal=0]="Normal",St[St.Additive=1]="Additive",St[St.Multiply=2]="Multiply",St[St.Screen=3]="Screen",St[St.PremultipliedAlpha=4]="PremultipliedAlpha";let Mt=null,Tt=null,Ct=1;const Et=new Map;function At(e){Mt=e,Tt=e.getResourceManager(),zt()}function Rt(){0!==Bt&&Mt&&(Mt._free(Bt),Bt=0),Et.clear(),Ct=1,kt=!1,Dt.clear(),Ut=null,Tt=null,Mt=null}function It(){if(!Tt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Tt}const Ft={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Ct++,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 Et.set(t,s),t},get:e=>Et.get(e),setUniform(e,t,s){const n=Et.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Mt?.invalidateMaterialCache(e))},getUniform(e,t){const s=Et.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Et.get(e);s&&(s.blendMode=t,Mt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Et.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Et.get(e);s&&(s.depthTest=t,Mt?.invalidateMaterialCache(e))},getShader(e){const t=Et.get(e);return t?.shader??0},release(e){Et.delete(e),Mt?.invalidateMaterialCache(e)},isValid:e=>Et.has(e),releaseAll(){Et.clear(),Mt?.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=Et.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ct++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Et.set(s,n),s},toAssetData(e,t){const s=Et.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=Et.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let kt=!1,Bt=0;const Lt=16384,Dt=new Map;let Ut=null;function Wt(e){const t=(0===Bt&&Mt&&(Bt=Mt._malloc(Lt)),Bt);if(0===t||!Mt)return{ptr:0,count:0};let s=0,n=0;const i=Mt.HEAPU8,o=Mt.HEAPU32,r=Mt.HEAPF32;for(const[a,l]of e){if(Pt(l))continue;let e=Dt.get(a);e||(Ut||(Ut=new TextEncoder),e=Ut.encode(a),Dt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Lt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Lt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function zt(){if(!Mt||kt)return;Mt.materialDataProvider=(e,t,s,n,i)=>{const o=Et.get(e);if(!o)return Mt.HEAPU32[t>>2]=0,Mt.HEAPU32[s>>2]=0,Mt.HEAPU32[n>>2]=0,void(Mt.HEAPU32[i>>2]=0);Mt.HEAPU32[t>>2]=o.shader,Mt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Wt(o.uniforms);Mt.HEAPU32[n>>2]=r,Mt.HEAPU32[i>>2]=a},kt=!0}const $t={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ot{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,s=O.assetLoadTimeout){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{r.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);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&&(this.failed_.set(e,{error:t,expiry:Date.now()+O.assetFailureCooldown}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Ht{constructor(e,t=""){this.cache_=new Ot,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 r(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ft.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Vt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Nt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const jt=new Map;function Xt(e){jt.set(e.name,e)}const Yt=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Gt(e,t){const s=e.getEntitiesWithComponents([Yt]);for(const n of s){const s=e.get(n,Yt);if(!s.enabled||!s.playing||!s.clip)continue;const i=jt.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ue)){const t=i.frames[s.currentFrame],o=e.get(n,ue);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,ue,o)}a&&e.insert(n,Yt,s)}}class qt{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}qt.mixer_=null,qt.bufferCache_=new Map,qt.bgmHandle_=null,qt.bgmVolume_=1,qt.fadeAnimId_=0,qt.disposed_=!1;const Kt=new Map,Jt=new Map;function Qt(e,t,s){Kt.set(e,{width:t,height:s})}function Zt(e){return Kt.get(e)}function es(){Kt.clear()}function ts(e,t){Jt.set(e,t)}function ss(e){return Jt.get(e)}let ns=null;function is(e){ns=e}function os(){ns=null}const rs={initLayer(e,t,s,n,i){ns?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){ns?.tilemap_destroyLayer(e)},setTile(e,t,s,n){ns?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>ns?ns.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){ns?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!ns)return;const s=t.byteLength,n=ns._malloc(s);new Uint16Array(ns.HEAPU8.buffer,n,t.length).set(t),ns.tilemap_setTiles(e,n,t.length),ns._free(n)},hasLayer:e=>!!ns&&ns.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x){ns?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x)}},as=K("Tilemap",{source:""}),ls=K("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function cs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function us(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function ds(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function hs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ds(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=us(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&d.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function ps(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}const fs=Math.PI/180;function ms(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,d=o+(u-t.row*c)-.5*n,h=e.spawn();e.insert(h,ae,{position:{x:r,y:d,z:0}}),e.insert(h,Me,{bodyType:Ae.Static}),e.insert(h,Te,{halfExtents:{x:.5*s,y:.5*n}}),a.push(h)}return a}const gs=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function ys(e){const t=gs.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function _s(e){return gs.get(e)?.fields??[]}function xs(e){return gs.get(e)?.spine??null}const ws=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function bs(e){return ws.get(e)}function vs(e,t){const s=ws.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function Ss(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,ve,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)vs(i,s),Cs(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function Ps(e,t){return Ss(e,t)}async function Ms(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Ts.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=gs.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Ts.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=gs.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=Ss(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const Ts=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o),Qt(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Vt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Xt(Nt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await qt.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=hs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=ps(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),Qt(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}ts(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Cs(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=se(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Es(e,t){const s=e.getEntitiesWithComponents([de]);for(const n of s){const s=e.get(n,de);s&&(s.aspectRatio=t,e.insert(n,de,s))}}class As{constructor(e){this.textureCache_=new Ot,this.shaderCache_=new Ot,this.jsonCache_=new Ot,this.textCache_=new Ot,this.binaryCache_=new Ot,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ot,this.prefabCache_=new Ot,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l(O.textCanvasSize,O.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 Ht(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===b(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=b(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const i=s?`${s}/${n}`:n;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of ys(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=xs(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ms(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Ft.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ft.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Rs=Ie(null,"Assets");class Is{build(e){const t=e.wasmModule;t?e.insertResource(Rs,new As(t)):console.warn("AssetPlugin: No WASM module available")}}const Fs=new Is;async function ks(e,t,s){const{entities:n,rootId:i}=await Ls(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Ms(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const Bs=10;async function Ls(e,t,s,n,i,o=0){if(o>Bs)throw new Error(`Prefab nesting depth exceeded ${Bs}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Ls(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Ds(d.components,r),Us(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Ds(e,t){for(const s of e){const e=bs(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function Us(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 Ws{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ks(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const zs=Ie(null,"Prefabs");class $s{constructor(){this.name="PrefabsPlugin",this.dependencies=[Rs]}build(e){const t=e.getResource(Rs);e.insertResource(zs,new Ws(e.world,t))}}const Os=new $s;let Hs=null,Vs=0,Ns=0,js=0;const Xs=new Float32Array(256);function Ys(e){Hs=e,Vs=Hs._malloc(64),Ns=Hs._malloc(64),js=Hs._malloc(1024)}function Gs(){Hs&&(Vs&&(Hs._free(Vs),Vs=0),Ns&&(Hs._free(Ns),Ns=0),js&&(Hs._free(js),js=0)),Hs=null}function qs(){if(!Hs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Hs}const Ks={r:1,g:1,b:1,a:1},Js={begin(e){const t=qs();try{t.HEAPF32.set(e,Vs/4),t.draw_begin(Vs)}catch(e){Ne(e,"Draw.begin")}},end(){try{qs().draw_end()}catch(e){Ne(e,"Draw.end")}},line(e,t,s,n=1){try{qs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.line")}},rect(e,t,s,n=!0){try{qs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{qs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{qs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{qs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circleOutline")}},texture(e,t,s,n=Ks){try{qs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ne(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Ks){try{qs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ne(e,"Draw.textureRotated")}},setLayer(e){qs().draw_setLayer(e)},setDepth(e){qs().draw_setDepth(e)},getDrawCallCount:()=>Hs?Hs.draw_getDrawCallCount():0,getPrimitiveCount:()=>Hs?Hs.draw_getPrimitiveCount():0,setBlendMode(e){qs().draw_setBlendMode(e)},setDepthTest(e){qs().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=qs();n.HEAPF32.set(s,Ns/4),n.draw_mesh(e,t,Ns)}catch(s){Ne(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=qs(),i=Ft.get(t);if(!i)return;if(Js.setBlendMode(i.blendMode),Js.setDepthTest(i.depthTest),0===i.uniforms.size)return void Js.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Ns/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=en(t);if(!(n<0)){if(Pt(s))Xs[o++]=10,Xs[o++]=n,Xs[o++]=s.slot??e++,Xs[o++]=s.textureId;else if("number"==typeof s)Xs[o++]=1,Xs[o++]=n,Xs[o++]=s;else if(Array.isArray(s)){Xs[o++]=s.length,Xs[o++]=n;for(let e=0;e<s.length;e++)Xs[o++]=s[e]}else"w"in s?(Xs[o++]=4,Xs[o++]=n,Xs[o++]=s.x,Xs[o++]=s.y,Xs[o++]=s.z,Xs[o++]=s.w):"z"in s?(Xs[o++]=3,Xs[o++]=n,Xs[o++]=s.x,Xs[o++]=s.y,Xs[o++]=s.z):(Xs[o++]=2,Xs[o++]=n,Xs[o++]=s.x,Xs[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(Xs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Ns);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),js/4),n.draw_meshWithUniforms(e,i.shader,Ns,js,o)}catch(s){Ne(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Qs={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},Zs=new Set;function en(e){const t=Qs[e];return void 0!==t?t:(Zs.has(e)||(Zs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Qs).join(", ")}`)),-1)}const tn=new Map;function sn(e,t,s){tn.set(e,{fn:t,scene:s??""})}function nn(e){tn.delete(e)}function on(){tn.clear()}var rn;exports.DataType=void 0,(rn=exports.DataType||(exports.DataType={}))[rn.Float=1]="Float",rn[rn.Float2=2]="Float2",rn[rn.Float3=3]="Float3",rn[rn.Float4=4]="Float4",rn[rn.Int=5]="Int",rn[rn.Int2=6]="Int2",rn[rn.Int3=7]="Int3",rn[rn.Int4=8]="Int4";let an=null,ln=0,cn=0,un=0;function dn(e){an=e,ln=an._malloc(262144),cn=an._malloc(65536),un=an._malloc(256)}function hn(){an&&(ln&&an._free(ln),cn&&an._free(cn),un&&an._free(un),ln=0,cn=0,un=0),an=null}function pn(){if(!an)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return an}const fn={create(e){const t=pn(),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,ln/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,un,i).set(o),t.geometry_init(s,ln,n,un,i,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,cn,n).set(e.indices),t.geometry_setIndices16(s,cn,n)}else{new Uint32Array(t.HEAPU8.buffer,cn,n).set(e.indices),t.geometry_setIndices32(s,cn,n)}}return s},updateVertices(e,t,s=0){const n=pn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,ln/4),n.geometry_updateVertices(e,ln,i,s)},release(e){e>0&&pn().geometry_release(e)},isValid:e=>!(!an||e<=0)&&an.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return fn.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return fn.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return fn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let mn=1;const gn=new Map,yn=new Map;function _n(){return gn}function xn(){return yn}class wn{constructor(){this.passes_=[],this.destroyed_=!1,this.id=mn++,gn.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of yn)t===this&&yn.delete(e);gn.delete(this.id)}}}const bn="#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";let vn=null;function Sn(e){vn=e}function Pn(){for(const e of _n().values())e.destroy();_n().clear(),xn().clear(),vn&&Tn.isInitialized()&&Tn.shutdown(),vn=null}function Mn(){if(!vn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vn}const Tn={createStack:()=>new wn,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");xn().set(e,t)},unbind(e){xn().delete(e)},getStack:e=>xn().get(e)??null,init(e,t){try{return Mn().postprocess_init(e,t)}catch(s){return Ne(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Mn().postprocess_shutdown()}catch(e){Ne(e,"PostProcess.shutdown")}},resize(e,t){try{Mn().postprocess_resize(e,t)}catch(s){Ne(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!vn)return!1;try{return vn.postprocess_isInitialized()}catch(e){return Ne(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Mn().postprocess_setBypass(e)}catch(e){Ne(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{Mn().postprocess_setOutputViewport(e,t,s,n)}catch(e){Ne(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=xn().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Tn.isInitialized()||Tn.init(1,1),Tn.setBypass(!1),function(e){const t=Mn();try{t.postprocess_clearPasses()}catch(e){return void Ne(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):Tn.setBypass(!0)},_resetAfterCamera(){try{Mn().postprocess_clearPasses(),Mn().postprocess_setBypass(!0)}catch(e){Ne(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of xn().keys())e(t)||xn().delete(t)},screenStack:null,setScreenStack(e){Tn.screenStack=e},_beginScreenCapture(){try{Mn().postprocess_beginScreenCapture()}catch(e){Ne(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Mn().postprocess_endScreenCapture()}catch(e){Ne(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Tn.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Mn();try{t.postprocess_clearScreenPasses()}catch(e){return void Ne(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{Mn().postprocess_executeScreenPasses()}catch(e){Ne(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Ft.createShader(bn,"#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(bn,"#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(bn,"#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"),createBloom:()=>Ft.createShader(bn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Ft.createShader(bn,"#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")},Cn=new Map;function En(e){Cn.set(e.type,e)}function An(e){return Cn.get(e)}En({type:"blur",label:"Blur",factory:()=>Tn.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),En({type:"bloom",label:"Bloom",factory:()=>Tn.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),En({type:"vignette",label:"Vignette",factory:()=>Tn.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),En({type:"grayscale",label:"Grayscale",factory:()=>Tn.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),En({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Tn.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Rn=new Map,In=new Map;function Fn(e){const t=Rn.get(e);t&&(Tn.unbind(e),t.destroy(),Rn.delete(e));const s=In.get(e);if(s){for(const e of s.values())Ft.releaseShader(e);In.delete(e)}}function kn(){for(const e of Rn.keys())Fn(e)}const Bn=Ie({enabled:!0},"PostProcessVolumeConfig"),Ln=new Map,Dn=new Map;function Un(e){const t=Dn.get(e);if(void 0!==t)return t;const s=An(e);if(!s)return null;const n=s.factory();return Dn.set(e,n),n}function Wn(e,t){if(0===t.size){const t=Ln.get(e);return void(t&&(Tn.unbind(e),t.destroy(),Ln.delete(e)))}let s=Ln.get(e);for(s||(s=Tn.createStack(),Ln.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Un(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?Tn.bind(e,s):Tn.unbind(e)}const zn=mt([nt(Pe,ae)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Ln)Wn(t,e)}},{name:"PostProcessVolumeSystem"});class $n{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Bn,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,zn)}cleanup(){kn(),function(){for(const[e,t]of Ln)Tn.unbind(e),t.destroy();Ln.clear();for(const e of Dn.values())Ft.releaseShader(e);Dn.clear()}(),Tn.setScreenStack(null)}}const On=new $n;var Hn;exports.RenderStage=void 0,(Hn=exports.RenderStage||(exports.RenderStage={}))[Hn.Background=0]="Background",Hn[Hn.Opaque=1]="Opaque",Hn[Hn.Transparent=2]="Transparent",Hn[Hn.Overlay=3]="Overlay";let Vn=null,Nn=0;function jn(e){Vn=e,Nn=Vn._malloc(64)}function Xn(){Vn&&Nn&&(Vn._free(Nn),Nn=0),Vn=null}const Yn={init(e,t){Vn?.renderer_init(e,t)},resize(e,t){Vn?.renderer_resize(e,t)},begin(e,t){if(Vn&&Nn)try{Vn.HEAPF32.set(e,Nn/4),Vn.renderer_begin(Nn,t??0)}catch(e){Ne(e,"Renderer.begin")}},flush(){try{Vn?.renderer_flush()}catch(e){Ne(e,"Renderer.flush")}},end(){try{Vn?.renderer_end()}catch(e){Ne(e,"Renderer.end")}},submitSprites(e){if(Vn)try{Vn.renderer_submitSprites(e._cpp)}catch(e){Ne(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Vn)try{Vn.renderer_submitBitmapText(e._cpp)}catch(e){Ne(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Vn)try{Vn.renderer_submitSpine?.(e._cpp)}catch(e){Ne(e,"Renderer.submitSpine")}},submitParticles(e){if(Vn)try{Vn.renderer_submitParticles?.(e._cpp)}catch(e){Ne(e,"Renderer.submitParticles")}},setStage(e){Vn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Vn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Vn?.renderer_releaseTarget(e)},getTargetTexture:e=>Vn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Vn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Vn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Vn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Vn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Vn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Vn?Vn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Vn?{drawCalls:Vn.renderer_getDrawCalls(),triangles:Vn.renderer_getTriangles(),sprites:Vn.renderer_getSprites(),text:Vn.renderer_getText(),spine:Vn.renderer_getSpine?.()??0,meshes:Vn.renderer_getMeshes(),culled:Vn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Gn=null;function qn(e){Gn=e}function Kn(){Gn=null}const Jn={enable(){Gn?.gl_enableErrorCheck(!0)},disable(){Gn?.gl_enableErrorCheck(!1)},check:e=>Gn?.gl_checkErrors(e)??0,diagnose(){Gn?.renderer_diagnose()}};class Qn{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Tn.screenStack&&Tn.screenStack.enabledPassCount>0&&(Tn.isInitialized()||Tn.init(1,1),Tn._applyScreenStack(),Tn._beginScreenCapture())}endScreenCapture(){Tn.screenStack&&Tn.screenStack.enabledPassCount>0&&(Tn._endScreenCapture(),Tn._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Yn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Yn.setViewport(0,0,n,i),Yn.clearBuffers(3),Yn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Yn.submitSprites(t),Yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Yn.submitSpine(t),Yn.submitParticles(t),Yn.flush(),this.executeDrawCallbacks(s,o),Yn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Tn.getStack(r);a&&(Tn._applyForCamera(r),Tn.resize(n.w,n.h),Tn.setOutputViewport(n.x,n.y,n.w,n.h)),Yn.setViewport(n.x,n.y,n.w,n.h),Yn.setScissor(n.x,n.y,n.w,n.h,!0),Yn.clearBuffers(i),Yn.setScissor(0,0,0,0,!1),Yn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Yn.submitSprites(t),Yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Yn.submitSpine(t),Yn.submitParticles(t),Yn.flush(),this.executeDrawCallbacks(s,o),Yn.end(),a&&Tn._resetAfterCamera()}executeDrawCallbacks(e,t){const s=tn;if(s.size>0){Js.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}Js.end();for(const e of n)nn(e)}}}const Zn="__scene_transition_overlay__";class ei{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ti{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Se,{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),sn(e,t,this.instance_.config.name)}bindPostProcess(e,t){Tn.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Tn.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);s.persistent=t,this.app_.world.insert(e,Se,s)}}}class si{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())nn(t);for(const t of e.postProcessBindings.keys())Tn.unbind(t)}this.transition_&&(nn(Zn),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??O.sceneTransitionDuration,i=t.color??{...O.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},sn(Zn,()=>{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;Js.setLayer(9999),Js.setDepth(9999),Js.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,nn(Zn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,nn(Zn),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 ei(t);this.scenes_.set(e,s);const n=new ti(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Rs)?this.app_.getResource(Rs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ei(t);this.scenes_.set(e,s);const n=new ti(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Rs)?this.app_.getResource(Rs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Se)){if(this.app_.world.get(e,Se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())nn(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())Tn.unbind(e);s.postProcessBindings.clear(),this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(Rs)&&(i.assetServer=this.app_.getResource(Rs));const o=await Ms(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,Se,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ii(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Rs)?this.app_.getResource(Rs):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)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 s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,ue)){const t=s.get(e,ue);n.sprite=t.color.a,t.color.a=0,s.insert(e,ue,t),i=!0}if(s.has(e,ye)){const t=s.get(e,ye);n.spine=t.color.a,t.color.a=0,s.insert(e,ye,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ue)){const t=s.get(e,ue);t.color.a=n.sprite,s.insert(e,ue,t)}if(void 0!==n.spine&&s.has(e,ye)){const t=s.get(e,ye);t.color.a=n.spine,s.insert(e,ye,t)}if(void 0!==n.bitmapText&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.bitmapText,s.insert(e,ge,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessBindings.values())s.setAllPassesEnabled(t)}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 ni=Ie(null,"SceneManager");function ii(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ni).getSceneStatus(t)&&s._fn(...n)}}}const oi=mt([ke(ni),Fe(De)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ri={name:"SceneManager",build(e){const t=new si(e);e.insertResource(ni,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ni),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,oi)}};class ai{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new ct,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Je,this.resources_=new Le;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ai}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Ve(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ni).register(e),this}setInitialScene(e){return this.getResource(ni).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new yt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(De)||this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new yt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,on();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=[Kn,Xn,Pn,hn,Rt,Gs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(De);t.delta=e,t.elapsed+=e,t.frameCount++}}function li(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ci=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ui(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case re.FixedWidth:return o;case re.FixedHeight:return r;case re.Expand:return Math.max(o,r);case re.Shrink:return Math.min(o,r);case re.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const di=[];function hi(e){if(e<di.length)return di[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return di.push(t),t}function pi(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,Se);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===ie.Orthographic){if(d=i.orthoSize,l){d=ui(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=mi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=yi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=xi(o.position.x,o.position.y,o.position.z),p=hi(c.length);p.entity=e,p.viewProjection.set(bi(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const fi=new Float32Array(16);function mi(e,t,s,n,i,o){const r=fi;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const gi=new Float32Array(16);function yi(e,t,s,n){const i=gi;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const _i=new Float32Array(16);function xi(e,t,s){const n=_i;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 wi=new Float32Array(16);function bi(e,t){const s=wi;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const vi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Si(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const Pi=ne("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let Mi=null,Ti=null;function Ci(e,t){e.has(t,ue)||e.insert(t,ue,{texture:N,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 Ei(e,t){switch(e){case vi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Ai(e,t,s,n){if(!e.has(t,Pi))return;const i=e.get(t,Pi),o=Ei(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Pi,i)}function Ri(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ii(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Fi(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Ii(r.charCodeAt(0))&&n.length>0&&Ii(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Ii(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function ki(e){let t=1;for(;t<e;)t*=2;return t}function Bi(e,t){let s=0,n=t;for(;e.has(n,fe);){const t=e.get(n,fe).entity;if(!e.valid(t))break;s++,n=t}return s}function Li(e,t){if(Mi&&Ti){const e=Mi.getUIRectComputedWidth(Ti,t);if(e>0)return e}return e.size.x}function Di(e,t){if(Mi&&Ti){const e=Mi.getUIRectComputedHeight(Ti,t);if(e>0)return e}return e.size.y}function Ui(e,t,s){let n=t;for(;e.has(n,fe);){const t=e.get(n,fe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Wi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function zi(e,t,s,n,i){if(!e.has(t,Pi))return;const o=e.get(t,Pi),r=Si(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,ue)){const s=e.get(t,ue);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ue,s))}if(e.has(t,ae)){const s=e.get(t,ae);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,ae,s)}}function $i(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Oi=.1,Hi=30,Vi={r:.3,g:.5,b:.8,a:1},Ni={Left:0,Center:1,Right:2},ji={Top:0,Middle:1,Bottom:2},Xi={Visible:0,Clip:1,Ellipsis:2},Yi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ni.Left,verticalAlign:ji.Top,wordWrap:!0,overflow:Xi.Visible,lineHeight:1.2});class Gi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l(O.textCanvasSize,O.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,ki(this.frameMaxW_)),e.height=Math.max(e.height,ki(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ki(this.frameMaxW_),e.height=ki(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Fi(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Xi.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,ki(p)),n.height=Math.max(n.height,ki(f)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===Xi.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case ji.Top:w=u;break;case ji.Middle:w=u+(f-2*u-x)/2;break;case ji.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let n;switch(e.align){case Ni.Left:n=u;break;case Ni.Center:n=p/2;break;case Ni.Right:n=p-u;break;default:n=u}s.fillText(t,n,b),b+=c}i&&e.overflow===Xi.Clip&&s.restore();const v=s.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Ni.Left:return"left";case Ni.Center:return"center";case Ni.Right:return"right"}}}const qi=$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?Li(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0});class Ki{build(e){te("Text",Yi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Gi(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Yi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Yi)){if(n.valid(e)&&n.has(e,ue)){const t=n.get(e,ue);n.insert(e,ue,{texture:N,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Yi]);for(const t of e){const e=n.get(t,Yi),o=n.has(t,Pi)?n.get(t,Pi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!qi.changed(a,r)){if(n.has(t,ue)&&n.get(t,ue).texture!==N)continue}Ci(n,t);const l=o?{size:{x:Li(o,t),y:Di(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ue);n.insert(t,ue,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,qi.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ji=new Ki,Qi=0,Zi=1,eo=ne("UIMask",{enabled:!0,mode:Qi});function to(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,i-s),h:Math.max(0,o-n)}}function so(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,b=n*u-r*a,v=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,C=d*_-f*m,E=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+b*E+v*C-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*E)*I,s[1]=(o*A-i*R-r*E)*I,s[2]=(g*P-y*S+_*v)*I,s[3]=(p*S-h*P-f*v)*I,s[4]=(c*C-a*R-u*T)*I,s[5]=(n*R-o*C+r*T)*I,s[6]=(y*b-m*P-_*w)*I,s[7]=(d*P-p*b+f*w)*I,s[8]=(a*A-l*C+u*M)*I,s[9]=(i*C-n*A-r*M)*I,s[10]=(m*S-g*b+_*x)*I,s[11]=(h*b-d*S-f*x)*I,s[12]=(l*T-a*E-c*M)*I,s[13]=(n*E-i*T+o*M)*I,s[14]=(g*w-m*v-y*x)*I,s[15]=(d*v-h*w+p*x)*I),s}function no(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function io(e,t){return 2*Math.atan2(e,t)}function oo(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function ro(e,t,s,n,i,o,r){if(!e.has(t,Pi)||!e.has(t,ae))return null;const a=e.get(t,Pi),l=e.get(t,ae),c=Li(a,t)*l.worldScale.x,u=Di(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=io(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),b=Math.sin(x),v=[[d+m*w-y*b,h+m*b+y*w],[d+g*w-y*b,h+g*b+y*w],[d+g*w-_*b,h+g*b+_*w],[d+m*w-_*b,h+m*b+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=oo(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function ao(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([eo]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,eo);s.enabled&&(d.add(e),s.mode===Zi?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Ui(t,e,e=>{if(i.has(e)){if(t.get(e,eo).mode===Qi)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,eo).mode===Qi){const e=ro(t,s,o,r,a,l,c);e&&(n=to(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ro(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Ui(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class lo{build(e){if(te("UIMask",eo),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ao(e.wasmModule,e.world))}}const co=new lo,uo=ne("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),ho=ne("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),po={Normal:0,Hovered:1,Pressed:2,Disabled:3},fo=K("Button",{state:po.Normal,transition:null});class mo{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 go=Ie(new mo,"UIEvents");class yo{build(e){te("UIRect",Pi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){Mi=e,Ti=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(vt)],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,mt([Fe(vt)],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,mt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const _o=new yo;let xo=!1,wo=!1;function bo(){return xo}function vo(){return wo}const So=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&&(so(t,e),s=!1),e)}}();function Po(e,t,s,n){t.emit(s,n,s),Ui(e,s,i=>{if(!e.has(i,uo))return!1;const o=e.get(i,uo);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Mo{build(e){te("Interactable",uo),te("Button",fo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new mo;e.insertResource(go,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(xt),Fe(vt)],(e,a)=>{if(i.drain(),bo()&&!vo())return;const l=t.getEntitiesWithComponents([ho]);for(const e of l){const s=t.get(e,ho);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,ho,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;So.update(a.viewProjection);const p=no(d,h,So.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,ho)){const e=t.get(o,ho);e.hovered=!1,t.insert(o,ho,e),i.emit(o,"hover_exit")}if(null!==_){Wi(t,_,ho);const e=t.get(_,ho);e.hovered=!0,t.insert(_,ho,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,ho);e.pressed=!0,e.justPressed=!0,t.insert(_,ho,e),r=_,Po(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,ho)){const e=t.get(r,ho);e.pressed=!1,e.justReleased=!0,t.insert(r,ho,e),Po(t,i,r,"release"),r===o&&Po(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,mt([],()=>{const e=t.getEntitiesWithComponents([fo]);for(const s of e){if(Wi(t,s,uo,{enabled:!0}),!t.has(s,ho))continue;const e=t.get(s,ho),n=t.get(s,fo),i=t.get(s,uo),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=po.Pressed:e.hovered?n.state=po.Hovered:n.state=po.Normal:n.state=po.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ue)){const o=t.get(s,ue);o.color=Ri(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ue,o)}}},{name:"ButtonSystem"}))}}const To=new Mo,Co=K("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Eo=K("Focusable",{tabIndex:0,isFocused:!1});class Ao{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 Ro=Ie(new Ao,"FocusManager");class Io{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(te("TextInput",Co),bo()&&!vo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l(O.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,c=!1,u=!0,d=0,h=0;const p=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!p)return;const f=p;function m(){const t=e.getResource(Ro);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Co)?n:null}const g=()=>{c||null===m()||b()},y=()=>{c=!0},_=()=>{c=!1,b()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void v();const i=s.get(n,Co);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(go).emit(n,"submit"),void v()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Co);n.focused=!1,n.dirty=!0;e.getResource(Ro).blur()}};function b(){const t=m();if(null===t)return;const n=s.get(t,Co);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(go).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=s.get(t,Co);e.focused=!1,e.dirty=!0}e.getResource(Ro).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=ki(Math.max(i.width,c)),i.height=ki(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=p?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Fi(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Fi(o,l.value,c-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const b=n.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(c,d,r,x.length,1,!0);n.set(e,v);const S=s.get(e,ue);S.texture=v,S.size.x=c,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,ue,S)}e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(Ro)],e=>{const t=s.getEntitiesWithComponents([Co]);for(const e of t)Wi(s,e,Eo,{tabIndex:0,isFocused:!1}),Wi(s,e,uo,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Co)){const e=s.get(P,Co);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Co);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,u=!u;s.get(o,Co).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Co)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Co,Pi]);for(const e of a){const t=s.get(e,Co);if(!t.dirty)continue;const n=s.get(e,Pi),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(Ci(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Fo=new Io,ko={Simple:0,Sliced:1,Tiled:2,Filled:3},Bo={Horizontal:0,Vertical:1},Lo={Left:0,Right:1,Bottom:2,Top:3},Do=K("Image",{texture:N,color:{r:1,g:1,b:1,a:1},imageType:ko.Simple,fillMethod:Bo.Horizontal,fillOrigin:Lo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Uo=$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?Li(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Wo{build(e){te("Image",Do);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Do)||s.delete(e);const e=t.getEntitiesWithComponents([Do]);for(const n of e){const e=t.get(n,Do),i=t.has(n,Pi)?t.get(n,Pi):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Uo.changed(r,o))continue;Ci(t,n);const a=t.get(n,ue);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=Li(i,n),a.size.y=Di(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===ko.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Bo.Horizontal?e.fillOrigin===Lo.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===Lo.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===ko.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,ue,a),s.set(n,Uo.take(o))}else a.color.a=0,t.insert(n,ue,a),s.set(n,Uo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const zo=new Wo,$o=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Oo=K("ToggleGroup",{allowSwitchOff:!1});class Ho{build(e){te("Toggle",$o),te("ToggleGroup",Oo);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(go)],e=>{const n=t.getEntitiesWithComponents([$o]);if(!bo()||vo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,$o);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,$o,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,$o);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(Wi(t,s,uo,{enabled:!0}),!t.has(s,ho))continue;const n=t.get(s,ho),i=t.get(s,$o),r=t.get(s,uo);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Oo);if(i.isOn&&r){if(!t.get(n,Oo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,$o,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,$o);i.isOn&&(i.isOn=!1,t.insert(n,$o,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ue)){const e=t.get(s,ue);e.color=Ri(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ue,e)}}}for(const e of n){const s=t.get(e,$o);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ue)){const e=t.get(s.graphicEntity,ue);e.enabled=s.isOn,t.insert(s.graphicEntity,ue,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Vo=new Ho,No=vi,jo=K("ProgressBar",{value:0,fillEntity:0,direction:vi.LeftToRight});function Xo(e,t,s,n){if(!e.has(t,Pi))return;const i=e.get(t,Pi),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=Si(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ue)){const s=e.get(t,ue);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ue,s))}if(e.has(t,ae)){const s=e.get(t,ae),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,ae,s))}}class Yo{build(e){te("ProgressBar",jo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{const e=t.getEntitiesWithComponents([jo,Pi]);for(const s of e){const e=t.get(s,jo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Pi),i=Math.max(0,Math.min(1,e.value));Ai(t,e.fillEntity,e.direction,i);const o=Li(n,s),r=Di(n,s);Xo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Go=new Yo,qo=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ko=K("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class Jo{build(e){te("Draggable",qo),te("DragState",Ko);const t=e.world,s=e.getResource(go);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(xt),Fe(vt)],(e,r)=>{if(bo()&&!vo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([qo,ho]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,qo).enabled)continue;if(t.get(n,ho).hovered){let e=0;t.has(n,ue)&&(e=t.get(n,ue).layer);const i=Bi(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Ko)||t.insert(s,Ko);const e=t.get(s,Ko),o=t.get(s,ae);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,Ko)){t.get(n,Ko).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,qo);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Ko).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Ko))return void(o=null);const n=t.get(o,Ko),i=t.get(o,qo),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,ae)){const e=function(e,t,s,n){if(!e.has(t,fe))return{x:s,y:n};const i=e.get(t,fe).entity;if(!e.valid(i)||!e.has(i,ae))return{x:s,y:n};const o=e.get(i,ae),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=io(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,ae);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ae,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Qo=new Jo,Zo=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function er(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 tr(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class sr{build(e){te("ScrollView",Zo);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([Fe(xt),Fe(vt),Fe(De)],(e,i,o)=>{const r=bo()&&!vo(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Zo,Pi]);for(const o of l){Wi(t,o,eo,{enabled:!0,mode:Qi});const l=t.get(o,Zo),c=t.get(o,Pi);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=Li(c,o),h=Di(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,me)){const e=t.get(l.contentEntity,me).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,ae))continue;const e=t.get(r,ae);let a=0,l=0,c=.5,u=.5;if(t.has(r,Pi)){const e=t.get(r,Pi);a=Li(e,r)||e.size.x,l=Di(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ue)){const e=t.get(r,ue);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){Wi(t,o,uo,{enabled:!0,blockRaycast:!0});const s=t.has(o,ho)?t.get(o,ho):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=er(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=er(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=er(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=er(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=tr(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Oi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Oi?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=tr(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Oi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Oi?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ae)){const e=t.get(l.contentEntity,ae),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,ae,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const nr=new sr,ir=vi,or=K("Slider",{value:0,minValue:0,maxValue:1,direction:vi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function rr(e,t,s,n,i,o){const r=Li(n,i)*s.worldScale.x,a=Di(n,i)*s.worldScale.y,l=io(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case vi.LeftToRight:return r>0?(p-m)/r:0;case vi.RightToLeft:return r>0?1-(p-m)/r:0;case vi.BottomToTop:return a>0?(f-g)/a:0;case vi.TopToBottom:return a>0?1-(f-g)/a:0}}function ar(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case vi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case vi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case vi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case vi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class lr{build(e){te("Slider",or);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(xt),Fe(vt),Fe(go)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([or,Pi]);for(const r of o){const o=t.get(r,or),a=t.get(r,Pi);if(!bo()||vo()){if(t.has(r,ae)){Wi(t,r,uo,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Wi(t,o.handleEntity,uo,{enabled:!0,blockRaycast:!1});const l=t.get(r,ae),c=t.has(r,ho)?t.get(r,ho):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,ho)&&(u=t.get(o.handleEntity,ho).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=rr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,or,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Li(a,r),d=Di(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ai(t,o.fillEntity,o.direction,c),zi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Pi)){const e=t.get(o.handleEntity,Pi);ar(e,o.direction,c),t.insert(o.handleEntity,Pi,e),zi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const cr=new lr;class ur{build(e){te("Focusable",Eo);const t=e.world,s=new Ao;e.insertResource(Ro,s),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(xt),Fe(go)],(e,n)=>{if(bo()&&!vo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Eo]);for(const e of i){if(!t.has(e,ho))continue;t.get(e,ho).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,uo)){if(!t.get(s,uo).enabled)continue}const n=t.get(s,Eo);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Eo)){t.get(i,Eo).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Eo).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const dr=new ur,hr=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function pr(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class fr{build(e){te("SafeArea",hr);const t=e.world;let n=pr(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=pr(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=pr(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(vt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([hr,Pi]);for(const e of d){const s=t.get(e,hr),i=t.get(e,Pi),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Pi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const mr=new fr,gr=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let yr=null;class _r{build(e){te("ListView",gr);const t=e.world,s=new Map;yr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([Fe(xt)],e=>{const n=bo()&&!vo();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([gr,Pi]);for(const o of i){Wi(t,o,uo,{enabled:!0,blockRaycast:!0}),Wi(t,o,eo,{enabled:!0,mode:Qi});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,gr),a=t.get(o,Pi),l=Di(a,o),c=Li(a,o);if(!n){const s=t.has(o,ho)?t.get(o,ho):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ve,{value:`ListItem_${e}`}),t.insert(s,Pi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,ae)){const n=t.get(s,ae);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,ae,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const xr=new _r,wr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class br{build(e){te("Dropdown",wr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ae))return;const s=t.get(e,ae);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ae,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,ue)){const s=t.get(e,ue);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ue,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,ue),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Hi;t.insert(i,Pi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,ae,{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,ue,{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Hi;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,Pi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Hi},offsetMax:{x:0,y:0},size:{x:r,y:Hi},pivot:{x:.5,y:.5}}),t.insert(o,ae,{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,ue,{texture:N,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Hi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,uo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ae,{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,Yi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ni.Left,verticalAlign:ji.Middle,wordWrap:!1,overflow:Xi.Clip,lineHeight:1.2}),t.insert(c,Pi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Hi},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Yi))return;const n=t.get(s,Yi);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Yi,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,uo)&&t.insert(e,uo,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ue))){const n=t.get(e,ue);t.insert(e,ue,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ue))continue;const i=s===e.highlightIndex?{...Vi}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ue,{texture:N,color:i,size:{x:e.ddWidth,y:Hi},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,ho))continue;if(t.get(s,ho).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(xt),Fe(go)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=bo()&&!vo(),f=t.getEntitiesWithComponents([wr]);for(const m of f){const f=t.get(m,wr);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;Wi(t,m,uo,{enabled:!0,blockRaycast:!0});const y=t.has(m,ho)?t.get(m,ho):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,ho))continue;if(t.get(s,ho).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,ho))continue;if(t.get(n,ho).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const vr=new br,Sr=0,Pr=0,Mr=2,Tr=K("LayoutGroup",{direction:Sr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Pr,reverseOrder:!1});class Cr{build(e){te("LayoutGroup",Tr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{const e=t.getEntitiesWithComponents([Tr,Pi,me]);for(const s of e){const e=t.get(s,Tr),n=t.get(s,Pi),i=t.get(s,me);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Pi)&&t.has(e,ae)&&o.push({entity:e,rect:t.get(e,Pi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Li(n,s),a=Di(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===Sr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Li(n.rect,n.entity),p=Di(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===Pr?(1-c)*a-u.top-(1-m)*p:e.childAlignment===Mr?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Pr?-l*r+u.left+f*i:e.childAlignment===Mr?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,ae);_.position.x=g,_.position.y=y,t.insert(n.entity,ae,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Er=new Cr;class Ar{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Rr=new Ar;async function Ir(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 Fr=Ie({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),kr={r:.2,g:.4,b:1,a:.7},Br={r:.2,g:1,b:.2,a:.7},Lr={r:.2,g:1,b:1,a:.7},Dr={r:1,g:1,b:.2,a:.5},Ur={r:1,g:.2,b:.2,a:.8},Wr={r:1,g:.2,b:.2,a:1},zr=1.5,$r=16;function Or(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Hr(e){switch(e){case Ae.Static:return kr;case Ae.Kinematic:return Lr;default:return Br}}function Vr(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Js.line(l[e],l[(e+1)%4],o,zr)}function Nr(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),d=l(-s,-n),h=l(s,-n);Js.line(c,d,o,zr),Js.line(u,h,o,zr);for(let e=0;e<$r;e++){const t=e/$r*Math.PI,i=(e+1)/$r*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Js.line(r,a,o,zr)}for(let e=0;e<$r;e++){const t=Math.PI+e/$r*Math.PI,i=Math.PI+(e+1)/$r*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Js.line(r,a,o,zr)}}function jr(e,t,s,n){const i=e+.5*s,o=t+.5*n;Js.line({x:e,y:t},{x:i,y:o},Ur,zr);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),p=o-6*(-l*Math.sin(a)+c*Math.cos(a));Js.line({x:i,y:o},{x:u,y:d},Ur,zr),Js.line({x:i,y:o},{x:h,y:p},Ur,zr)}function Xr(e,t,s){if(bo()&&!vo())return;const n=e.getResource(Fr);if(!n||!n.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([he]);for(const s of t){const t=e.world.get(s,he);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Me,ae]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Me);if(!s.enabled)continue;const o=e.world.get(t,ae),a=o.worldPosition.x,l=o.worldPosition.y,c=Or(o.worldRotation);if(n.showColliders){if(e.world.has(t,Te)){const n=e.world.get(t,Te),o=n.isSensor?Dr:Hr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Vr(a+r*d-u*h,l+r*h+u*d,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Ce)){const n=e.world.get(t,Ce),o=n.isSensor?Dr:Hr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;Js.circleOutline({x:p,y:f},n.radius*i,o,zr,32)}if(e.world.has(t,Ee)){const n=e.world.get(t,Ee),o=n.isSensor?Dr:Hr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Nr(a+r*d-u*h,l+r*h+u*d,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Ae.Dynamic){const e=r.getLinearVelocity(t);jr(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Js.circle({x:e.contactX,y:e.contactY},3,Wr,!0,32)}}const Yr=Ie({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Gr=Ie(null,"PhysicsAPI");function qr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Kr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Jr{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,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(Yr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Ir(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([he]);for(const s of t){const t=e.world.get(s,he);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([Fe(De)],a=>{if(bo()&&!vo())return;const l=r.getEntitiesWithComponents([Me,ae]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,ae);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=qr(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ea(e,n,i,this.config_.collisionLayerMasks),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ae.Kinematic){const e=qr(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,ae);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,fe)){const t=e.world.get(r,fe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ae)){const s=e.world.get(t.entity,ae),n=qr(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Kr(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(r,ae,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Yr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Gr,ta._fromModule(n)),function(e,t,s){e.insertResource(Fr,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),sn("physics-debug-draw",()=>{Xr(e,t,s)})}(e,Gr,Yr),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}const Qr=16;function Zr(e,t,s){if(!s)return t;for(let t=0;t<Qr;t++)if(e===1<<t)return s[t];return t}function ea(e,t,s,n){const i=e.world;if(i.has(s,Te)){const e=i.get(s,Te),o=e.categoryBits??1,r=Zr(o,e.maskBits??65535,n);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,o,r)}if(i.has(s,Ce)){const e=i.get(s,Ce),o=e.categoryBits??1,r=Zr(o,e.maskBits??65535,n);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(s,Ee)){const e=i.get(s,Ee),o=e.categoryBits??1,r=Zr(o,e.maskBits??65535,n);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}}class ta{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(ta.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)}static setDebugDraw(e,t){const s=e.getResource(Fr);s&&(s.enabled=t,e.insertResource(Fr,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Fr);s&&e.insertResource(Fr,{...s,...t})}}const sa={nearest:0,linear:1},na={repeat:0,clamp:1,mirror:2};function ia(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=sa[n.filterMode??"linear"]??1,a=na[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function oa(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 ra(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,_=l*p,x=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(y+x))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(f+x))*o,(_+w)*o,0,(g+b)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function aa(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=_s(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=ia(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=xs(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===b(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,r);if(t._free(d),p<0)continue;o[a]=p;const f=oa(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=ia(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...z},fixedTimestep:a?.fixedTimestep??$,subStepCount:a?.subStepCount??4};new Jr("",e,()=>Promise.resolve(r)).build(t)}const p=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=_s(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=b(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=ia(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),f=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=_s(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=Ft.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Ft.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=_s(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Vt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,ia(e,n))}catch{r.set(t,0)}Xt(Nt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=_s(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=hs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=ps(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=ia(e,t),Qt(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}ts(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=_s(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await qt.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await qt.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=_s(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,u,p,f);const m=Ps(t.world,n);if(c&&t.hasResource(ni))for(const e of m.values())t.world.insert(e,Se,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=xs(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=W);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ye)?c.get(o,ye):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,ae)){const e=ra(c.get(o,ae),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(Rs);e&&e.setAddressableManifest(l)}}function la(e,t,s){return{name:e,async setup(){await aa({...s,sceneData:t,sceneName:e})}}}async function ca(e){const{app:t,firstScene:s,aspectRatio:n}=e;li(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ni);for(const t of e.scenes)o.register(la(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Es(t.world,n)}class ua{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=xs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===b(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=_s(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=b(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const da="__preview__";const ha={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Yn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Yn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Yn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Yn.releaseRenderTarget(e._handle),ha.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Yn.begin(t,e._handle)},end(){Yn.end()},getDepthTexture:e=>Yn.getTargetDepthTexture(e._handle)};var pa;exports.LogLevel=void 0,(pa=exports.LogLevel||(exports.LogLevel={}))[pa.Debug=0]="Debug",pa[pa.Info=1]="Info",pa[pa.Warn=2]="Warn",pa[pa.Error=3]="Error";class fa{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 ma{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new fa)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ga=new ma;const ya={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},_a={Running:0,Paused:1,Completed:2,Cancelled:3},xa={None:0,Restart:1,PingPong:2};const wa=1.70158,ba=2.70158,va=2.5949095;const Sa=2*Math.PI/3,Pa=2*Math.PI/4.5;const Ma=7.5625,Ta=2.75;const Ca=1e-6;function Ea(e,t,s){switch(e){case ya.Linear:return t;case ya.EaseInQuad:return function(e){return e*e}(t);case ya.EaseOutQuad:return function(e){return e*(2-e)}(t);case ya.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ya.EaseInCubic:return function(e){return e*e*e}(t);case ya.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ya.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ya.EaseInBack:return function(e){return ba*e*e*e-wa*e*e}(t);case ya.EaseOutBack:return function(e){const t=e-1;return 1+ba*t*t*t+wa*t*t}(t);case ya.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-va)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+va)+2)/2}(t);case ya.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Sa)}(t);case ya.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Sa)+1}(t);case ya.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Pa)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Pa)/2+1}(t);case ya.EaseOutBounce:return function(e){return e<1/Ta?Ma*e*e:e<2/Ta?Ma*(e-=1.5/Ta)*e+.75:e<2.5/Ta?Ma*(e-=2.25/Ta)*e+.9375:Ma*(e-=2.625/Ta)*e+.984375}(t);case ya.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<Ca)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<Ca)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case ya.Step:return function(e){return e<1?0:1}(t);default:return t}}const Aa=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??ya.Linear,bezierPoints:null,state:_a.Running,loop:i?.loop??xa.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===_a.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==_a.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=Ea(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==xa.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===xa.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=_a.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===_a.Running&&(t.state=_a.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===_a.Paused&&(t.state=_a.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=_a.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:_a.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ra{constructor(e){this.id=e}get state(){return Aa.getState(this.id)}bezier(e,t,s,n){return Aa.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ra?Aa.setSequenceNext(this.id,e.id):Aa.setSequenceNextExternal(this.id,e),this}pause(){Aa.pause(this.id)}resume(){Aa.resume(this.id)}cancel(){Aa.cancel(this.id)}}class Ia{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return e instanceof Ra?(Aa.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Fa=null,ka=null;function Ba(e,t){Fa=e,ka=t,Aa.init(e,t)}function La(){Aa.shutdown(),Fa=null,ka=null}function Da(){if(!Fa)throw new Error("Tween API not initialized");return Fa}function Ua(){if(!ka)throw new Error("Tween API not initialized");return ka}const Wa={to(e,t,s,n,i,o){const r=Da(),a=Ua(),l=o?.easing??ya.Linear,c=o?.delay??0,u=o?.loop??xa.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Ia(r,a,h)},value(e,t,s,n,i){const o=Aa.create(e,t,s,n,i);return new Ra(o)},cancel(e){Da()._anim_cancelTween(Ua(),e.entity)},cancelAll(e){Da()._anim_cancelAllTweens(Ua(),e)},update(e){Da()._anim_updateTweens(Ua(),e),Aa.update(e)}};class za{constructor(){this.name="AnimationPlugin"}build(e){Ba(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Wa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Gt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){La()}}const $a=new za;var Oa;exports.AttenuationModel=void 0,(Oa=exports.AttenuationModel||(exports.AttenuationModel={}))[Oa.Linear=0]="Linear",Oa[Oa.Inverse=1]="Inverse",Oa[Oa.Exponential=2]="Exponential";const Ha={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Va(e,t=Ha){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case exports.AttenuationModel.Inverse:a=n/Math.max(r,n);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Na(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const ja=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),Xa=K("AudioListener",{enabled:!0});class Ya{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;qt.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(De)],t=>{if(!(!bo()||vo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([Xa,ce]);for(const e of h){if(n.get(e,Xa).enabled){const t=n.get(e,ce);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([ja]);a.clear();for(const e of p){const t=n.get(e,ja);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=qt.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,ce),a=r?.position.x??0,h=r?.position.y??0,p=a-i,f=h-u,m=Va(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Na(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),qt.dispose()}}const Ga=new Ya;let qa=null,Ka=null;function Ja(e,t){qa=e,Ka=t}function Qa(){qa=null,Ka=null}const Za={update(e){qa&&Ka&&qa.particle_update?.(Ka,e)},play(e){qa&&Ka&&qa.particle_play?.(Ka,e)},stop(e){qa&&Ka&&qa.particle_stop?.(Ka,e)},reset(e){qa&&Ka&&qa.particle_reset?.(Ka,e)},getAliveCount:e=>qa?qa.particle_getAliveCount?.(e)??0:0};class el{constructor(){this.name="ParticlePlugin"}build(e){Ja(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Za.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Qa()}}const tl=new el,sl=1e6;class nl{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){is(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(vt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:sl,l=i?.valid?i.worldTop:sl,c=t.getEntitiesWithComponents([ls,ae]);for(const e of c){const n=t.tryGet(e,ls),i=t.tryGet(e,ae);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=Zt(c);if(!u)continue;if(!s.has(e)){if(rs.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];rs.setTiles(e,t)}s.add(e)}const d=n.tileWidth/u.width,h=n.tileHeight/u.height,p=n.tint,f=n.parallaxFactor;rs.submitLayer(e,c,n.layer,0,n.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,p.r,p.g,p.b,p.a,n.opacity,f.x,f.y)}const u=t.getEntitiesWithComponents([as,ae]);for(const e of u){if(t.tryGet(e,ls))continue;const i=t.tryGet(e,as),c=t.tryGet(e,ae);if(!i?.source||!c)continue;const u=ss(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];rs.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&rs.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const d=n.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],s=u.tilesets[0];if(!s)continue;const n=Zt(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;rs.submitLayer(t,s.textureHandle,e,0,s.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)rs.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),es(),os()}}const il=new nl;function ol(e,t){return e.toFixed(t)}function rl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class al{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${ol(e.fps,1)}</span> Frame: <span style="color:#d19a66">${ol(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${rl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${ol(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function ll(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const cl=Ie(ll(),"Stats");const ul="StatsCollect";class dl{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class hl{constructor(e){this.name="Stats",this.collector_=new dl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(cl,ll());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new al(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=mt([Fe(De),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(cl);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(ul),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Yn.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:ul});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const pl=new hl;class fl{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function ml(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}const gl=[Ji,co,_o,zo,Go,To,Qo,nr,cr,Vo,Fo,dr,mr,xr,vr,Er,Rr],yl=[...gl,$a,Ga,tl,il,On];function _l(e,t){return function(e,t){const s=ai.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ys(e),At(e),dn(e),Sn(e),jn(e),qn(e);const i=new Qn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=pi(e,n,t,i));const r=s.getResource(vt);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(vt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Yn.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Yn.resize(t,l),s.hasResource(ni)){const e=s.getResource(ni).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=pi(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:ci,width:t,height:l,elapsed:d});else{i.beginScreenCapture();for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d,cameraEntity:e.entity})}i.endScreenCapture(),Yn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Fs),s.addPlugin(Os),s.addPlugin(bt),s.addPlugin(ri),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:yl,...t})}class xl{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function wl(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function bl(e,t){try{return await e({instantiateWasm:wl(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await f(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return m(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=za,exports.App=ai,exports.AssetPlugin=Is,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=As,exports.Assets=Rs,exports.AsyncCache=Ot,exports.Audio=qt,exports.AudioBus=d,exports.AudioListener=Xa,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new d(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}},exports.AudioPlugin=Ya,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=ja,exports.BitmapText=ge,exports.BodyType=Ae,exports.BoxCollider=Te,exports.Button=fo,exports.ButtonState=po,exports.Camera=de,exports.Canvas=he,exports.CapsuleCollider=Ee,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=me,exports.CircleCollider=Ce,exports.ClearFlags=oe,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=at,exports.DEFAULT_DESIGN_HEIGHT=D,exports.DEFAULT_DESIGN_WIDTH=L,exports.DEFAULT_FALLBACK_DT=W,exports.DEFAULT_FIXED_TIMESTEP=$,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=z,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE=U,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=Jo,exports.DragState=Ko,exports.Draggable=qo,exports.Draw=Js,exports.Dropdown=wr,exports.DropdownPlugin=br,exports.EasingType=ya,exports.EmitterShape=_e,exports.EntityCommands=rt,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=dt,exports.EventRegistry=ct,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=ut,exports.FillDirection=vi,exports.FillMethod=Bo,exports.FillOrigin=Lo,exports.FocusManager=Ro,exports.FocusManagerState=Ao,exports.FocusPlugin=ur,exports.Focusable=Eo,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=Jn,exports.Geometry=fn,exports.GetWorld=pt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=j,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=N,exports.Image=Do,exports.ImagePlugin=Wo,exports.ImageType=ko,exports.Input=xt,exports.InputPlugin=wt,exports.InputState=_t,exports.Interactable=uo,exports.LayoutGroupPlugin=Cr,exports.ListView=gr,exports.ListViewPlugin=_r,exports.LocalTransform=le,exports.Logger=ma,exports.LoopMode=xa,exports.Material=Ft,exports.MaterialLoader=Ht,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ve,exports.Parent=fe,exports.Particle=Za,exports.ParticleEasing=we,exports.ParticleEmitter=be,exports.ParticlePlugin=el,exports.Physics=ta,exports.PhysicsEvents=Yr,exports.PhysicsPlugin=Jr,exports.PostProcess=Tn,exports.PostProcessPlugin=$n,exports.PostProcessStack=wn,exports.PostProcessVolume=Pe,exports.PrefabServer=Ws,exports.Prefabs=zs,exports.PrefabsPlugin=$s,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(ni);t.register({name:da,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(da),this.loadPromise_=t.load(da).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 ua(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await aa({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:da})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([de]);for(const n of s){if(e.get(n,de).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([he]);for(const i of n){const n=e.get(i,he);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(ni).getScene(da),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,ae,r);const a={isActive:!0,projectionType:ie.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:oe.ColorAndDepth};e.insert(o,de,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ni);await e.switchTo(da),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=jo,exports.ProgressBarDirection=No,exports.ProgressBarPlugin=Yo,exports.ProjectionType=ie,exports.Query=nt,exports.QueryInstance=it,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=ot,exports.RenderPipeline=Qn,exports.RenderTexture=ha,exports.Renderer=Yn,exports.Res=Fe,exports.ResMut=ke,exports.RigidBody=Me,exports.RuntimeConfig=O,exports.SafeArea=hr,exports.SafeAreaPlugin=fr,exports.ScaleMode=re,exports.SceneManager=ni,exports.SceneManagerState=si,exports.SceneOwner=Se,exports.ScrollView=Zo,exports.ScrollViewPlugin=sr,exports.ShaderSources=$t,exports.SimulationSpace=xe,exports.Slider=or,exports.SliderDirection=ir,exports.SliderPlugin=lr,exports.SpineAnimation=ye,exports.Sprite=ue,exports.SpriteAnimator=Yt,exports.Stats=cl,exports.StatsCollector=dl,exports.StatsOverlay=al,exports.StatsPlugin=hl,exports.Storage=We,exports.SystemRunner=yt,exports.Text=Yi,exports.TextAlign=Ni,exports.TextInput=Co,exports.TextInputPlugin=Io,exports.TextOverflow=Xi,exports.TextPlugin=Ki,exports.TextRenderer=Gi,exports.TextVerticalAlign=ji,exports.Tilemap=as,exports.TilemapAPI=rs,exports.TilemapLayer=ls,exports.TilemapPlugin=nl,exports.Time=De,exports.Toggle=$o,exports.TogglePlugin=Ho,exports.Transform=ae,exports.Tween=Wa,exports.TweenHandle=Ia,exports.TweenState=_a,exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UICameraInfo=vt,exports.UIEventQueue=mo,exports.UIEvents=go,exports.UIInteraction=ho,exports.UIInteractionPlugin=Mo,exports.UILayoutPlugin=yo,exports.UIMask=eo,exports.UIMaskPlugin=lo,exports.UIRect=Pi,exports.UIRenderOrderPlugin=Ar,exports.Velocity=pe,exports.WeChatAssetProvider=xl,exports.WebAssetProvider=ua,exports.World=Je,exports.WorldTransform=ce,exports.addStartupSystem=function(e){gt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){gt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){gt().push({schedule:e,system:t})},exports.animationPlugin=$a,exports.applyBuildRuntimeConfig=V,exports.applyDirectionalFill=Ai,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=O.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=O.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=O.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=O.canvasMatchWidthOrHeight)},exports.assetPlugin=Fs,exports.audioPlugin=Ga,exports.calculateAttenuation=Va,exports.calculatePanning=Na,exports.cleanupAllPostProcessVolumes=kn,exports.cleanupPostProcessVolume=Fn,exports.clearAnimClips=function(){jt.clear()},exports.clearDrawCallbacks=on,exports.clearTextureDimensionsCache=es,exports.clearTilemapSourceCache=function(){Jt.clear()},exports.clearUserComponents=function(){const e=q();for(const t of e.keys())ee.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Ei,exports.computeFillSize=function(e,t,s,n){switch(e){case vi.BottomToTop:case vi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case vi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case vi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case vi.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=Si,exports.createMaskProcessor=ao,exports.createRuntimeSceneConfig=la,exports.createWebApp=_l,exports.debug=function(e,t,s){ga.debug(e,t,s)},exports.defaultFrameStats=ll,exports.defineComponent=K,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Ie,exports.defineSystem=mt,exports.defineTag=function(e){const t=ee.get(e)??q().get(e);if(t)return t;const s=G(e,{});return q().set(e,s),ee.set(e,s),Q(e,{},!0),s},exports.dragPlugin=Qo,exports.dropdownPlugin=vr,exports.error=function(e,t,s){ga.error(e,t,s)},exports.extractAnimClipTexturePaths=Vt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ve]);for(const n of s){const s=e.get(n,ve);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=li,exports.focusPlugin=dr,exports.getAddressableType=function(e){return b(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAllEffectDefs=function(){return Array.from(Cn.values())},exports.getAnimClip=function(e){return jt.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=se,exports.getComponentAssetFieldDescriptors=_s,exports.getComponentAssetFields=ys,exports.getComponentDefaults=function(e){const t=se(e);return t?X(t._default):null},exports.getComponentEntityFields=bs,exports.getComponentSpineFieldDescriptor=xs,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=An,exports.getEffectTypes=function(){return Array.from(Cn.keys())},exports.getLogger=function(){return ga},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=Zt,exports.getTilemapSource=ss,exports.getUserComponent=J,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=zo,exports.info=function(e,t,s){ga.info(e,t,s)},exports.initDrawAPI=Ys,exports.initGLDebugAPI=qn,exports.initGeometryAPI=dn,exports.initMaterialAPI=At,exports.initParticleAPI=Ja,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(Rs);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ml(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await ml(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new fl(n);await ca({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=Sn,exports.initRendererAPI=jn,exports.initRuntime=ca,exports.initTilemapAPI=is,exports.initTweenAPI=Ba,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:wl("esengine.wasm")}),l=i.getContext("webgl2")||i.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=_l(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&V(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await bl(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await bl(e.physicsFactory,"physics.wasm"));const p=new xl(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await ca({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:i.width/i.height}),u.run()},exports.inputPlugin=bt,exports.instantiatePrefab=ks,exports.intersectRects=to,exports.invertMatrix4=so,exports.isBuiltinComponent=Z,exports.isCustomExtension=P,exports.isEditor=bo,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=vo,exports.isRuntime=function(){return!xo},exports.isTextureRef=Pt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Er,exports.listViewPlugin=xr,exports.loadComponent=Cs,exports.loadPhysicsModule=Ir,exports.loadRuntimeScene=aa,exports.loadSceneData=Ps,exports.loadSceneWithAssets=Ms,exports.loadTiledMap=function(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,ae,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,ls,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,d=-t.rotation*fs;if(e.insert(r,ae,{position:{x:c,y:u,z:0}}),e.insert(r,Me,{bodyType:Ae.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Ce,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Te,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Te,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,ae,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=ms(e,s,t,a,0,0);i.push(...n)}return i},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.parseAnimClipData=Nt,exports.parseTiledMap=async function(e,t){const s=ns;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?cs(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}},exports.parseTmjJson=hs,exports.particlePlugin=tl,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=io(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)},exports.postProcessPlugin=On,exports.prefabsPlugin=Os,exports.progressBarPlugin=Go,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Xt,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=te,exports.registerComponentAssetFields=function(e,t){gs.set(e,t)},exports.registerComponentEntityFields=function(e,t){ws.set(e,t)},exports.registerDrawCallback=sn,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Rs);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=zt,exports.registerTextureDimensions=Qt,exports.registerTilemapSource=ts,exports.remapEntityFields=vs,exports.resolveRelativePath=ps,exports.safeAreaPlugin=mr,exports.sceneManagerPlugin=ri,exports.screenToWorld=no,exports.scrollViewPlugin=nr,exports.setEditorMode=function(e){xo=e},exports.setListViewRenderer=function(e,t){if(!yr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=yr.get(e);s?s.renderer=t:yr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){ga.setMinLevel(e)},exports.setPlayMode=function(e){wo=e},exports.setWasmErrorHandler=Ve,exports.shutdownDrawAPI=Gs,exports.shutdownGLDebugAPI=Kn,exports.shutdownGeometryAPI=hn,exports.shutdownMaterialAPI=Rt,exports.shutdownParticleAPI=Qa,exports.shutdownPostProcessAPI=Pn,exports.shutdownRendererAPI=Xn,exports.shutdownTilemapAPI=os,exports.shutdownTweenAPI=La,exports.sliderPlugin=cr,exports.spriteAnimatorSystemUpdate=Gt,exports.statsPlugin=pl,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ue))return;const r=e.get(t,ue);let a,l;switch(s){case vi.BottomToTop:case vi.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ue,r))},exports.syncPostProcessVolume=function(e,t){let s=Rn.get(e),n=In.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=Tn.createStack(),Rn.set(e,s)),n||(n=new Map,In.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=An(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}Tn.bind(e,s)}else if(s&&(Tn.unbind(e),s.destroy(),Rn.delete(e)),n){for(const e of n.values())Ft.releaseShader(e);In.delete(e)}},exports.textInputPlugin=Fo,exports.textPlugin=Ji,exports.tilemapPlugin=il,exports.toBuildPath=M,exports.togglePlugin=Vo,exports.transitionTo=async function(e,t,s){const n=e.getResource(ni);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=To,exports.uiLayoutPlugin=_o,exports.uiMaskPlugin=co,exports.uiPlugins=gl,exports.uiRenderOrderPlugin=Rr,exports.unregisterAnimClip=function(e){jt.delete(e)},exports.unregisterComponent=function(e){q().delete(e),ee.delete(e)},exports.unregisterDrawCallback=nn,exports.updateCameraAspectRatio=Es,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){ga.warn(e,t,s)},exports.wrapSceneSystem=ii,exports.wxFileExists=function(e){return new Promise(t=>{C().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{C().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{C().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})};
+"use strict";let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return"wechat"===e?.name}async function n(e,s){return t().fetch(e,s)}async function i(e){return t().readFile(e)}async function o(e){return t().readTextFile(e)}async function r(e){return t().fileExists(e)}async function a(e,s){return t().instantiateWasm(e,s)}function l(e,s){return t().createCanvas(e,s)}function c(){return t().now()}function u(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class d{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof d?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class h{constructor(e,t,s){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=s}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class p{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const s=this.urlCache_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=wx.createInnerAudioContext();n.loop=t.loop??!1,n.volume=t.volume??1,n.playbackRate=t.playbackRate??1,n.startTime=t.startOffset??0,n.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,n);const o=new h(i,n,this.contexts_);return n.onEnded(()=>{o.onEnd?.(),n.loop||(n.destroy(),this.contexts_.delete(i))}),n.onError(e=>{console.error(`[WeChatAudio] Playback error for "${s}":`,e.errMsg)}),n.src=s,n.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function f(e,t){return new Promise((s,n)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function m(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const s=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(s,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${s}": ${t}`)}}const g=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],y={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},_=new Map,x=new Set;for(const e of g)for(const t of e.extensions)_.set(t,e),x.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function b(e){return _.get(w(e))}function v(e){return x.has(e.toLowerCase())}function S(){const e=[];for(const t of g)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function P(e){const t=b(e);return t?.wechatPackInclude??!1}function M(e){const t=b(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const s=e.lastIndexOf(".");return s>=0?e.substring(0,s)+".json":e}let T=null;function C(){return T||(T=wx.getFileSystemManager()),T}function E(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(P(e)){const t=e.substring(e.lastIndexOf("."));return`[ESEngine] Cannot read "${e}": WeChat blocked access to "${t}" files. Add { type: "suffix", value: "${t}" } to packOptions.include in project.config.json`}return`[ESEngine] Cannot read "${e}": permission denied. Check file is included in WeChat package`}return s.includes("no such file")||s.includes("not found")?`[ESEngine] File not found: "${e}". Ensure the asset is included in the build (referenced by a scene or added to an addressable group with export mode "always")`:`[ESEngine] Failed to read "${e}": ${t}`}function A(e){const t=C();try{return t.accessSync(e),!0}catch{return!1}}function R(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function I(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const i=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(i.data.buffer)}}async function F(e){return I(await R(e))}let k=!1;const B=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return f(e,t)}async readFile(e){return function(e){return C().readFileSync(e)}(M(e))}async readTextFile(e){return function(e,t="utf-8"){return C().readFileSync(e,t)}(M(e))}async fileExists(e){return A(M(e))}async loadImagePixels(e){return F(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return m(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const s=wx.createCanvas();return s.width=e,s.height=t,s}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t=>e.onKeyDown(t.code),n=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(s),wx.onKeyUp(n));const o=t=>{for(const s of t.touches)e.onPointerDown(s.identifier,s.clientX,s.clientY)},r=t=>{const s=t.touches[0];s&&e.onPointerMove(s.clientX,s.clientY)},a=t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(s),wx.offKeyUp(n)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new p}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch{}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch{}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const s of t)s.startsWith(e)&&wx.removeStorageSync(s)}catch{}}},L=1920,D=1080,U={x:100,y:100},W=1/60,z={x:0,y:-9.81},$=1/60,O={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};const H={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function V(e,t){if(void 0!==t.maxDeltaTime&&(O.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(O.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(O.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(O.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(O.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");O.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(O.canvasScaleMode=H[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(O.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(O.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(O.assetFailureCooldown=t.assetFailureCooldown)}const N=4294967295,j=4294967295;function X(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(X);const t={};for(const s in e)t[s]=X(e[s]);return t}let Y=0;function G(e,t){const s=++Y,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?{...X(t),...e}:X(t):e?{...t,...e}:{...t}}}function q(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ee.get(e)??q().get(e);if(s)return s;const n=G(e,t);return q().set(e,n),ee.set(e,n),Q(e,t,!1),n}function J(e){return q().get(e)}function Q(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function Z(e){return!0===e._builtin}const ee=new Map;function te(e,t){ee.set(e,t)}function se(e){return ee.get(e)??J(e)}function ne(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ee.set(e,s),s}const ie={Perspective:0,Orthographic:1},oe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},re={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ae=ne("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}}),le=ae,ce=ae,ue=ne("Sprite",{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:U.x,y:U.y},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),de=ne("Camera",{projectionType:ie.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:oe.ColorAndDepth}),he=ne("Canvas",{designResolution:{x:L,y:D},pixelsPerUnit:100,scaleMode:re.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),pe=ne("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),fe=ne("Parent",{entity:0}),me=ne("Children",{entities:[]}),ge=ne("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:j,enabled:!0}),ye=ne("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),_e={Point:0,Circle:1,Rectangle:2,Cone:3},xe={World:0,Local:1},we={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},be=ne("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:_e.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:we.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:we.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:N,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:xe.World,enabled:!0}),ve=K("Name",{value:""}),Se=K("SceneOwner",{scene:"",persistent:!1}),Pe=K("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});const Me=ne("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Te=ne("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ce=ne("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ee=ne("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),Ae={Static:0,Kinematic:1,Dynamic:2};let Re=0;function Ie(e,t){const s=++Re;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Fe(e){return{_type:"res",_resource:e}}function ke(e){return{_type:"res_mut",_resource:e}}class Be{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 Le{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 Be(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const De=Ie({delta:0,elapsed:0,frameCount:0},"Time"),Ue="esengine:",We={getString(e,s){const n=t().getStorageItem(Ue+e);return null!==n?n:s},setString(e,s){t().setStorageItem(Ue+e,s)},getNumber(e,s){const n=t().getStorageItem(Ue+e);if(null===n)return s;const i=Number(n);return Number.isNaN(i)?s:i},setNumber(e,s){t().setStorageItem(Ue+e,String(s))},getBoolean(e,s){const n=t().getStorageItem(Ue+e);return null===n?s:"true"===n},setBoolean(e,s){t().setStorageItem(Ue+e,String(s))},getJSON(e,s){const n=t().getStorageItem(Ue+e);if(null===n)return s;try{return JSON.parse(n)}catch{return s}},setJSON(e,s){t().setStorageItem(Ue+e,JSON.stringify(s))},remove(e){t().removeStorageItem(Ue+e)},has:e=>null!==t().getStorageItem(Ue+e),clear(){t().clearStorage(Ue)}};function ze(e,t,s){const n=[];for(const[e,i]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:i});continue}const s=$e(t[e]),o=$e(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Oe(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 He=null;function Ve(e){He=e}function Ne(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),He&&He(e,t)}function je(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 Xe=1;const Ye=new WeakMap;function Ge(e){let t=Ye.get(e);return void 0===t&&(t=Xe++,Ye.set(e,t)),t}const qe=[];function Ke(e,t=[],s=[]){qe.length=0;for(const t of e)qe.push(Ge(t));qe.sort((e,t)=>e-t);let n=qe.join(",");if(t.length>0){qe.length=0;for(const e of t)qe.push(Ge(e));qe.sort((e,t)=>e-t),n+="|+"+qe.join(",")}if(s.length>0){qe.length=0;for(const e of s)qe.push(Ge(e));qe.sort((e,t)=>e-t),n+="|-"+qe.join(",")}return n}class Je{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ne(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ne(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const s of t){this.tsStorage_.get(s)?.delete(e),this.componentAddedTicks_.get(s)?.delete(e),this.componentChangedTicks_.get(s)?.delete(e);let t=this.componentRemovedBuffer_.get(s);t||(t=[],this.componentRemovedBuffer_.set(s,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Ne(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ne(t,`removeParent(entity=${e})`)}}insert(e,t,s){return Z(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(Z(t)){if(this.cppRegistry_)try{const n=t._default,i=s;let o=i;for(const e of Object.keys(i))e in n||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,je(o))}catch(s){Ne(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 Z(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return Z(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(Z(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Ne(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.");Z(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const s=this.cppRegistry_,n=s[`add${e}`],i=s[`get${e}`],o=s[`has${e}`],r=s[`remove${e}`];if("function"!=typeof n||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:n.bind(s),get:i.bind(s),has:o.bind(s),remove:r.bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n=t._default,i={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&e in n&&(i[e]=t);const e=ze(t._name,n,i);if(e.length>0)throw new Error(Oe(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const s=this.getBuiltinMethods(t._cppName);r=!s.has(e),s.add(e,je(o))}catch(s){Ne(s,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let s=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[n];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){s=!0;break}}}if(!s)return e;const n={};for(const s of Object.keys(e)){const i=e[s],o=t[s];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))n[s]=i;else{const e=i,t=o;n[s]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return n}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(s){return Ne(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 Ne(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Ne(s,`removeBuiltin(${t._name}, entity=${e})`)}this.recordRemovedTick_(t,e),this.worldVersion_++}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const i=ze(t._name,t._default,e);if(i.length>0)throw new Error(Oe(t._name,i));n=e}const i=t.create(n),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const n=this.entityComponents_.get(e);if(n){const e=n.indexOf(t._id);-1!==e&&n.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.add(s)}catch{}if(this.cppRegistry_)for(const[s,n]of ee)if(Z(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=q();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??Ke(e,t,s),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!Z(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<a&&(a=s,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const n of c){let i=!0;for(const t of e)if(!this.has(n,t)){i=!1;break}if(i)for(const e of t)if(!this.has(n,e)){i=!1;break}if(i)for(const e of s)if(this.has(n,e)){i=!1;break}i&&l.push(n)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,s){const n=this.componentAddedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}isChangedSince(e,t,s){const n=this.componentChangedTicks_.get(t._id);if(!n)return!1;const i=n.get(e);return void 0!==i&&i>s}getRemovedEntitiesSince(e,t){const s=this.componentRemovedBuffer_.get(e._id);if(!s)return[];const n=[];for(const e of s)e.tick>t&&n.push(e.entity);return n}cleanRemovedBuffer(e){for(const[t,s]of this.componentRemovedBuffer_){let n=0;for(let t=0;t<s.length;t++)s[t].tick>=e&&(s[n++]=s[t]);s.length=n,0===n&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let s=this.componentAddedTicks_.get(e._id);s||(s=new Map,this.componentAddedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordChangedTick_(e,t){let s=this.componentChangedTicks_.get(e._id);s||(s=new Map,this.componentChangedTicks_.set(e._id,s)),s.set(t,this.worldTick_)}recordRemovedTick_(e,t){let s=this.componentRemovedBuffer_.get(e._id);s||(s=[],this.componentRemovedBuffer_.set(e._id,s)),s.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function Qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ze(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function et(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function tt(e){return Qe(e)||Ze(e)||et(e)?e._component:e}function st(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{Qe(e)&&n.push(t),Ze(e)?i.push({index:t,component:e._component}):et(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>st(e,[...t,...n],s),without:(...n)=>st(e,t,[...s,...n])}}function nt(...e){return st(e)}class it{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(tt),this.allRequired_=this.actualComponents_.concat(t._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=t._mutIndices.map(e=>({component:this.actualComponents_[e],data:null})),this.cacheKey_=Ke(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:s}=this.descriptor_;if(0===t.length&&0===s.length)return!0;const n=this.lastRunTick_;for(const s of t)if(!this.world_.isAddedSince(e,s.component,n))return!1;for(const t of s)if(!this.world_.isChangedSince(e,t.component,n))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,s=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),n=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of s)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<n;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...s]of this)e(t,...s)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class ot{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 rt{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=Z(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 at{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new rt(this,null);return this.spawned_.push(e),e}entity(e){return new rt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}class lt{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 ct{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new lt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new lt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}class ut{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 pt(){return{_type:"get_world"}}exports.Schedule=void 0,(ht=exports.Schedule||(exports.Schedule={}))[ht.Startup=0]="Startup",ht[ht.First=1]="First",ht[ht.PreUpdate=2]="PreUpdate",ht[ht.Update=3]="Update",ht[ht.PostUpdate=4]="PostUpdate",ht[ht.Last=5]="Last",ht[ht.FixedPreUpdate=10]="FixedPreUpdate",ht[ht.FixedUpdate=11]="FixedUpdate",ht[ht.FixedPostUpdate=12]="FixedPostUpdate";let ft=0;function mt(e,t,s){const n=++ft;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function gt(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}class yt{constructor(e,t,s){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=s??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);const s=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof at&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-s),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new it(this.world_,e,this.currentLastRunTick_);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new at(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 ut(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new dt(s)}case"removed":{const t=e;return new ot(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class _t{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=Ie(new _t,"Input");class wt{constructor(e){this.target_=e??null}build(e){const s=new _t;e.insertResource(xt,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,mt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const bt=new wt,vt=Ie({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 St;function Pt(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(St=exports.BlendMode||(exports.BlendMode={}))[St.Normal=0]="Normal",St[St.Additive=1]="Additive",St[St.Multiply=2]="Multiply",St[St.Screen=3]="Screen",St[St.PremultipliedAlpha=4]="PremultipliedAlpha";let Mt=null,Tt=null,Ct=1;const Et=new Map;function At(e){Mt=e,Tt=e.getResourceManager(),zt()}function Rt(){0!==Bt&&Mt&&(Mt._free(Bt),Bt=0),Et.clear(),Ct=1,kt=!1,Dt.clear(),Ut=null,Tt=null,Mt=null}function It(){if(!Tt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Tt}const Ft={createShader:(e,t)=>It().createShader(e,t),releaseShader(e){e>0&&It().releaseShader(e)},create(e){const t=Ct++,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 Et.set(t,s),t},get:e=>Et.get(e),setUniform(e,t,s){const n=Et.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Mt?.invalidateMaterialCache(e))},getUniform(e,t){const s=Et.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Et.get(e);s&&(s.blendMode=t,Mt?.invalidateMaterialCache(e))},getBlendMode(e){const t=Et.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Et.get(e);s&&(s.depthTest=t,Mt?.invalidateMaterialCache(e))},getShader(e){const t=Et.get(e);return t?.shader??0},release(e){Et.delete(e),Mt?.invalidateMaterialCache(e)},isValid:e=>Et.has(e),releaseAll(){Et.clear(),Mt?.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=Et.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ct++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Et.set(s,n),s},toAssetData(e,t){const s=Et.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=Et.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let kt=!1,Bt=0;const Lt=16384,Dt=new Map;let Ut=null;function Wt(e){const t=(0===Bt&&Mt&&(Bt=Mt._malloc(Lt)),Bt);if(0===t||!Mt)return{ptr:0,count:0};let s=0,n=0;const i=Mt.HEAPU8,o=Mt.HEAPU32,r=Mt.HEAPF32;for(const[a,l]of e){if(Pt(l))continue;let e=Dt.get(a);e||(Ut||(Ut=new TextEncoder),e=Ut.encode(a),Dt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Lt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Lt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function zt(){if(!Mt||kt)return;Mt.materialDataProvider=(e,t,s,n,i)=>{const o=Et.get(e);if(!o)return Mt.HEAPU32[t>>2]=0,Mt.HEAPU32[s>>2]=0,Mt.HEAPU32[n>>2]=0,void(Mt.HEAPU32[i>>2]=0);Mt.HEAPU32[t>>2]=o.shader,Mt.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Wt(o.uniforms);Mt.HEAPU32[n>>2]=r,Mt.HEAPU32[i>>2]=a},kt=!0}const $t={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class Ot{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,s=O.assetLoadTimeout){const n=this.cache_.get(e);if(void 0!==n)return n;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.promise;const r={promise:null,aborted:!1};r.promise=(async()=>{const n=t(),i=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{r.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);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&&(this.failed_.set(e,{error:t,expiry:Date.now()+O.assetFailureCooldown}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Ht{constructor(e,t=""){this.cache_=new Ot,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 r(t))throw new Error(`Material file not found: ${t}`);const s=await o(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),a=await this.shaderLoader_.load(i);return{handle:Ft.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function Vt(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function Nt(e,t,s){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:s.get(e.texture)??0};if(e.atlasFrame){const s=e.atlasFrame;t.uvOffset={x:s.x/s.pageWidth,y:1-(s.y+s.height)/s.pageHeight},t.uvScale={x:s.width/s.pageWidth,y:s.height/s.pageHeight}}return t})}}const jt=new Map;function Xt(e){jt.set(e.name,e)}const Yt=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Gt(e,t){const s=e.getEntitiesWithComponents([Yt]);for(const n of s){const s=e.get(n,Yt);if(!s.enabled||!s.playing||!s.clip)continue;const i=jt.get(s.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*s.speed),r=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let a=r;if(s.frameTimer>=o&&(s.frameTimer-=o,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),a=!0),a&&e.has(n,ue)){const t=i.frames[s.currentFrame],o=e.get(n,ue);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,ue,o)}a&&e.insert(n,Yt,s)}}class qt{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const s=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,s)}static playSFX(e,t){const s={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},n=this.bufferCache_.get(e);if(!n){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const n=this.bufferCache_.get(e);n&&t.resolve(this.backend_.play(n,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(n,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,n=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,n):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:s,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,s)},n=this.bufferCache_.get(e);n?s(n):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&s(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const s=this.mixer_?.getBus(e);s&&(s.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,s){e.setVolume(0);const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,s){const n=performance.now(),i=()=>{const o=(performance.now()-n)/1e3,r=Math.min(o/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}qt.mixer_=null,qt.bufferCache_=new Map,qt.bgmHandle_=null,qt.bgmVolume_=1,qt.fadeAnimId_=0,qt.disposed_=!1;const Kt=new Map,Jt=new Map;function Qt(e,t,s){Kt.set(e,{width:t,height:s})}function Zt(e){return Kt.get(e)}function es(){Kt.clear()}function ts(e,t){Jt.set(e,t)}function ss(e){return Jt.get(e)}let ns=null;function is(e){ns=e}function os(){ns=null}const rs={initLayer(e,t,s,n,i){ns?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){ns?.tilemap_destroyLayer(e)},setTile(e,t,s,n){ns?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>ns?ns.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){ns?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!ns)return;const s=t.byteLength,n=ns._malloc(s);new Uint16Array(ns.HEAPU8.buffer,n,t.length).set(t),ns.tilemap_setTiles(e,n,t.length),ns._free(n)},hasLayer:e=>!!ns&&ns.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x){ns?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,d,h,p,f,m,g,y,_,x)}},as=K("Tilemap",{source:""}),ls=K("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function cs(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function us(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function ds(e,t){if(0===e)return 0;let s=0;2147483648&e&&(s|=8192),1073741824&e&&(s|=16384),536870912&e&&(s|=32768);return(536870911&e)-t+1|s}function hs(e){const t=e.width,s=e.height,n=e.tilewidth??0,i=e.tileheight??0;if(!(t&&s&&n&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??n,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const n=e.width??t,i=e.height??s,o=!1!==e.visible,r=e.data,l=new Uint16Array(n*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ds(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=us(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,p="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:p})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const s=[];for(const e of t){const t=new Map,n=e.properties;if(n)for(const e of n)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}s.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:s})}if(o)for(const e of o){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const n of s)"collision"===n.name&&!0===n.value&&d.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function ps(e,t){const s=e.lastIndexOf("/"),n=((s>=0?e.substring(0,s+1):"")+t).split("/"),i=[];for(const e of n)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}const fs=Math.PI/180;function ms(e,t,s,n,i,o){const r=function(e,t,s,n){const i=new Uint8Array(t*s),o=[],r=(o,r)=>{if(o>=t||r>=s)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&n.has(l)};for(let e=0;e<s;e++)for(let n=0;n<t;n++){if(!r(n,e))continue;let a=1;for(;r(n+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<a;e++)if(!r(n+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let o=0;o<a;o++)i[(e+s)*t+(n+o)]=1;o.push({col:n,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,n),a=[],l=s.tileWidth,c=s.tileHeight,u=s.height*c;for(const t of r){const s=t.width*l,n=t.height*c,r=i+t.col*l+.5*s,d=o+(u-t.row*c)-.5*n,h=e.spawn();e.insert(h,ae,{position:{x:r,y:d,z:0}}),e.insert(h,Me,{bodyType:Ae.Static}),e.insert(h,Te,{halfExtents:{x:.5*s,y:.5*n}}),a.push(h)}return a}const gs=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function ys(e){const t=gs.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function _s(e){return gs.get(e)?.fields??[]}function xs(e){return gs.get(e)?.spine??null}const ws=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function bs(e){return ws.get(e)}function vs(e,t){const s=ws.get(e.type);if(!s)return;const n=e.data;for(const i of s){const s=n[i];if("number"==typeof s&&0!==s){const o=t.get(s);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${s} which does not exist`),n[i]=void 0!==o?o:0}}}function Ss(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,ve,{value:n.name})}for(const n of t.entities){if(!1===n.visible)continue;const t=s.get(n.id);for(const i of n.components)vs(i,s),Cs(e,t,i,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),i=s.get(n.parent);void 0!==t&&void 0!==i&&e.setParent(t,i)}return s}function Ps(e,t){return Ss(e,t)}async function Ms(e,t,s){const n=s?.assetServer,i=s?.assetBaseUrl??n?.baseUrl,o=new Map;n&&await async function(e,t,s,n,i){const o=new Map;for(const e of Ts.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=gs.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...Ts.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,s,n);l.set(e,r)}),u=r.map(async e=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)});if(await Promise.all([...c,...u]),i){for(const e of n.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=gs.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const n=s[e.field];if("string"!=typeof n||!n)continue;const i=t.get(n);void 0!==i&&(s[e.field]=i)}}}(t,n,i,o,s?.collectAssets);const r=Ss(e,t);if(n&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&n.setTextureMetadataByPath(t,s.sliceBorder)}return r}const Ts=new Map([["texture",{async load(e,t,s,n){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),n.set(e,o),Qt(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,s);n.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["font",{async load(e,t,s){const n=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,s);n.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["anim-clip",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=Vt(i),r=new Map,a=o.map(async e=>{try{const i=s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),n.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);Xt(Nt(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,s){const n=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await qt.preloadAll(n).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,n){const i=[...e].map(async e=>{try{const i=hs(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=ps(e,r.image);let a=0;try{const e=s?`${s}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,n.set(i,e),Qt(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}ts(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Cs(e,t,s,n){if("LocalTransform"!==s.type&&"WorldTransform"!==s.type||(s.type="Transform"),"UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===s.type){const e=s.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=se(s.type);if(i)e.insert(t,i,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function Es(e,t){const s=e.getEntitiesWithComponents([de]);for(const n of s){const s=e.get(n,de);s&&(s.aspectRatio=t,e.insert(n,de,s))}}class As{constructor(e){this.textureCache_=new Ot,this.shaderCache_=new Ot,this.jsonCache_=new Ot,this.textCache_=new Ot,this.binaryCache_=new Ot,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Ot,this.prefabCache_=new Ot,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=l(O.textCanvasSize,O.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 Ht(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),i=this.textureCache_.get(n);if(!i)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),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 s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const i=this.resolveUrl(t,s),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),l.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,s),u="binary"===b(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),i=l.find(e=>e.name===s);if(i){const s=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,i.info.width,i.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=b(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const i=s?`${s}/${n}`:n;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${n}`:n,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,async()=>{const e=await this.fetchJson(s);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const s of e.entities){for(const e of s.components){if(!e.data)continue;for(const s of ys(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=xs(e.type);if(s)for(const n of[s.skeletonField,s.atlasField]){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}}if(s.nestedPrefab?.prefabPath){const e=t(s.nestedPrefab.prefabPath);e&&(s.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Ms(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const i=n.metadata?.atlas;i&&s.push(this.loadSpine(n.path,i).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.loadImageFromSrc(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((s,n)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(i)},i.onerror=()=>n(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:s,height:n}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:l,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.getEmbedded(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:i}=this.parseEsShader(t);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return Ft.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await r(t))throw new Error(`Shader file not found: ${e}`);const n=await o(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:a}=this.parseEsShader(n);if(!i||!a)throw new Error(`Invalid shader format: ${e}`);return Ft.createShader(i,a)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(M(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await o(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return o(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.getEmbedded(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return i(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await n(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let i="";for(const e of n){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Rs=Ie(null,"Assets");class Is{build(e){const t=e.wasmModule;t?e.insertResource(Rs,new As(t)):console.warn("AssetPlugin: No WASM module available")}}const Fs=new Is;async function ks(e,t,s){const{entities:n,rootId:i}=await Ls(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Ms(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=r.get(i);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:r}}const Bs=10;async function Ls(e,t,s,n,i,o=0){if(o>Bs)throw new Error(`Prefab nesting depth exceeded ${Bs}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(i?.has(n.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${n.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await Ls(e,n.nestedPrefab.overrides,s,a,i,o+1);r.set(n.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==n.parent?r.get(n.parent)??null:null),l.push(...t.entities);continue}const c=r.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?r.get(n.parent)??null:null,children:n.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Ds(d.components,r),Us(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Ds(e,t){for(const s of e){const e=bs(s.type);if(e)for(const n of e){const e=s.data[n];if("number"==typeof e&&0!==e){const i=t.get(e);void 0!==i&&(s.data[n]=i)}}}}function Us(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 Ws{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,i=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ks(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const zs=Ie(null,"Prefabs");class $s{constructor(){this.name="PrefabsPlugin",this.dependencies=[Rs]}build(e){const t=e.getResource(Rs);e.insertResource(zs,new Ws(e.world,t))}}const Os=new $s;let Hs=null,Vs=0,Ns=0,js=0;const Xs=new Float32Array(256);function Ys(e){Hs=e,Vs=Hs._malloc(64),Ns=Hs._malloc(64),js=Hs._malloc(1024)}function Gs(){Hs&&(Vs&&(Hs._free(Vs),Vs=0),Ns&&(Hs._free(Ns),Ns=0),js&&(Hs._free(js),js=0)),Hs=null}function qs(){if(!Hs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Hs}const Ks={r:1,g:1,b:1,a:1},Js={begin(e){const t=qs();try{t.HEAPF32.set(e,Vs/4),t.draw_begin(Vs)}catch(e){Ne(e,"Draw.begin")}},end(){try{qs().draw_end()}catch(e){Ne(e,"Draw.end")}},line(e,t,s,n=1){try{qs().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.line")}},rect(e,t,s,n=!0){try{qs().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{qs().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Ne(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{qs().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{qs().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){Ne(e,"Draw.circleOutline")}},texture(e,t,s,n=Ks){try{qs().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Ne(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Ks){try{qs().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){Ne(e,"Draw.textureRotated")}},setLayer(e){qs().draw_setLayer(e)},setDepth(e){qs().draw_setDepth(e)},getDrawCallCount:()=>Hs?Hs.draw_getDrawCallCount():0,getPrimitiveCount:()=>Hs?Hs.draw_getPrimitiveCount():0,setBlendMode(e){qs().draw_setBlendMode(e)},setDepthTest(e){qs().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=qs();n.HEAPF32.set(s,Ns/4),n.draw_mesh(e,t,Ns)}catch(s){Ne(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=qs(),i=Ft.get(t);if(!i)return;if(Js.setBlendMode(i.blendMode),Js.setDepthTest(i.depthTest),0===i.uniforms.size)return void Js.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Ns/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=en(t);if(!(n<0)){if(Pt(s))Xs[o++]=10,Xs[o++]=n,Xs[o++]=s.slot??e++,Xs[o++]=s.textureId;else if("number"==typeof s)Xs[o++]=1,Xs[o++]=n,Xs[o++]=s;else if(Array.isArray(s)){Xs[o++]=s.length,Xs[o++]=n;for(let e=0;e<s.length;e++)Xs[o++]=s[e]}else"w"in s?(Xs[o++]=4,Xs[o++]=n,Xs[o++]=s.x,Xs[o++]=s.y,Xs[o++]=s.z,Xs[o++]=s.w):"z"in s?(Xs[o++]=3,Xs[o++]=n,Xs[o++]=s.x,Xs[o++]=s.y,Xs[o++]=s.z):(Xs[o++]=2,Xs[o++]=n,Xs[o++]=s.x,Xs[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(Xs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Ns);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),js/4),n.draw_meshWithUniforms(e,i.shader,Ns,js,o)}catch(s){Ne(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Qs={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},Zs=new Set;function en(e){const t=Qs[e];return void 0!==t?t:(Zs.has(e)||(Zs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Qs).join(", ")}`)),-1)}const tn=new Map;function sn(e,t,s){tn.set(e,{fn:t,scene:s??""})}function nn(e){tn.delete(e)}function on(){tn.clear()}var rn;exports.DataType=void 0,(rn=exports.DataType||(exports.DataType={}))[rn.Float=1]="Float",rn[rn.Float2=2]="Float2",rn[rn.Float3=3]="Float3",rn[rn.Float4=4]="Float4",rn[rn.Int=5]="Int",rn[rn.Int2=6]="Int2",rn[rn.Int3=7]="Int3",rn[rn.Int4=8]="Int4";let an=null,ln=0,cn=0,un=0;function dn(e){an=e,ln=an._malloc(262144),cn=an._malloc(65536),un=an._malloc(256)}function hn(){an&&(ln&&an._free(ln),cn&&an._free(cn),un&&an._free(un),ln=0,cn=0,un=0),an=null}function pn(){if(!an)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return an}const fn={create(e){const t=pn(),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,ln/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,un,i).set(o),t.geometry_init(s,ln,n,un,i,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,cn,n).set(e.indices),t.geometry_setIndices16(s,cn,n)}else{new Uint32Array(t.HEAPU8.buffer,cn,n).set(e.indices),t.geometry_setIndices32(s,cn,n)}}return s},updateVertices(e,t,s=0){const n=pn(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,ln/4),n.geometry_updateVertices(e,ln,i,s)},release(e){e>0&&pn().geometry_release(e)},isValid:e=>!(!an||e<=0)&&an.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return fn.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const i=n/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;s.push(o,r,a,l)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return fn.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(n-t),a=(r.y-s)/(i-s);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return fn.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(r)})}};let mn=1;const gn=new Map,yn=new Map;function _n(){return gn}function xn(){return yn}class wn{constructor(){this.passes_=[],this.destroyed_=!1,this.id=mn++,gn.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const s=this.passes_.find(t=>t.name===e);return s&&(s.enabled=t),this}setUniform(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.floatUniforms.set(t,s),this}setUniformVec4(e,t,s){const n=this.passes_.find(t=>t.name===e);return n&&n.vec4Uniforms.set(t,{...s}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of yn)t===this&&yn.delete(e);gn.delete(this.id)}}}const bn="#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";let vn=null;function Sn(e){vn=e}function Pn(){for(const e of _n().values())e.destroy();_n().clear(),xn().clear(),vn&&Tn.isInitialized()&&Tn.shutdown(),vn=null}function Mn(){if(!vn)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vn}const Tn={createStack:()=>new wn,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");xn().set(e,t)},unbind(e){xn().delete(e)},getStack:e=>xn().get(e)??null,init(e,t){try{return Mn().postprocess_init(e,t)}catch(s){return Ne(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Mn().postprocess_shutdown()}catch(e){Ne(e,"PostProcess.shutdown")}},resize(e,t){try{Mn().postprocess_resize(e,t)}catch(s){Ne(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!vn)return!1;try{return vn.postprocess_isInitialized()}catch(e){return Ne(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Mn().postprocess_setBypass(e)}catch(e){Ne(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{Mn().postprocess_setOutputViewport(e,t,s,n)}catch(e){Ne(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=xn().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Tn.isInitialized()||Tn.init(1,1),Tn.setBypass(!1),function(e){const t=Mn();try{t.postprocess_clearPasses()}catch(e){return void Ne(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):Tn.setBypass(!0)},_resetAfterCamera(){try{Mn().postprocess_clearPasses(),Mn().postprocess_setBypass(!0)}catch(e){Ne(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of xn().keys())e(t)||xn().delete(t)},screenStack:null,setScreenStack(e){Tn.screenStack=e},_beginScreenCapture(){try{Mn().postprocess_beginScreenCapture()}catch(e){Ne(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Mn().postprocess_endScreenCapture()}catch(e){Ne(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Tn.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Mn();try{t.postprocess_clearScreenPasses()}catch(e){return void Ne(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){Ne(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniform("${s.name}", "${e}")`)}for(const[e,n]of s.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(s.name,e,n.x,n.y,n.z,n.w)}catch(t){Ne(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{Mn().postprocess_executeScreenPasses()}catch(e){Ne(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Ft.createShader(bn,"#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(bn,"#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(bn,"#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"),createBloom:()=>Ft.createShader(bn,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Ft.createShader(bn,"#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")},Cn=new Map;function En(e){Cn.set(e.type,e)}function An(e){return Cn.get(e)}En({type:"blur",label:"Blur",factory:()=>Tn.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),En({type:"bloom",label:"Bloom",factory:()=>Tn.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),En({type:"vignette",label:"Vignette",factory:()=>Tn.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),En({type:"grayscale",label:"Grayscale",factory:()=>Tn.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),En({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Tn.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Rn=new Map,In=new Map;function Fn(e){const t=Rn.get(e);t&&(Tn.unbind(e),t.destroy(),Rn.delete(e));const s=In.get(e);if(s){for(const e of s.values())Ft.releaseShader(e);In.delete(e)}}function kn(){for(const e of Rn.keys())Fn(e)}const Bn=Ie({enabled:!0},"PostProcessVolumeConfig"),Ln=new Map,Dn=new Map;function Un(e){const t=Dn.get(e);if(void 0!==t)return t;const s=An(e);if(!s)return null;const n=s.factory();return Dn.set(e,n),n}function Wn(e,t){if(0===t.size){const t=Ln.get(e);return void(t&&(Tn.unbind(e),t.destroy(),Ln.delete(e)))}let s=Ln.get(e);for(s||(s=Tn.createStack(),Ln.set(e,s));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const[e,n]of t){if(!n.enabled)continue;const t=Un(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?Tn.bind(e,s):Tn.unbind(e)}const zn=mt([nt(Pe,ae)],e=>{const t=[];for(const[s,n,i]of e)t.push({data:n,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const s=[];for(const{data:e,tx:n}of t)e.isGlobal&&s.push({data:e,factor:1});if(s.length>0){const e=function(e){const t=new Map,s=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:n}of s)if(!(n<=0))for(const s of e.effects){if(!s.enabled)continue;const e=t.get(s.type);if(e)for(const[t,i]of Object.entries(s.uniforms)){const s=e.uniforms.get(t)??0;e.uniforms.set(t,s+(i-s)*n)}else{const e=new Map;for(const[t,i]of Object.entries(s.uniforms))e.set(t,i*n);t.set(s.type,{enabled:!0,uniforms:e})}}return t}(s);for(const[t]of Ln)Wn(t,e)}},{name:"PostProcessVolumeSystem"});class $n{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Bn,{enabled:!0}),e.addSystemToSchedule(exports.Schedule.PostUpdate,zn)}cleanup(){kn(),function(){for(const[e,t]of Ln)Tn.unbind(e),t.destroy();Ln.clear();for(const e of Dn.values())Ft.releaseShader(e);Dn.clear()}(),Tn.setScreenStack(null)}}const On=new $n;var Hn;exports.RenderStage=void 0,(Hn=exports.RenderStage||(exports.RenderStage={}))[Hn.Background=0]="Background",Hn[Hn.Opaque=1]="Opaque",Hn[Hn.Transparent=2]="Transparent",Hn[Hn.Overlay=3]="Overlay";let Vn=null,Nn=0;function jn(e){Vn=e,Nn=Vn._malloc(64)}function Xn(){Vn&&Nn&&(Vn._free(Nn),Nn=0),Vn=null}const Yn={init(e,t){Vn?.renderer_init(e,t)},resize(e,t){Vn?.renderer_resize(e,t)},begin(e,t){if(Vn&&Nn)try{Vn.HEAPF32.set(e,Nn/4),Vn.renderer_begin(Nn,t??0)}catch(e){Ne(e,"Renderer.begin")}},flush(){try{Vn?.renderer_flush()}catch(e){Ne(e,"Renderer.flush")}},end(){try{Vn?.renderer_end()}catch(e){Ne(e,"Renderer.end")}},submitSprites(e){if(Vn)try{Vn.renderer_submitSprites(e._cpp)}catch(e){Ne(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Vn)try{Vn.renderer_submitBitmapText(e._cpp)}catch(e){Ne(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Vn)try{Vn.renderer_submitSpine?.(e._cpp)}catch(e){Ne(e,"Renderer.submitSpine")}},submitParticles(e){if(Vn)try{Vn.renderer_submitParticles?.(e._cpp)}catch(e){Ne(e,"Renderer.submitParticles")}},setStage(e){Vn?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Vn?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Vn?.renderer_releaseTarget(e)},getTargetTexture:e=>Vn?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Vn?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Vn?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Vn?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Vn?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Vn?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Vn?Vn.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Vn?{drawCalls:Vn.renderer_getDrawCalls(),triangles:Vn.renderer_getTriangles(),sprites:Vn.renderer_getSprites(),text:Vn.renderer_getText(),spine:Vn.renderer_getSpine?.()??0,meshes:Vn.renderer_getMeshes(),culled:Vn.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Gn=null;function qn(e){Gn=e}function Kn(){Gn=null}const Jn={enable(){Gn?.gl_enableErrorCheck(!0)},disable(){Gn?.gl_enableErrorCheck(!1)},check:e=>Gn?.gl_checkErrors(e)??0,diagnose(){Gn?.renderer_diagnose()}};class Qn{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Tn.screenStack&&Tn.screenStack.enabledPassCount>0&&(Tn.isInitialized()||Tn.init(1,1),Tn._applyScreenStack(),Tn._beginScreenCapture())}endScreenCapture(){Tn.screenStack&&Tn.screenStack.enabledPassCount>0&&(Tn._endScreenCapture(),Tn._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Yn.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Yn.setViewport(0,0,n,i),Yn.clearBuffers(3),Yn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Yn.submitSprites(t),Yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Yn.submitSpine(t),Yn.submitParticles(t),Yn.flush(),this.executeDrawCallbacks(s,o),Yn.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Tn.getStack(r);a&&(Tn._applyForCamera(r),Tn.resize(n.w,n.h),Tn.setOutputViewport(n.x,n.y,n.w,n.h)),Yn.setViewport(n.x,n.y,n.w,n.h),Yn.setScissor(n.x,n.y,n.w,n.h,!0),Yn.clearBuffers(i),Yn.setScissor(0,0,0,0,!1),Yn.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Yn.submitSprites(t),Yn.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Yn.submitSpine(t),Yn.submitParticles(t),Yn.flush(),this.executeDrawCallbacks(s,o),Yn.end(),a&&Tn._resetAfterCamera()}executeDrawCallbacks(e,t){const s=tn;if(s.size>0){Js.begin(e);const n=[];for(const[e,i]of s.entries())if(!i.scene||!this.activeScenes_||this.activeScenes_.has(i.scene))try{i.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}Js.end();for(const e of n)nn(e)}}}const Zn="__scene_transition_overlay__";class ei{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class ti{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Se,{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),sn(e,t,this.instance_.config.name)}bindPostProcess(e,t){Tn.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Tn.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);s.persistent=t,this.app_.world.insert(e,Se,s)}}}class si{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.switching_=!1,this.loadPromises_=new Map,this.app_=e}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())nn(t);for(const t of e.postProcessBindings.keys())Tn.unbind(t)}this.transition_&&(nn(Zn),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??O.sceneTransitionDuration,i=t.color??{...O.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},sn(Zn,()=>{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;Js.setLayer(9999),Js.setDepth(9999),Js.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{try{s&&s!==e&&await this.unload(s,t),await this.load(e)}catch(e){console.error("Scene transition failed:",e);const{resolve:t}=this.transition_;this.transition_=null,nn(Zn),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,nn(Zn),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 ei(t);this.scenes_.set(e,s);const n=new ti(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Rs)?this.app_.getResource(Rs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new ei(t);this.scenes_.set(e,s);const n=new ti(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Rs)?this.app_.getResource(Rs):null;if(e)i=await e.loadJson(t.path);else{const e=await fetch(t.path);i=await e.json()}}return await this.loadSceneData_(s,e,t,i),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,i);try{return await i}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,Se)){if(this.app_.world.get(e,Se).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())nn(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())Tn.unbind(e);s.postProcessBindings.clear(),this.releaseSceneAssets_(s),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,s,n){if(n){const s={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:s};this.app_.hasResource(Rs)&&(i.assetServer=this.app_.getResource(Rs));const o=await Ms(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,Se,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=ii(this.app_,t,n);this.app_.addSystemToSchedule(e,s)}const i=this.contexts_.get(t);s.setup&&await s.setup(i)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const s=this.app_.hasResource(Rs)?this.app_.getResource(Rs):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)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 s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n={};let i=!1;if(s.has(e,ue)){const t=s.get(e,ue);n.sprite=t.color.a,t.color.a=0,s.insert(e,ue,t),i=!0}if(s.has(e,ye)){const t=s.get(e,ye);n.spine=t.color.a,t.color.a=0,s.insert(e,ye,t),i=!0}if(s.has(e,ge)){const t=s.get(e,ge);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,ge,t),i=!0}i&&t.savedAlphas.set(e,n)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const s=this.app_.world;for(const e of t.entities){if(!s.valid(e))continue;const n=t.savedAlphas.get(e);if(n){if(void 0!==n.sprite&&s.has(e,ue)){const t=s.get(e,ue);t.color.a=n.sprite,s.insert(e,ue,t)}if(void 0!==n.spine&&s.has(e,ye)){const t=s.get(e,ye);t.color.a=n.spine,s.insert(e,ye,t)}if(void 0!==n.bitmapText&&s.has(e,ge)){const t=s.get(e,ge);t.color.a=n.bitmapText,s.insert(e,ge,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessBindings.values())s.setAllPassesEnabled(t)}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 ni=Ie(null,"SceneManager");function ii(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ni).getSceneStatus(t)&&s._fn(...n)}}}const oi=mt([ke(ni),Fe(De)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),ri={name:"SceneManager",build(e){const t=new si(e);e.insertResource(ni,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ni),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,oi)}};class ai{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new ct,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=c(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Je,this.resources_=new Le;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new ai}addPlugin(e){if(this.installedPluginSet_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if("string"==typeof t){if(!this.installedPluginNames_.has(t))throw new Error(`Plugin "${e.name??"unknown"}" requires plugin "${t}" which has not been installed`)}else if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installedPluginSet_.add(e),this.installed_plugins_.push(e),e.name&&this.installedPluginNames_.add(e.name),e.build(this),this}addEvent(e){return this.eventRegistry_.register(e),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}removeSystem(e){let t=!1;for(const[s,n]of this.systems_){const i=n.filter(t=>t.system._id!==e);i.length!==n.length&&(this.systems_.set(s,i),this.sortedSystemsCache_.delete(s),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Ve(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ni).register(e),this}setInitialScene(e){return this.getResource(ni).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new yt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(De)||this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(exports.Schedule.Last);else{this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new yt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(De,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(exports.Schedule.Startup),this.lastTime_=c(),this.mainLoop())}quit(){this.running_=!1,on();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=[Kn,Xn,Pn,hn,Rt,Gs];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const i=t.get(n);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,i=new Set,o=r=>{if(n.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}i.delete(r),n.add(r),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));const n=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(exports.Schedule[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(De);t.delta=e,t.elapsed+=e,t.frameCount++}}function li(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ci=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ui(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case re.FixedWidth:return o;case re.FixedHeight:return r;case re.Expand:return Math.max(o,r);case re.Shrink:return Math.min(o,r);case re.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const di=[];function hi(e){if(e<di.length)return di[e];const t={entity:0,viewProjection:new Float32Array(16),viewportRect:{x:0,y:0,w:0,h:0},clearFlags:0,priority:0,halfW:0,halfH:0,cameraX:0,cameraY:0};return di.push(t),t}function pi(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,Se);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===ie.Orthographic){if(d=i.orthoSize,l){d=ui(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=mi(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=yi(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=xi(o.position.x,o.position.y,o.position.z),p=hi(c.length);p.entity=e,p.viewProjection.set(bi(a,h)),p.viewportRect.x=i.viewportX,p.viewportRect.y=i.viewportY,p.viewportRect.w=i.viewportW,p.viewportRect.h=i.viewportH,p.clearFlags=i.clearFlags,p.priority=i.priority,p.halfW=u,p.halfH=d,p.cameraX=o.position.x,p.cameraY=o.position.y,c.push(p)}return c.sort((e,t)=>e.priority-t.priority),c}const fi=new Float32Array(16);function mi(e,t,s,n,i,o){const r=fi;r.fill(0);const a=t-e,l=n-s,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(n+s)/l,r[14]=-(o+i)/c,r[15]=1,r}const gi=new Float32Array(16);function yi(e,t,s,n){const i=gi;i.fill(0);const o=1/Math.tan(e/2),r=s-n;return i[0]=o/t,i[5]=o,i[10]=(n+s)/r,i[11]=-1,i[14]=2*n*s/r,i}const _i=new Float32Array(16);function xi(e,t,s){const n=_i;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 wi=new Float32Array(16);function bi(e,t){const s=wi;for(let n=0;n<4;n++)for(let i=0;i<4;i++)s[4*i+n]=e[0+n]*t[4*i+0]+e[4+n]*t[4*i+1]+e[8+n]*t[4*i+2]+e[12+n]*t[4*i+3];return s}const vi={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function Si(e,t,s,n,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let p,f,m,g;e.x===t.x?(p=c+s.x-i.x*r.x,m=p+i.x):(p=c+s.x,m=u+n.x),e.y===t.y?(f=d+s.y-i.y*r.y,g=f+i.y):(f=d+s.y,g=h+n.y);const y=Math.max(0,m-p),_=Math.max(0,g-f);return{originX:p+r.x*y,originY:f+r.y*_,width:y,height:_,rect:{left:p,bottom:f,right:m,top:g}}}const Pi=ne("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let Mi=null,Ti=null;function Ci(e,t){e.has(t,ue)||e.insert(t,ue,{texture:N,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 Ei(e,t){switch(e){case vi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vi.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case vi.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function Ai(e,t,s,n){if(!e.has(t,Pi))return;const i=e.get(t,Pi),o=Ei(s,n);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Pi,i)}function Ri(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ii(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Fi(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),i=[];for(const t of n){if(!t){i.push("");continue}let n="";for(let o=0;o<t.length;o++){const r=t[o],a=n+r;if(e.measureText(a).width>s&&n){if(Ii(r.charCodeAt(0))&&n.length>0&&Ii(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Ii(n.charCodeAt(t))){e=t;break}e>=0?(i.push(n.substring(0,e+1)),n=n.substring(e+1)+r):(i.push(n),n=r)}else i.push(n),n=r}else n=a}n&&i.push(n)}return i.length>0?i:[""]}function ki(e){let t=1;for(;t<e;)t*=2;return t}function Bi(e,t){let s=0,n=t;for(;e.has(n,fe);){const t=e.get(n,fe).entity;if(!e.valid(t))break;s++,n=t}return s}function Li(e,t){if(Mi&&Ti){const e=Mi.getUIRectComputedWidth(Ti,t);if(e>0)return e}return e.size.x}function Di(e,t){if(Mi&&Ti){const e=Mi.getUIRectComputedHeight(Ti,t);if(e>0)return e}return e.size.y}function Ui(e,t,s){let n=t;for(;e.has(n,fe);){const t=e.get(n,fe).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Wi(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function zi(e,t,s,n,i){if(!e.has(t,Pi))return;const o=e.get(t,Pi),r=Si(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,ue)){const s=e.get(t,ue);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,ue,s))}if(e.has(t,ae)){const s=e.get(t,ae);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,ae,s)}}function $i(e){const t=Object.keys(e),s=t.map(t=>e[t]);return{take(e){const n={};for(let i=0;i<t.length;i++)n[t[i]]=s[i](e);return n},changed(e,n){for(let i=0;i<t.length;i++)if(e[t[i]]!==s[i](n))return!0;return!1},update(e,n){for(let i=0;i<t.length;i++)e[t[i]]=s[i](n)}}}const Oi=.1,Hi=30,Vi={r:.3,g:.5,b:.8,a:1},Ni={Left:0,Center:1,Right:2},ji={Top:0,Middle:1,Bottom:2},Xi={Visible:0,Clip:1,Ellipsis:2},Yi=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ni.Left,verticalAlign:ji.Top,wordWrap:!0,overflow:Xi.Visible,lineHeight:1.2});class Gi{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=l(O.textCanvasSize,O.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,ki(this.frameMaxW_)),e.height=Math.max(e.height,ki(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=ki(this.frameMaxW_),e.height=ki(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=Fi(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),p=i?Math.ceil(o):d+2*u,f=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Xi.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,p),this.frameMaxH_=Math.max(this.frameMaxH_,f),(n.width<p||n.height<f)&&(n.width=Math.max(n.width,ki(p)),n.height=Math.max(n.height,ki(f)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;s.clearRect(0,0,n.width,n.height),s.font=`${e.fontSize}px ${e.fontFamily}`,s.textAlign=this.mapAlign(e.align),s.textBaseline="top",s.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===Xi.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case ji.Top:w=u;break;case ji.Middle:w=u+(f-2*u-x)/2;break;case ji.Bottom:w=f-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let b=w;for(const t of l){let n;switch(e.align){case Ni.Left:n=u;break;case Ni.Center:n=p/2;break;case Ni.Right:n=p-u;break;default:n=u}s.fillText(t,n,b),b+=c}i&&e.overflow===Xi.Clip&&s.restore();const v=s.getImageData(0,0,p,f),S=new Uint8Array(v.data.buffer),P=this.module.getResourceManager(),M=this.module._malloc(S.length);this.module.HEAPU8.set(S,M);const T=P.createTexture(p,f,M,S.length,1,!0);return this.module._free(M),{textureHandle:T,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const i=this.renderText(t,s);return this.cache.set(e,i),i}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}measureWidth(e){let t=0;for(const s of e)t=Math.max(t,this.ctx.measureText(s).width);return t}mapAlign(e){switch(e){case Ni.Left:return"left";case Ni.Center:return"center";case Ni.Right:return"right"}}}const qi=$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?Li(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0});class Ki{build(e){te("Text",Yi);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Gi(t),n=e.world,i=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Yi));for(const e of i.keys())if(!n.valid(e)||!n.has(e,Yi)){if(n.valid(e)&&n.has(e,ue)){const t=n.get(e,ue);n.insert(e,ue,{texture:N,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([Yi]);for(const t of e){const e=n.get(t,Yi),o=n.has(t,Pi)?n.get(t,Pi):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!qi.changed(a,r)){if(n.has(t,ue)&&n.get(t,ue).texture!==N)continue}Ci(n,t);const l=o?{size:{x:Li(o,t),y:Di(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,ue);n.insert(t,ue,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,qi.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Ji=new Ki,Qi=0,Zi=1,eo=ne("UIMask",{enabled:!0,mode:Qi});function to(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,i-s),h:Math.max(0,o-n)}}function so(e,t){const s=t??new Float32Array(16),n=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,b=n*u-r*a,v=i*c-o*l,S=i*u-r*l,P=o*u-r*c,M=d*g-h*m,T=d*y-p*m,C=d*_-f*m,E=h*y-p*g,A=h*_-f*g,R=p*_-f*y;let I=x*R-w*A+b*E+v*C-S*T+P*M;return 0===I||(I=1/I,s[0]=(l*R-c*A+u*E)*I,s[1]=(o*A-i*R-r*E)*I,s[2]=(g*P-y*S+_*v)*I,s[3]=(p*S-h*P-f*v)*I,s[4]=(c*C-a*R-u*T)*I,s[5]=(n*R-o*C+r*T)*I,s[6]=(y*b-m*P-_*w)*I,s[7]=(d*P-p*b+f*w)*I,s[8]=(a*A-l*C+u*M)*I,s[9]=(i*C-n*A-r*M)*I,s[10]=(m*S-g*b+_*x)*I,s[11]=(h*b-d*S-f*x)*I,s[12]=(l*T-a*E-c*M)*I,s[13]=(n*E-i*T+o*M)*I,s[14]=(g*w-m*v-y*x)*I,s[15]=(d*v-h*w+p*x)*I),s}function no(e,t,s,n,i,o,r){const a=(e-n)/o*2-1,l=(t-i)/r*2-1,c=s[0]*a+s[4]*l+s[12],u=s[1]*a+s[5]*l+s[13],d=s[3]*a+s[7]*l+s[15];return{x:c/d,y:u/d}}function io(e,t){return 2*Math.atan2(e,t)}function oo(e,t,s,n,i,o,r){const a=s[0]*e+s[4]*t+s[12],l=s[1]*e+s[5]*t+s[13],c=s[3]*e+s[7]*t+s[15];return[n+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function ro(e,t,s,n,i,o,r){if(!e.has(t,Pi)||!e.has(t,ae))return null;const a=e.get(t,Pi),l=e.get(t,ae),c=Li(a,t)*l.worldScale.x,u=Di(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,p=a.pivot.x,f=a.pivot.y,m=-c*p,g=c*(1-p),y=-u*f,_=u*(1-f),x=io(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),b=Math.sin(x),v=[[d+m*w-y*b,h+m*b+y*w],[d+g*w-y*b,h+g*b+y*w],[d+g*w-_*b,h+g*b+_*w],[d+m*w-_*b,h+m*b+_*w]];let S=1/0,P=1/0,M=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=oo(e,t,s,n,i,o,r);S=Math.min(S,a),P=Math.min(P,l),M=Math.max(M,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(P),w:Math.round(M-S),h:Math.round(T-P)}}function ao(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([eo]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,eo);s.enabled&&(d.add(e),s.mode===Zi?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,s,n,i,o,r,a,l,c){const u=[];for(const e of n){let s=!0;Ui(t,e,e=>{if(i.has(e)){if(t.get(e,eo).mode===Qi)return s=!1,!0}return!1}),s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(i.has(s)){if(t.get(s,eo).mode===Qi){const e=ro(t,s,o,r,a,l,c);e&&(n=to(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=ro(t,e,o,r,a,l,c);s&&d(e,s)}}(e,t,s,c,d,n,i,o,r,a),u.length>0&&function(e,t,s,n,i){e.renderer_clearStencil();const o=[];for(const e of n){let s=!0;Ui(t,e,e=>!!i.has(e)&&(s=!1,!0)),s&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,n){if(a)return;e.renderer_setEntityStencilMask(t,n);const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}function u(t,n){if(a)return;const o=e.getChildEntities(s,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,n),u(t,n)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,s,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class lo{build(e){if(te("UIMask",eo),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ao(e.wasmModule,e.world))}}const co=new lo,uo=ne("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),ho=ne("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),po={Normal:0,Hovered:1,Pressed:2,Disabled:3},fo=K("Button",{state:po.Normal,transition:null});class mo{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 go=Ie(new mo,"UIEvents");class yo{build(e){te("UIRect",Pi);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){Mi=e,Ti=t}(s,n);e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(vt)],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,mt([Fe(vt)],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,mt([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const _o=new yo;let xo=!1,wo=!1;function bo(){return xo}function vo(){return wo}const So=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&&(so(t,e),s=!1),e)}}();function Po(e,t,s,n){t.emit(s,n,s),Ui(e,s,i=>{if(!e.has(i,uo))return!1;const o=e.get(i,uo);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Mo{build(e){te("Interactable",uo),te("Button",fo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new mo;e.insertResource(go,i);let o=null,r=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(xt),Fe(vt)],(e,a)=>{if(i.drain(),bo()&&!vo())return;const l=t.getEntitiesWithComponents([ho]);for(const e of l){const s=t.get(e,ho);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,ho,s))}if(!a.valid)return;const c=u(),d=e.mouseX*c,h=a.screenH-e.mouseY*c;So.update(a.viewProjection);const p=no(d,h,So.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=p.x,a.worldMouseY=p.y;const f=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,p.x,p.y,f,m,g);const y=s.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,ho)){const e=t.get(o,ho);e.hovered=!1,t.insert(o,ho,e),i.emit(o,"hover_exit")}if(null!==_){Wi(t,_,ho);const e=t.get(_,ho);e.hovered=!0,t.insert(_,ho,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,ho);e.pressed=!0,e.justPressed=!0,t.insert(_,ho,e),r=_,Po(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,ho)){const e=t.get(r,ho);e.pressed=!1,e.justReleased=!0,t.insert(r,ho,e),Po(t,i,r,"release"),r===o&&Po(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(exports.Schedule.Update,mt([],()=>{const e=t.getEntitiesWithComponents([fo]);for(const s of e){if(Wi(t,s,uo,{enabled:!0}),!t.has(s,ho))continue;const e=t.get(s,ho),n=t.get(s,fo),i=t.get(s,uo),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=po.Pressed:e.hovered?n.state=po.Hovered:n.state=po.Normal:n.state=po.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,ue)){const o=t.get(s,ue);o.color=Ri(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,ue,o)}}},{name:"ButtonSystem"}))}}const To=new Mo,Co=K("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Eo=K("Focusable",{tabIndex:0,isFocused:!1});class Ao{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 Ro=Ie(new Ao,"FocusManager");class Io{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(te("TextInput",Co),bo()&&!vo())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=l(O.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,c=!1,u=!0,d=0,h=0;const p=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!p)return;const f=p;function m(){const t=e.getResource(Ro);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Co)?n:null}const g=()=>{c||null===m()||b()},y=()=>{c=!0},_=()=>{c=!1,b()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void v();const i=s.get(n,Co);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(go).emit(n,"submit"),void v()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,f.selectionStart=o,f.selectionEnd=o,i.dirty=!0,S())},w=()=>{const t=m();if(null!==t){const n=s.get(t,Co);n.focused=!1,n.dirty=!0;e.getResource(Ro).blur()}};function b(){const t=m();if(null===t)return;const n=s.get(t,Co);if(n.readOnly)return;let i=f.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),f.value=i),i!==n.value){n.value=i;e.getResource(go).emit(t,"change")}n.cursorPos=f.selectionStart??i.length,n.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=s.get(t,Co);e.focused=!1,e.dirty=!0}e.getResource(Ro).blur(),f.blur()}function S(){u=!0,d=0}f.addEventListener("input",g),f.addEventListener("compositionstart",y),f.addEventListener("compositionend",_),f.addEventListener("keydown",x),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",g),f.removeEventListener("compositionstart",y),f.removeEventListener("compositionend",_),f.removeEventListener("keydown",x),f.removeEventListener("blur",w),f.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let P=null;function M(e,l,c,d){(i.width<c||i.height<d)&&(i.width=ki(Math.max(i.width,c)),i.height=ki(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,c,d),o.save(),o.beginPath(),o.rect(l.padding,0,c-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const p=0===l.value.length,f=p?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=p?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=Fi(o,f,c-2*y);let t=y;for(const s of e)o.fillText(s,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(f,y,e)}if(l.focused&&u){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Fi(o,l.value,c-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const b=n.get(e);void 0!==b&&w.releaseTexture(b);const v=w.createTexture(c,d,r,x.length,1,!0);n.set(e,v);const S=s.get(e,ue);S.texture=v,S.size.x=c,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,ue,S)}e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(Ro)],e=>{const t=s.getEntitiesWithComponents([Co]);for(const e of t)Wi(s,e,Eo,{tabIndex:0,isFocused:!1}),Wi(s,e,uo,{enabled:!0,blockRaycast:!0});const n=m();if(n!==P){if(null!==P&&s.valid(P)&&s.has(P,Co)){const e=s.get(P,Co);e.focused=!1,e.dirty=!0,f.blur()}null!==n&&function(e){const t=s.get(e,Co);t.readOnly||(t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),S())}(n),P=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(d+=i,d>=.5)){d-=.5,u=!u;s.get(o,Co).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Co)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Co,Pi]);for(const e of a){const t=s.get(e,Co);if(!t.dirty)continue;const n=s.get(e,Pi),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(Ci(s,e),M(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Fo=new Io,ko={Simple:0,Sliced:1,Tiled:2,Filled:3},Bo={Horizontal:0,Vertical:1},Lo={Left:0,Right:1,Bottom:2,Top:3},Do=K("Image",{texture:N,color:{r:1,g:1,b:1,a:1},imageType:ko.Simple,fillMethod:Bo.Horizontal,fillOrigin:Lo.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Uo=$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?Li(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Di(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Wo{build(e){te("Image",Do);const t=e.world,s=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,Do)||s.delete(e);const e=t.getEntitiesWithComponents([Do]);for(const n of e){const e=t.get(n,Do),i=t.has(n,Pi)?t.get(n,Pi):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Uo.changed(r,o))continue;Ci(t,n);const a=t.get(n,ue);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=Li(i,n),a.size.y=Di(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===ko.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Bo.Horizontal?e.fillOrigin===Lo.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===Lo.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===ko.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,ue,a),s.set(n,Uo.take(o))}else a.color.a=0,t.insert(n,ue,a),s.set(n,Uo.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const zo=new Wo,$o=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Oo=K("ToggleGroup",{allowSwitchOff:!1});class Ho{build(e){te("Toggle",$o),te("ToggleGroup",Oo);const t=e.world,s=new Set;e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(go)],e=>{const n=t.getEntitiesWithComponents([$o]);if(!bo()||vo()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,$o);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,$o,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,$o);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(Wi(t,s,uo,{enabled:!0}),!t.has(s,ho))continue;const n=t.get(s,ho),i=t.get(s,$o),r=t.get(s,uo);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Oo);if(i.isOn&&r){if(!t.get(n,Oo).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,$o,i),i.isOn&&r){const i=o.get(n);if(i)for(const n of i){if(n===s)continue;const i=t.get(n,$o);i.isOn&&(i.isOn=!1,t.insert(n,$o,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,ue)){const e=t.get(s,ue);e.color=Ri(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,ue,e)}}}for(const e of n){const s=t.get(e,$o);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,ue)){const e=t.get(s.graphicEntity,ue);e.enabled=s.isOn,t.insert(s.graphicEntity,ue,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Vo=new Ho,No=vi,jo=K("ProgressBar",{value:0,fillEntity:0,direction:vi.LeftToRight});function Xo(e,t,s,n){if(!e.has(t,Pi))return;const i=e.get(t,Pi),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=Si(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,ue)){const s=e.get(t,ue);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,ue,s))}if(e.has(t,ae)){const s=e.get(t,ae),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,ae,s))}}class Yo{build(e){te("ProgressBar",jo);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{const e=t.getEntitiesWithComponents([jo,Pi]);for(const s of e){const e=t.get(s,jo);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,Pi),i=Math.max(0,Math.min(1,e.value));Ai(t,e.fillEntity,e.direction,i);const o=Li(n,s),r=Di(n,s);Xo(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Go=new Yo,qo=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ko=K("DragState",{isDragging:!1,startWorldPos:{x:0,y:0},currentWorldPos:{x:0,y:0},deltaWorld:{x:0,y:0},totalDeltaWorld:{x:0,y:0},pointerStartWorld:{x:0,y:0}});class Jo{build(e){te("Draggable",qo),te("DragState",Ko);const t=e.world,s=e.getResource(go);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(xt),Fe(vt)],(e,r)=>{if(bo()&&!vo())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([qo,ho]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,qo).enabled)continue;if(t.get(n,ho).hovered){let e=0;t.has(n,ue)&&(e=t.get(n,ue).layer);const i=Bi(t,n);(e>o||e===o&&i>=r)&&(o=e,r=i,s=n)}}if(null!==s){n=s,i={x:a.x,y:a.y},t.has(s,Ko)||t.insert(s,Ko);const e=t.get(s,Ko),o=t.get(s,ae);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,Ko)){t.get(n,Ko).isDragging=!1}n=null}if(null!==n&&null===o){if(!t.valid(n))return void(n=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(n,qo);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Ko).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Ko))return void(o=null);const n=t.get(o,Ko),i=t.get(o,qo),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const d=function(e,t,s,n){let i=e.lockX?t.startWorldPos.x:s,o=e.lockY?t.startWorldPos.y:n;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,n,c,u);c=d.x,u=d.y;const h=n.currentWorldPos.x,p=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-p},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,ae)){const e=function(e,t,s,n){if(!e.has(t,fe))return{x:s,y:n};const i=e.get(t,fe).entity;if(!e.valid(i)||!e.has(i,ae))return{x:s,y:n};const o=e.get(i,ae),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=io(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(s*u-n*c)/r,y:(s*c+n*u)/a}}(t,o,n.deltaWorld.x,n.deltaWorld.y),s=t.get(o,ae);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ae,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const Qo=new Jo,Zo=K("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function er(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 tr(e,t,s,n,i){const o=2/(n=Math.max(1e-4,n)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(s+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(s-o*c)*a}}class sr{build(e){te("ScrollView",Zo);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([Fe(xt),Fe(vt),Fe(De)],(e,i,o)=>{const r=bo()&&!vo(),a=Math.min(o.delta,.05);for(const[e]of s)t.valid(e)||s.delete(e);i.valid&&(n.x=i.worldMouseX,n.y=i.worldMouseY);const l=t.getEntitiesWithComponents([Zo,Pi]);for(const o of l){Wi(t,o,eo,{enabled:!0,mode:Qi});const l=t.get(o,Zo),c=t.get(o,Pi);let u=s.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},s.set(o,u));const d=Li(c,o),h=Di(c,o);let p=l.contentWidth,f=l.contentHeight;if((0===p||0===f)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,me)){const e=t.get(l.contentEntity,me).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,ae))continue;const e=t.get(r,ae);let a=0,l=0,c=.5,u=.5;if(t.has(r,Pi)){const e=t.get(r,Pi);a=Li(e,r)||e.size.x,l=Di(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,ue)){const e=t.get(r,ue);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),p=e.position.y-l*u,f=e.position.y+l*(1-u);d<s&&(s=d),h>n&&(n=h),p<i&&(i=p),f>o&&(o=f)}0===p&&(p=n-s),0===f&&(f=o-i)}const m=Math.max(0,p-d),g=Math.max(0,f-h);if(!r&&i.valid){Wi(t,o,uo,{enabled:!0,blockRaycast:!0});const s=t.has(o,ho)?t.get(o,ho):null;if(s?.justPressed&&(u.isDragging=!0,u.lastWorldX=n.x,u.lastWorldY=n.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=n.x-u.lastWorldX,t=n.y-u.lastWorldY,s=Math.min(1,10*a);if(l.horizontalEnabled){const t=er(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const n=a>0?-e*t/a:0;u.velocityX+=(n-u.velocityX)*s}}if(l.verticalEnabled){const e=er(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const n=a>0?t*e/a:0;u.velocityY+=(n-u.velocityY)*s}}u.lastWorldX=n.x,u.lastWorldY=n.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=er(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=er(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=tr(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Oi&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Oi?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=tr(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Oi&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Oi?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ae)){const e=t.get(l.contentEntity,ae),s=e.position.x,n=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(s-u.lastAppliedX)>.01)&&(u.contentBaseX=s),(isNaN(u.lastAppliedY)||Math.abs(n-u.lastAppliedY)>.01)&&(u.contentBaseY=n),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,ae,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const nr=new sr,ir=vi,or=K("Slider",{value:0,minValue:0,maxValue:1,direction:vi.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function rr(e,t,s,n,i,o){const r=Li(n,i)*s.worldScale.x,a=Di(n,i)*s.worldScale.y,l=io(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,p=d*u-h*c,f=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case vi.LeftToRight:return r>0?(p-m)/r:0;case vi.RightToLeft:return r>0?1-(p-m)/r:0;case vi.BottomToTop:return a>0?(f-g)/a:0;case vi.TopToBottom:return a>0?1-(f-g)/a:0}}function ar(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case vi.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case vi.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case vi.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case vi.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class lr{build(e){te("Slider",or);const t=e.world;let s=null;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(xt),Fe(vt),Fe(go)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([or,Pi]);for(const r of o){const o=t.get(r,or),a=t.get(r,Pi);if(!bo()||vo()){if(t.has(r,ae)){Wi(t,r,uo,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Wi(t,o.handleEntity,uo,{enabled:!0,blockRaycast:!1});const l=t.get(r,ae),c=t.has(r,ho)?t.get(r,ho):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,ho)&&(u=t.get(o.handleEntity,ho).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=rr(n.worldMouseX,n.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let s=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(s=Math.round(s));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,s)),t.insert(r,or,o),o.value!==c&&i.emit(r,"change")}s===r&&e.isMouseButtonReleased(0)&&(s=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Li(a,r),d=Di(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Ai(t,o.fillEntity,o.direction,c),zi(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Pi)){const e=t.get(o.handleEntity,Pi);ar(e,o.direction,c),t.insert(o.handleEntity,Pi,e),zi(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const cr=new lr;class ur{build(e){te("Focusable",Eo);const t=e.world,s=new Ao;e.insertResource(Ro,s),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(xt),Fe(go)],(e,n)=>{if(bo()&&!vo())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Eo]);for(const e of i){if(!t.has(e,ho))continue;t.get(e,ho).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const n=function(){const e=[];for(const s of i){if(!t.valid(s))continue;if(t.has(s,uo)){if(!t.get(s,uo).enabled)continue}const n=t.get(s,Eo);e.push({entity:s,tabIndex:n.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===n.length)return;const r=null!==s.focusedEntity?n.findIndex(e=>e===s.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?n.length-1:0:a?(r-1+n.length)%n.length:(r+1)%n.length,o(n[l])}function o(e){const i=s.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Eo)){t.get(i,Eo).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Eo).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const dr=new ur,hr=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function pr(){return s()?function(){const e=globalThis,t=e.wx?.getSystemInfoSync?.();if(!t||!t.safeArea)return{top:0,bottom:0,left:0,right:0};const{safeArea:s,screenWidth:n,screenHeight:i}=t;return{top:s.top,bottom:i-s.bottom,left:s.left,right:n-s.right}}():function(){if("undefined"==typeof document||"undefined"==typeof getComputedStyle)return{top:0,bottom:0,left:0,right:0};const e=getComputedStyle(document.documentElement);return{top:parseFloat(e.getPropertyValue("--sat")||"0"),bottom:parseFloat(e.getPropertyValue("--sab")||"0"),left:parseFloat(e.getPropertyValue("--sal")||"0"),right:parseFloat(e.getPropertyValue("--sar")||"0")}}()}class fr{build(e){te("SafeArea",hr);const t=e.world;let n=pr(),i=!0,o=0,r=0;if(s()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=pr(),i=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=pr(),i=!0});e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(vt)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,i=!0),!i)return;i=!1;const l=u(),c=s()?a/e.screenH:l*a/e.screenH,d=t.getEntitiesWithComponents([hr,Pi]);for(const e of d){const s=t.get(e,hr),i=t.get(e,Pi),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Pi,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const mr=new fr,gr=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let yr=null;class _r{build(e){te("ListView",gr);const t=e.world,s=new Map;yr=s,e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([Fe(xt)],e=>{const n=bo()&&!vo();for(const[e,n]of s)if(!t.valid(e)){for(const e of n.itemEntities.values())t.valid(e)&&t.despawn(e);s.delete(e)}const i=t.getEntitiesWithComponents([gr,Pi]);for(const o of i){Wi(t,o,uo,{enabled:!0,blockRaycast:!0}),Wi(t,o,eo,{enabled:!0,mode:Qi});let i=s.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},s.set(o,i));const r=t.get(o,gr),a=t.get(o,Pi),l=Di(a,o),c=Li(a,o);if(!n){const s=t.has(o,ho)?t.get(o,ho):null;if(s?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<d||e>=h)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=d;e<h;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,ve,{value:`ListItem_${e}`}),t.insert(s,Pi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(s,o),i.itemEntities.set(e,s),i.renderer&&i.renderer(e,s)),t.has(s,ae)){const n=t.get(s,ae);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,ae,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const xr=new _r,wr=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class br{build(e){te("Dropdown",wr);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ae))return;const s=t.get(e,ae);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ae,{position:{x:s.position.x,y:s.position.y,z:s.position.z},rotation:{x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,ue)){const s=t.get(e,ue);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,ue,{texture:s.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:s.enabled})}}function o(e,s,n){s.isOpen=!0,n.highlightIndex=s.selectedIndex;const i=s.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(n);const o=t.get(e,ue),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Hi;t.insert(i,Pi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,ae,{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,ue,{texture:N,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Hi;t.insert(o,ve,{value:`Option_${e}`}),t.insert(o,Pi,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Hi},offsetMax:{x:0,y:0},size:{x:r,y:Hi},pivot:{x:.5,y:.5}}),t.insert(o,ae,{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,ue,{texture:N,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Hi},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,uo,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ae,{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,Yi,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ni.Left,verticalAlign:ji.Middle,wordWrap:!1,overflow:Xi.Clip,lineHeight:1.2}),t.insert(c,Pi,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Hi},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}d(n)}function r(e,t,s){t.isOpen=!1,c(s),u(t.listEntity,!1)}function a(e,t,s,n,i){t.selectedIndex=n,r(0,t,s),i.emit(e,"change")}function l(e){const s=e.labelEntity;if(0===s||!t.valid(s))return;if(!t.has(s,Yi))return;const n=t.get(s,Yi);let i={r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},o=n.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(s,Yi,{content:o,fontSize:n.fontSize,fontFamily:n.fontFamily,color:i,align:n.align,verticalAlign:n.verticalAlign,wordWrap:n.wordWrap,overflow:n.overflow,lineHeight:n.lineHeight})}function c(e){for(const s of e.textEntities)t.valid(s)&&t.despawn(s);for(const s of e.optionEntities)t.valid(s)&&t.despawn(s);e.optionEntities=[],e.textEntities=[]}function u(e,s){if(0!==e&&t.valid(e)&&(t.has(e,uo)&&t.insert(e,uo,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,ue))){const n=t.get(e,ue);t.insert(e,ue,{texture:n.texture,color:{r:n.color.r,g:n.color.g,b:n.color.b,a:n.color.a},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:s})}}function d(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,ue))continue;const i=s===e.highlightIndex?{...Vi}:{r:.95,g:.95,b:.95,a:1};t.insert(n,ue,{texture:N,color:i,size:{x:e.ddWidth,y:Hi},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,ho))continue;if(t.get(s,ho).hovered)return!0}return!1}e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(xt),Fe(go)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const p=bo()&&!vo(),f=t.getEntitiesWithComponents([wr]);for(const m of f){const f=t.get(m,wr);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(f.listEntity),i(m),f.isOpen||u(f.listEntity,!1),l(f),p)continue;Wi(t,m,uo,{enabled:!0,blockRaycast:!0});const y=t.has(m,ho)?t.get(m,ho):null;if(y?.justPressed&&(f.isOpen?r(m,f,g):o(m,f,g)),f.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,ho))continue;if(t.get(s,ho).justPressed){a(m,f,g,e,c);break}}let s=-1;for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,ho))continue;if(t.get(n,ho).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=f.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=f.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,f,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,f,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,f,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const vr=new br,Sr=0,Pr=0,Mr=2,Tr=K("LayoutGroup",{direction:Sr,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Pr,reverseOrder:!1});class Cr{build(e){te("LayoutGroup",Tr);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([],()=>{const e=t.getEntitiesWithComponents([Tr,Pi,me]);for(const s of e){const e=t.get(s,Tr),n=t.get(s,Pi),i=t.get(s,me);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Pi)&&t.has(e,ae)&&o.push({entity:e,rect:t.get(e,Pi)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Li(n,s),a=Di(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===Sr;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=Li(n.rect,n.entity),p=Di(n.rect,n.entity),f=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+f*i,y=e.childAlignment===Pr?(1-c)*a-u.top-(1-m)*p:e.childAlignment===Mr?-c*a+u.bottom+m*p:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*p,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Pr?-l*r+u.left+f*i:e.childAlignment===Mr?(1-l)*r-u.right-(1-f)*i:(.5-l)*r+.5*(u.left-u.right)+(f-.5)*i,y=(1-c)*a-u.top-h-(1-m)*p,h+=p,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,ae);_.position.x=g,_.position.y=y,t.insert(n.entity,ae,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Er=new Cr;class Ar{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Rr=new Ar;async function Ir(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 Fr=Ie({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),kr={r:.2,g:.4,b:1,a:.7},Br={r:.2,g:1,b:.2,a:.7},Lr={r:.2,g:1,b:1,a:.7},Dr={r:1,g:1,b:.2,a:.5},Ur={r:1,g:.2,b:.2,a:.8},Wr={r:1,g:.2,b:.2,a:1},zr=1.5,$r=16;function Or(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Hr(e){switch(e){case Ae.Static:return kr;case Ae.Kinematic:return Lr;default:return Br}}function Vr(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*r-s.y*a,y:t+s.x*a+s.y*r}));for(let e=0;e<4;e++)Js.line(l[e],l[(e+1)%4],o,zr)}function Nr(e,t,s,n,i,o){const r=Math.cos(i),a=Math.sin(i),l=(s,n)=>({x:e+s*r-n*a,y:t+s*a+n*r}),c=l(-s,n),u=l(s,n),d=l(-s,-n),h=l(s,-n);Js.line(c,d,o,zr),Js.line(u,h,o,zr);for(let e=0;e<$r;e++){const t=e/$r*Math.PI,i=(e+1)/$r*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Js.line(r,a,o,zr)}for(let e=0;e<$r;e++){const t=Math.PI+e/$r*Math.PI,i=Math.PI+(e+1)/$r*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Js.line(r,a,o,zr)}}function jr(e,t,s,n){const i=e+.5*s,o=t+.5*n;Js.line({x:e,y:t},{x:i,y:o},Ur,zr);const r=Math.sqrt(s*s+n*n);if(r<1)return;const a=Math.PI/6,l=s/r,c=n/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),p=o-6*(-l*Math.sin(a)+c*Math.cos(a));Js.line({x:i,y:o},{x:u,y:d},Ur,zr),Js.line({x:i,y:o},{x:h,y:p},Ur,zr)}function Xr(e,t,s){const n=e.getResource(Fr);if(!n||!n.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([he]);for(const s of t){const t=e.world.get(s,he);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Me,ae]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Me);if(!s.enabled)continue;const o=e.world.get(t,ae),a=o.worldPosition.x,l=o.worldPosition.y,c=Or(o.worldRotation);if(n.showColliders){if(e.world.has(t,Te)){const n=e.world.get(t,Te),o=n.isSensor?Dr:Hr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Vr(a+r*d-u*h,l+r*h+u*d,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Ce)){const n=e.world.get(t,Ce),o=n.isSensor?Dr:Hr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c),p=a+r*d-u*h,f=l+r*h+u*d;Js.circleOutline({x:p,y:f},n.radius*i,o,zr,32)}if(e.world.has(t,Ee)){const n=e.world.get(t,Ee),o=n.isSensor?Dr:Hr(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,d=Math.cos(c),h=Math.sin(c);Nr(a+r*d-u*h,l+r*h+u*d,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Ae.Dynamic){const e=r.getLinearVelocity(t);jr(a,l,e.x*i,e.y*i)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)Js.circle({x:e.contactX,y:e.contactY},3,Wr,!0,32)}}const Yr=Ie({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Gr=Ie(null,"PhysicsAPI");function qr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Kr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class Jr{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,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(Yr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Ir(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const i=function(e){const t=e.world.getEntitiesWithComponents([he]);for(const s of t){const t=e.world.get(s,he);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(exports.Schedule.PostUpdate,mt([Fe(De)],a=>{if(bo()&&!vo())return;const l=r.getEntitiesWithComponents([Me,ae]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Me),l=r.get(i,ae);if(t.has(i)){const e=s.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=qr(l.worldRotation);n._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ea(e,n,i,this.config_.collisionLayerMasks),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Ae.Kinematic){const e=qr(l.worldRotation);n._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,r=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,c=t.HEAPF32[n+3];if(!e.world.valid(r))continue;const u=e.world.get(r,ae);if(!u)continue;let d=a,h=l,p=c;if(e.world.has(r,fe)){const t=e.world.get(r,fe);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ae)){const s=e.world.get(t.entity,ae),n=qr(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);d=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),h=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),p=c-n}}u.position.x=d,u.position.y=h;const f=Kr(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(r,ae,u)}}(e,n,i),function(e,t,s){t._physics_collectEvents();const n=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+5]*s})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<r;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<l;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;c.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Yr,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Gr,ta._fromModule(n)),function(e,t,s){e.insertResource(Fr,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),sn("physics-debug-draw",()=>{Xr(e,t,s)})}(e,Gr,Yr),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}const Qr=16;function Zr(e,t,s){if(!s)return t;for(let t=0;t<Qr;t++)if(e===1<<t)return s[t];return t}function ea(e,t,s,n){const i=e.world;if(i.has(s,Te)){const e=i.get(s,Te),o=e.categoryBits??1,r=Zr(o,e.maskBits??65535,n);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,o,r)}if(i.has(s,Ce)){const e=i.get(s,Ce),o=e.categoryBits??1,r=Zr(o,e.maskBits??65535,n);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(s,Ee)){const e=i.get(s,Ee),o=e.categoryBits??1,r=Zr(o,e.maskBits??65535,n);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}}class ta{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(ta.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)}static setDebugDraw(e,t){const s=e.getResource(Fr);s&&(s.enabled=t,e.insertResource(Fr,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Fr);s&&e.insertResource(Fr,{...s,...t})}}const sa={nearest:0,linear:1},na={repeat:0,clamp:1,mirror:2};function ia(e,t,s=!0,n){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),n&&(n.filterMode||n.wrapMode)&&i.createTextureEx){const e=sa[n.filterMode??"linear"]??1,a=na[n.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,s,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,s);return e._free(o),r}function oa(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 ra(e,t,s,n){const i=e.worldScale.x*t*(s?-1:1),o=e.worldScale.y*t*(n?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,p=c+c,f=a*d,m=a*h,g=a*p,y=l*h,_=l*p,x=c*p,w=u*d,b=u*h,v=u*p;return new Float32Array([(1-(y+x))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(f+x))*o,(_+w)*o,0,(g+b)*r,(_-w)*r,(1-(f+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function aa(e){const{app:t,module:s,sceneData:n,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,s){const n={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=_s(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===n[o])try{const t=i?.[o];n[o]=ia(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(s,n,i);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const i=s[e];if(i&&i>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(i,e.left,e.right,e.top,e.bottom)}}}}(s,n,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=xs(n.type);if(!r||!n.data)continue;const a=n.data[r.skeletonField],l=n.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const n=await i.readText(l),r="binary"===b(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);h=s.length,d=t._malloc(h+1),t.HEAPU8.set(s,d),t.HEAPU8[d+h]=0}const p=s.loadSkeleton(d,h,n,n.length,r);if(t._free(d),p<0)continue;o[a]=p;const f=oa(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=m+"/"+f[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=ia(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,h,n,i)),r){const e={gravity:a?.gravity??{...z},fixedTimestep:a?.fixedTimestep??$,subStepCount:a?.subStepCount??4};new Jr("",e,()=>Promise.resolve(r)).build(t)}const p=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=_s(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=b(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=ia(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),f=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=_s(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){s[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=n[i];r||(r=Ft.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Ft.createFromAsset(e,r)}catch{s[o]=0}}return s}(n,i);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=_s(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=JSON.parse(t),o=Vt(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,ia(e,n))}catch{r.set(t,0)}Xt(Nt(i,n,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(s,n,i),await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=_s(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!n.has(i)){n.add(i);try{const t=await s.readText(i),n=hs(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=ps(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=ia(e,t),Qt(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}ts(i,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(s,n,i),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=_s(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!n.has(t)&&(n.add(t),s.push(t))}}0!==s.length&&(t?await Promise.all(s.map(async e=>{try{const s=await t.readBinary(e);await qt.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await qt.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(n,i),function(e,t,s,n){const i={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=_s(e.type);if(0===t.length)continue;const s=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof s[e.field]&&(s[e.field]=t[s[e.field]]||0)}}}(n,u,p,f);const m=Ps(t.world,n);if(c&&t.hasResource(ni))for(const e of m.values())t.world.insert(e,Se,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,s,n){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=xs(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,n,d,m);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=W);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,ye)?c.get(o,ye):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,ae)){const e=ra(c.get(o,ae),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(r);for(let e=0;e<p;e++){const i=n.getMeshBatchVertexCount(r,e),o=n.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=s._malloc(a),u=s._malloc(l),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,p);const f=s.HEAPU32[d>>2],m=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),y=new Uint16Array(s.HEAPU8.buffer,u,o),_=t._malloc(a),x=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(y),t.renderer_submitTriangles(_,i,x,o,f,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(t,s,o,h,e)}if(l){const e=t.getResource(Rs);e&&e.setAddressableManifest(l)}}function la(e,t,s){return{name:e,async setup(){await aa({...s,sceneData:t,sceneName:e})}}}async function ca(e){const{app:t,firstScene:s,aspectRatio:n}=e;li(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ni);for(const t of e.scenes)o.register(la(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Es(t.world,n)}class ua{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=xs(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===b(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=_s(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(n.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&s.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of n){const t=b(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const da="__preview__";const ha={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Yn.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Yn.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Yn.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Yn.releaseRenderTarget(e._handle),ha.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Yn.begin(t,e._handle)},end(){Yn.end()},getDepthTexture:e=>Yn.getTargetDepthTexture(e._handle)};var pa;exports.LogLevel=void 0,(pa=exports.LogLevel||(exports.LogLevel={}))[pa.Debug=0]="Debug",pa[pa.Info=1]="Info",pa[pa.Warn=2]="Warn",pa[pa.Error=3]="Error";class fa{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 ma{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new fa)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const i={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(i)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const ga=new ma;const ya={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},_a={Running:0,Paused:1,Completed:2,Cancelled:3},xa={None:0,Restart:1,PingPong:2};const wa=1.70158,ba=2.70158,va=2.5949095;const Sa=2*Math.PI/3,Pa=2*Math.PI/4.5;const Ma=7.5625,Ta=2.75;const Ca=1e-6;function Ea(e,t,s){switch(e){case ya.Linear:return t;case ya.EaseInQuad:return function(e){return e*e}(t);case ya.EaseOutQuad:return function(e){return e*(2-e)}(t);case ya.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ya.EaseInCubic:return function(e){return e*e*e}(t);case ya.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ya.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ya.EaseInBack:return function(e){return ba*e*e*e-wa*e*e}(t);case ya.EaseOutBack:return function(e){const t=e-1;return 1+ba*t*t*t+wa*t*t}(t);case ya.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-va)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+va)+2)/2}(t);case ya.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Sa)}(t);case ya.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Sa)+1}(t);case ya.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Pa)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Pa)/2+1}(t);case ya.EaseOutBounce:return function(e){return e<1/Ta?Ma*e*e:e<2/Ta?Ma*(e-=1.5/Ta)*e+.75:e<2.5/Ta?Ma*(e-=2.25/Ta)*e+.9375:Ma*(e-=2.625/Ta)*e+.984375}(t);case ya.CubicBezier:return s?function(e,t,s,n,i){let o=e;for(let s=0;s<8;s++){const s=1-o,i=3*t*s*s*o+3*n*s*o*o+o*o*o-e;if(Math.abs(i)<Ca)break;const r=3*t*(1-2*o)*(1-o)+6*n*o*(1-o)-3*n*o*o+3*o*o;if(Math.abs(r)<Ca)break;o-=i/r}const r=1-o;return 3*s*r*r*o+3*i*r*o*o+o*o*o}(t,s.p1x,s.p1y,s.p2x,s.p2y):t;case ya.Step:return function(e){return e<1?0:1}(t);default:return t}}const Aa=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,s,n,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:s,elapsed:0,delay:i?.delay??0,easing:i?.easing??ya.Linear,bezierPoints:null,state:_a.Running,loop:i?.loop??xa.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:n,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===_a.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==_a.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const s=Math.min(t.elapsed/t.duration,1),n=Ea(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==xa.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===xa.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=_a.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===_a.Running&&(t.state=_a.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===_a.Paused&&(t.state=_a.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=_a.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:_a.Cancelled}setBezier(e,t,s,n,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:s,p2x:n,p2y:i})}setSequenceNext(e,t){const s=this.entries_.get(e);s&&(s.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const s=this.entries_.get(e);s&&(s.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class Ra{constructor(e){this.id=e}get state(){return Aa.getState(this.id)}bezier(e,t,s,n){return Aa.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ra?Aa.setSequenceNext(this.id,e.id):Aa.setSequenceNextExternal(this.id,e),this}pause(){Aa.pause(this.id)}resume(){Aa.resume(this.id)}cancel(){Aa.cancel(this.id)}}class Ia{constructor(e,t,s){this.module_=e,this.registry_=t,this.entity=s}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,s,n){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,s,n),this}then(e){return e instanceof Ra?(Aa.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let Fa=null,ka=null;function Ba(e,t){Fa=e,ka=t,Aa.init(e,t)}function La(){Aa.shutdown(),Fa=null,ka=null}function Da(){if(!Fa)throw new Error("Tween API not initialized");return Fa}function Ua(){if(!ka)throw new Error("Tween API not initialized");return ka}const Wa={to(e,t,s,n,i,o){const r=Da(),a=Ua(),l=o?.easing??ya.Linear,c=o?.delay??0,u=o?.loop??xa.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Ia(r,a,h)},value(e,t,s,n,i){const o=Aa.create(e,t,s,n,i);return new Ra(o)},cancel(e){Da()._anim_cancelTween(Ua(),e.entity)},cancelAll(e){Da()._anim_cancelAllTweens(Ua(),e)},update(e){Da()._anim_updateTweens(Ua(),e),Aa.update(e)}};class za{constructor(){this.name="AnimationPlugin"}build(e){Ba(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Wa.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Gt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){La()}}const $a=new za;var Oa;exports.AttenuationModel=void 0,(Oa=exports.AttenuationModel||(exports.AttenuationModel={}))[Oa.Linear=0]="Linear",Oa[Oa.Inverse=1]="Inverse",Oa[Oa.Exponential=2]="Exponential";const Ha={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Va(e,t=Ha){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case exports.AttenuationModel.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case exports.AttenuationModel.Inverse:a=n/Math.max(r,n);break;case exports.AttenuationModel.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function Na(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const ja=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:exports.AttenuationModel.Inverse,rolloff:1,priority:0,enabled:!0}),Xa=K("AudioListener",{enabled:!0});class Ya{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const s=t().createAudioBackend(),n=this.config_;s.initialize({initialPoolSize:n.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=s.mixer;qt.init(s,i),i&&(void 0!==n.masterVolume&&(i.master.volume=n.masterVolume),void 0!==n.musicVolume&&(i.music.volume=n.musicVolume),void 0!==n.sfxVolume&&(i.sfx.volume=n.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(exports.Schedule.PreUpdate,mt([Fe(De)],t=>{if(!(!bo()||vo()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([Xa,ce]);for(const e of h){if(n.get(e,Xa).enabled){const t=n.get(e,ce);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([ja]);a.clear();for(const e of p){const t=n.get(e,ja);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&s.isReady){const e=qt.getBufferHandle(t.clip);if(e){const n=s.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,n),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const s=o.get(c);if(!s.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,ce),a=r?.position.x??0,h=r?.position.y??0,p=a-i,f=h-u,m=Va(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Na(a,0,i,0,t.maxDistance);s.setVolume(t.volume*m),s.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),qt.dispose()}}const Ga=new Ya;let qa=null,Ka=null;function Ja(e,t){qa=e,Ka=t}function Qa(){qa=null,Ka=null}const Za={update(e){qa&&Ka&&qa.particle_update?.(Ka,e)},play(e){qa&&Ka&&qa.particle_play?.(Ka,e)},stop(e){qa&&Ka&&qa.particle_stop?.(Ka,e)},reset(e){qa&&Ka&&qa.particle_reset?.(Ka,e)},getAliveCount:e=>qa?qa.particle_getAliveCount?.(e)??0:0};class el{constructor(){this.name="ParticlePlugin"}build(e){Ja(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Za.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Qa()}}const tl=new el,sl=1e6;class nl{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){is(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(vt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:sl,l=i?.valid?i.worldTop:sl,c=t.getEntitiesWithComponents([ls,ae]);for(const e of c){const n=t.tryGet(e,ls),i=t.tryGet(e,ae);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=Zt(c);if(!u)continue;if(!s.has(e)){if(rs.initLayer(e,n.width,n.height,n.tileWidth,n.tileHeight),n.tiles.length>0){const t=new Uint16Array(n.tiles.length);for(let e=0;e<n.tiles.length;e++)t[e]=n.tiles[e];rs.setTiles(e,t)}s.add(e)}const d=n.tileWidth/u.width,h=n.tileHeight/u.height,p=n.tint,f=n.parallaxFactor;rs.submitLayer(e,c,n.layer,0,n.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,p.r,p.g,p.b,p.a,n.opacity,f.x,f.y)}const u=t.getEntitiesWithComponents([as,ae]);for(const e of u){if(t.tryGet(e,ls))continue;const i=t.tryGet(e,as),c=t.tryGet(e,ae);if(!i?.source||!c)continue;const u=ss(i.source);if(!u)continue;if(!n.has(e)){const t=[];for(let n=0;n<u.layers.length;n++){const i=1073741824+256*e+n,o=u.layers[n];rs.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&rs.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const d=n.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],s=u.tilesets[0];if(!s)continue;const n=Zt(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;rs.submitLayer(t,s.textureHandle,e,0,s.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)rs.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),es(),os()}}const il=new nl;function ol(e,t){return e.toFixed(t)}function rl(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class al{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${ol(e.fps,1)}</span> Frame: <span style="color:#d19a66">${ol(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const s=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let n='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of s){n+=`<div>${rl(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${ol(t,1)}ms</span></div>`}t.push(n)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function ll(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const cl=Ie(ll(),"Stats");const ul="StatsCollect";class dl{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class hl{constructor(e){this.name="Stats",this.collector_=new dl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(cl,ll());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new al(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=mt([Fe(De),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(cl);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(ul),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Yn.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,s?.update(o)},{name:ul});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const pl=new hl;class fl{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,s)=>{const n=new Image;n.onload=()=>{const e=document.createElement("canvas");e.width=n.width,e.height=n.height;const s=e.getContext("2d");s.drawImage(n,0,0);const i=s.getImageData(0,0,n.width,n.height);t({width:n.width,height:n.height,pixels:new Uint8Array(i.data.buffer)})},n.onerror=s,n.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function ml(e,t){try{const s=function(e){const t=atob(e),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(s.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}const gl=[Ji,co,_o,zo,Go,To,Qo,nr,cr,Vo,Fo,dr,mr,xr,vr,Er,Rr],yl=[...gl,$a,Ga,tl,il,On];function _l(e,t){return function(e,t){const s=ai.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Ys(e),At(e),dn(e),Sn(e),jn(e),qn(e);const i=new Qn;s.setPipeline(i);let o=c();const r=t?.getViewportSize??(()=>{const e=u();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=pi(e,n,t,i));const r=s.getResource(vt);if(o.length>0){const e=o[0],s=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(s.x*t),r.vpY=Math.round((1-s.y-s.h)*i),r.vpW=Math.round(s.w*t),r.vpH=Math.round(s.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}s.insertResource(vt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},d={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;Yn.setClearColor(e.x,e.y,e.z,e.w)}const d=(c()-o)/1e3;let h;if(Yn.resize(t,l),s.hasResource(ni)){const e=s.getResource(ni).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const p=pi(e,n,t,l,s.world,h);if(a(t,l,p),0===p.length)i.render({registry:{_cpp:n},viewProjection:ci,width:t,height:l,elapsed:d});else{i.beginScreenCapture();for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:d,cameraEntity:e.entity})}i.endScreenCapture(),Yn.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,d),s.addPlugin(Fs),s.addPlugin(Os),s.addPlugin(bt),s.addPlugin(ri),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:yl,...t})}class xl{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return o(this.resolvePath_(e))}async readBinary(e){const t=await i(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function wl(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function bl(e,t){try{return await e({instantiateWasm:wl(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}k||(k=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await f(s,n);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return m(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?s[n++]=i:i<2048?(s[n++]=192|i>>6,s[n++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,s[n++]=240|i>>18,s[n++]=128|i>>12&63,s[n++]=128|i>>6&63,s[n++]=128|63&i):(s[n++]=224|i>>12,s[n++]=128|i>>6&63,s[n++]=128|63&i)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=B,exports.Added=function(e){return{_filterType:"added",_component:e}},exports.AnimationPlugin=za,exports.App=ai,exports.AssetPlugin=Is,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=As,exports.Assets=Rs,exports.AsyncCache=Ot,exports.Audio=qt,exports.AudioBus=d,exports.AudioListener=Xa,exports.AudioMixer=class{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new d(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new d(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new d(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new d(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new d(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new d(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}},exports.AudioPlugin=Ya,exports.AudioPool=class{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}},exports.AudioSource=ja,exports.BitmapText=ge,exports.BodyType=Ae,exports.BoxCollider=Te,exports.Button=fo,exports.ButtonState=po,exports.Camera=de,exports.Canvas=he,exports.CapsuleCollider=Ee,exports.Changed=function(e){return{_filterType:"changed",_component:e}},exports.Children=me,exports.CircleCollider=Ce,exports.ClearFlags=oe,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=at,exports.DEFAULT_DESIGN_HEIGHT=D,exports.DEFAULT_DESIGN_WIDTH=L,exports.DEFAULT_FALLBACK_DT=W,exports.DEFAULT_FIXED_TIMESTEP=$,exports.DEFAULT_FONT_FAMILY="Arial",exports.DEFAULT_FONT_SIZE=24,exports.DEFAULT_GRAVITY=z,exports.DEFAULT_LINE_HEIGHT=1.2,exports.DEFAULT_MAX_DELTA_TIME=.5,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_SPINE_SKIN="default",exports.DEFAULT_SPRITE_SIZE=U,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.DragPlugin=Jo,exports.DragState=Ko,exports.Draggable=qo,exports.Draw=Js,exports.Dropdown=wr,exports.DropdownPlugin=br,exports.EasingType=ya,exports.EmitterShape=_e,exports.EntityCommands=rt,exports.EventReader=function(e){return{_type:"event_reader",_event:e}},exports.EventReaderInstance=dt,exports.EventRegistry=ct,exports.EventWriter=function(e){return{_type:"event_writer",_event:e}},exports.EventWriterInstance=ut,exports.FillDirection=vi,exports.FillMethod=Bo,exports.FillOrigin=Lo,exports.FocusManager=Ro,exports.FocusManagerState=Ao,exports.FocusPlugin=ur,exports.Focusable=Eo,exports.FrameHistory=class{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,s){const n={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:s?new Map(s):new Map};this.count_<this.capacity_?(this.buffer_.push(n),this.count_++):this.buffer_[this.cursor_]=n,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}},exports.GLDebug=Jn,exports.Geometry=fn,exports.GetWorld=pt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=j,exports.INVALID_MATERIAL=0,exports.INVALID_TEXTURE=N,exports.Image=Do,exports.ImagePlugin=Wo,exports.ImageType=ko,exports.Input=xt,exports.InputPlugin=wt,exports.InputState=_t,exports.Interactable=uo,exports.LayoutGroupPlugin=Cr,exports.ListView=gr,exports.ListViewPlugin=_r,exports.LocalTransform=le,exports.Logger=ma,exports.LoopMode=xa,exports.Material=Ft,exports.MaterialLoader=Ht,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ve,exports.Parent=fe,exports.Particle=Za,exports.ParticleEasing=we,exports.ParticleEmitter=be,exports.ParticlePlugin=el,exports.Physics=ta,exports.PhysicsEvents=Yr,exports.PhysicsPlugin=Jr,exports.PostProcess=Tn,exports.PostProcessPlugin=$n,exports.PostProcessStack=wn,exports.PostProcessVolume=Pe,exports.PrefabServer=Ws,exports.Prefabs=zs,exports.PrefabsPlugin=$s,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(ni);t.register({name:da,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(da),this.loadPromise_=t.load(da).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 ua(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await aa({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:da})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([de]);for(const n of s){if(e.get(n,de).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=1.7777777777777777;const n=e.getEntitiesWithComponents([he]);for(const i of n){const n=e.get(i,he);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(ni).getScene(da),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,ae,r);const a={isActive:!0,projectionType:ie.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:oe.ColorAndDepth};e.insert(o,de,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ni);await e.switchTo(da),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=jo,exports.ProgressBarDirection=No,exports.ProgressBarPlugin=Yo,exports.ProjectionType=ie,exports.Query=nt,exports.QueryInstance=it,exports.Removed=function(e){return{_type:"removed",_component:e}},exports.RemovedQueryInstance=ot,exports.RenderPipeline=Qn,exports.RenderTexture=ha,exports.Renderer=Yn,exports.Res=Fe,exports.ResMut=ke,exports.RigidBody=Me,exports.RuntimeConfig=O,exports.SafeArea=hr,exports.SafeAreaPlugin=fr,exports.ScaleMode=re,exports.SceneManager=ni,exports.SceneManagerState=si,exports.SceneOwner=Se,exports.ScrollView=Zo,exports.ScrollViewPlugin=sr,exports.ShaderSources=$t,exports.SimulationSpace=xe,exports.Slider=or,exports.SliderDirection=ir,exports.SliderPlugin=lr,exports.SpineAnimation=ye,exports.Sprite=ue,exports.SpriteAnimator=Yt,exports.Stats=cl,exports.StatsCollector=dl,exports.StatsOverlay=al,exports.StatsPlugin=hl,exports.Storage=We,exports.SystemRunner=yt,exports.Text=Yi,exports.TextAlign=Ni,exports.TextInput=Co,exports.TextInputPlugin=Io,exports.TextOverflow=Xi,exports.TextPlugin=Ki,exports.TextRenderer=Gi,exports.TextVerticalAlign=ji,exports.Tilemap=as,exports.TilemapAPI=rs,exports.TilemapLayer=ls,exports.TilemapPlugin=nl,exports.Time=De,exports.Toggle=$o,exports.TogglePlugin=Ho,exports.Transform=ae,exports.Tween=Wa,exports.TweenHandle=Ia,exports.TweenState=_a,exports.TweenTarget={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12},exports.UICameraInfo=vt,exports.UIEventQueue=mo,exports.UIEvents=go,exports.UIInteraction=ho,exports.UIInteractionPlugin=Mo,exports.UILayoutPlugin=yo,exports.UIMask=eo,exports.UIMaskPlugin=lo,exports.UIRect=Pi,exports.UIRenderOrderPlugin=Ar,exports.Velocity=pe,exports.WeChatAssetProvider=xl,exports.WebAssetProvider=ua,exports.World=Je,exports.WorldTransform=ce,exports.addStartupSystem=function(e){gt().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){gt().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){gt().push({schedule:e,system:t})},exports.animationPlugin=$a,exports.applyBuildRuntimeConfig=V,exports.applyDirectionalFill=Ai,exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=O.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=O.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=O.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=O.canvasMatchWidthOrHeight)},exports.assetPlugin=Fs,exports.audioPlugin=Ga,exports.calculateAttenuation=Va,exports.calculatePanning=Na,exports.cleanupAllPostProcessVolumes=kn,exports.cleanupPostProcessVolume=Fn,exports.clearAnimClips=function(){jt.clear()},exports.clearDrawCallbacks=on,exports.clearTextureDimensionsCache=es,exports.clearTilemapSourceCache=function(){Jt.clear()},exports.clearUserComponents=function(){const e=q();for(const t of e.keys())ee.delete(t);e.clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeFillAnchors=Ei,exports.computeFillSize=function(e,t,s,n){switch(e){case vi.BottomToTop:case vi.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}},exports.computeHandleAnchors=function(e,t){switch(e){case vi.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case vi.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case vi.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=Si,exports.createMaskProcessor=ao,exports.createRuntimeSceneConfig=la,exports.createWebApp=_l,exports.debug=function(e,t,s){ga.debug(e,t,s)},exports.defaultFrameStats=ll,exports.defineComponent=K,exports.defineEvent=function(e){return{_id:Symbol(`Event_${e}`),_name:e}},exports.defineResource=Ie,exports.defineSystem=mt,exports.defineTag=function(e){const t=ee.get(e)??q().get(e);if(t)return t;const s=G(e,{});return q().set(e,s),ee.set(e,s),Q(e,{},!0),s},exports.dragPlugin=Qo,exports.dropdownPlugin=vr,exports.error=function(e,t,s){ga.error(e,t,s)},exports.extractAnimClipTexturePaths=Vt,exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ve]);for(const n of s){const s=e.get(n,ve);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=li,exports.focusPlugin=dr,exports.getAddressableType=function(e){return b(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of g)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return x},exports.getAllEffectDefs=function(){return Array.from(Cn.values())},exports.getAnimClip=function(e){return jt.get(e)},exports.getAssetBuildTransform=function(e){return b(e)?.buildTransform},exports.getAssetMimeType=function(e){return y[e.toLowerCase()]},exports.getAssetTypeEntry=b,exports.getComponent=se,exports.getComponentAssetFieldDescriptors=_s,exports.getComponentAssetFields=ys,exports.getComponentDefaults=function(e){const t=se(e);return t?X(t._default):null},exports.getComponentEntityFields=bs,exports.getComponentSpineFieldDescriptor=xs,exports.getCustomExtensions=S,exports.getEditorType=function(e){return b(e)?.editorType??"unknown"},exports.getEffectDef=An,exports.getEffectTypes=function(){return Array.from(Cn.keys())},exports.getLogger=function(){return ga},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getTextureDimensions=Zt,exports.getTilemapSource=ss,exports.getUserComponent=J,exports.getWeChatPackOptions=function(){return S().map(e=>({type:"suffix",value:e}))},exports.imagePlugin=zo,exports.info=function(e,t,s){ga.info(e,t,s)},exports.initDrawAPI=Ys,exports.initGLDebugAPI=qn,exports.initGeometryAPI=dn,exports.initMaterialAPI=At,exports.initParticleAPI=Ja,exports.initPlayableRuntime=async function(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(Rs);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await ml(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await ml(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new fl(n);await ca({app:t,module:s,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()},exports.initPostProcessAPI=Sn,exports.initRendererAPI=jn,exports.initRuntime=ca,exports.initTilemapAPI=is,exports.initTweenAPI=Ba,exports.initWeChatRuntime=async function(e){const t=await o("asset-manifest.json"),s=JSON.parse(t),n=function(e){const{assetIndex:t,pathIndex:s}=e;return e=>{const n=M(e),i=t[e]||t[n]||s[n]||s[e];return i?i.path:n}}(function(e){const t={},s={};for(const n in e.groups){const i=e.groups[n];for(const e in i.assets){const n=i.assets[e];t[e]=n,s[n.path]=n}}return{assetIndex:t,pathIndex:s}}(s)),i=wx.createCanvas(),r=wx.getSystemInfoSync();i.width=r.windowWidth*r.pixelRatio,i.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:i,instantiateWasm:wl("esengine.wasm")}),l=i.getContext("webgl2")||i.getContext("webgl");if(!l)return void console.error("[ESEngine] Failed to create WebGL context");const c=a.GL.registerContext(l,{majorVersion:0===l.getParameter(l.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),u=_l(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&V(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await bl(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await bl(e.physicsFactory,"physics.wasm"));const p=new xl(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await ca({app:u,module:a,provider:p,scenes:f,firstScene:e.firstScene,spineModule:d,physicsModule:h,physicsConfig:e.physicsConfig,manifest:s,aspectRatio:i.width/i.height}),u.run()},exports.inputPlugin=bt,exports.instantiatePrefab=ks,exports.intersectRects=to,exports.invertMatrix4=so,exports.isBuiltinComponent=Z,exports.isCustomExtension=P,exports.isEditor=bo,exports.isKnownAssetExtension=v,exports.isPlatformInitialized=function(){return null!==e},exports.isPlayMode=vo,exports.isRuntime=function(){return!xo},exports.isTextureRef=Pt,exports.isWeChat=s,exports.isWeb=function(){return"web"===e?.name},exports.layoutGroupPlugin=Er,exports.listViewPlugin=xr,exports.loadComponent=Cs,exports.loadPhysicsModule=Ir,exports.loadRuntimeScene=aa,exports.loadSceneData=Ps,exports.loadSceneWithAssets=Ms,exports.loadTiledMap=function(e,t,s,n={}){const i=[],o=t.tilesets[0];let r=0;for(const n of t.layers){if(!n.visible)continue;const a=e.spawn();e.insert(a,ae,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,ls,{width:n.width,height:n.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(n.tiles),tint:{...n.tintColor},opacity:n.opacity,visible:n.visible,parallaxFactor:{x:n.parallaxX,y:n.parallaxY}}),i.push(a),r++}if(!1!==n.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,n){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=s+a+.5*t.width,u=n+(o-l)-.5*t.height,d=-t.rotation*fs;if(e.insert(r,ae,{position:{x:c,y:u,z:0}}),e.insert(r,Me,{bodyType:Ae.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Ce,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,n=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<s&&(s=r),r>i&&(i=r),a<n&&(n=a),a>o&&(o=a)}const a=i-s,l=o-n,c=.5*(s+i),u=.5*(n+o);e.insert(r,Te,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Te,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,ae,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...s)}const a=new Set(n.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const s of t.layers){if(!s.visible)continue;const n=ms(e,s,t,a,0,0);i.push(...n)}return i},exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&v(w(e)))},exports.parseAnimClipData=Nt,exports.parseTiledMap=async function(e,t){const s=ns;if(!s)return null;const n=new TextEncoder,i=n.encode(e),o=s._malloc(i.byteLength);s.HEAPU8.set(i,o);const r=s.tiled_loadMap(o,i.byteLength);if(s._free(o),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=s.tiled_getExternalTilesetSource(r,i);if(!t)return s.tiled_freeMap(r),null;const o=await t(e),a=n.encode(o),l=s._malloc(a.byteLength);s.HEAPU8.set(a,l);const c=s.tiled_loadExternalTileset(r,i,l,a.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const i={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=s.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=s.tiled_getLayerWidth(r,e),n=s.tiled_getLayerHeight(r,e),o=t*n,a=2*o,l=s._malloc(a);s.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(s.HEAPU8.buffer,l,o)),s._free(l),i.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:n,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?cs(s.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:s.tiled_getLayerParallaxX(r,e),parallaxY:s.tiled_getLayerParallaxY(r,e)})}const a=s.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:s.tiled_getTilesetName(r,e),image:s.tiled_getTilesetImage(r,e),tileWidth:s.tiled_getTilesetTileWidth(r,e),tileHeight:s.tiled_getTilesetTileHeight(r,e),columns:s.tiled_getTilesetColumns(r,e),tileCount:s.tiled_getTilesetTileCount(r,e)});return s.tiled_freeMap(r),i}catch{return s.tiled_freeMap(r),null}},exports.parseTmjJson=hs,exports.particlePlugin=tl,exports.platformFetch=n,exports.platformFileExists=r,exports.platformInstantiateWasm=a,exports.platformReadFile=i,exports.platformReadTextFile=o,exports.pointInOBB=function(e,t,s,n,i,o,r,a,l,c){const u=io(l,c),d=Math.sin(-u),h=Math.cos(-u),p=e-s,f=t-n,m=p*h-f*d+s,g=p*d+f*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)},exports.pointInWorldRect=function(e,t,s,n,i,o,r,a){return e>=s-i*r&&e<=s+i*(1-r)&&t>=n-o*a&&t<=n+o*(1-a)},exports.postProcessPlugin=On,exports.prefabsPlugin=Os,exports.progressBarPlugin=Go,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerAnimClip=Xt,exports.registerAssetBuildTransform=function(e,t){for(const s of g)s.editorType===e&&(s.buildTransform=t)},exports.registerComponent=te,exports.registerComponentAssetFields=function(e,t){gs.set(e,t)},exports.registerComponentEntityFields=function(e,t){ws.set(e,t)},exports.registerDrawCallback=sn,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(Rs);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=zt,exports.registerTextureDimensions=Qt,exports.registerTilemapSource=ts,exports.remapEntityFields=vs,exports.resolveRelativePath=ps,exports.safeAreaPlugin=mr,exports.sceneManagerPlugin=ri,exports.screenToWorld=no,exports.scrollViewPlugin=nr,exports.setEditorMode=function(e){xo=e},exports.setListViewRenderer=function(e,t){if(!yr)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=yr.get(e);s?s.renderer=t:yr.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})},exports.setLogLevel=function(e){ga.setMinLevel(e)},exports.setPlayMode=function(e){wo=e},exports.setWasmErrorHandler=Ve,exports.shutdownDrawAPI=Gs,exports.shutdownGLDebugAPI=Kn,exports.shutdownGeometryAPI=hn,exports.shutdownMaterialAPI=Rt,exports.shutdownParticleAPI=Qa,exports.shutdownPostProcessAPI=Pn,exports.shutdownRendererAPI=Xn,exports.shutdownTilemapAPI=os,exports.shutdownTweenAPI=La,exports.sliderPlugin=cr,exports.spriteAnimatorSystemUpdate=Gt,exports.statsPlugin=pl,exports.syncFillSpriteSize=function(e,t,s,n,i,o){if(!e.has(t,ue))return;const r=e.get(t,ue);let a,l;switch(s){case vi.BottomToTop:case vi.TopToBottom:a=i,l=o*n;break;default:a=i*n,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,ue,r))},exports.syncPostProcessVolume=function(e,t){let s=Rn.get(e),n=In.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=Tn.createStack(),Rn.set(e,s)),n||(n=new Map,In.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=An(e.type);if(!t)continue;let i=n.get(e.type);void 0===i&&(i=t.factory(),n.set(e.type,i)),s.addPass(e.type,i);for(const n of t.uniforms){const t=e.uniforms[n.name]??n.defaultValue;s.setUniform(e.type,n.name,t)}}Tn.bind(e,s)}else if(s&&(Tn.unbind(e),s.destroy(),Rn.delete(e)),n){for(const e of n.values())Ft.releaseShader(e);In.delete(e)}},exports.textInputPlugin=Fo,exports.textPlugin=Ji,exports.tilemapPlugin=il,exports.toBuildPath=M,exports.togglePlugin=Vo,exports.transitionTo=async function(e,t,s){const n=e.getResource(ni);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=To,exports.uiLayoutPlugin=_o,exports.uiMaskPlugin=co,exports.uiPlugins=gl,exports.uiRenderOrderPlugin=Rr,exports.unregisterAnimClip=function(e){jt.delete(e)},exports.unregisterComponent=function(e){q().delete(e),ee.delete(e)},exports.unregisterDrawCallback=nn,exports.updateCameraAspectRatio=Es,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){ga.warn(e,t,s)},exports.wrapSceneSystem=ii,exports.wxFileExists=function(e){return new Promise(t=>{C().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})},exports.wxFileExistsSync=A,exports.wxGetImagePixels=I,exports.wxLoadImage=R,exports.wxLoadImagePixels=F,exports.wxReadFile=function(e){return new Promise((t,s)=>{C().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(E(e,t.errMsg)))}})})},exports.wxReadTextFile=function(e,t="utf-8"){return new Promise((s,n)=>{C().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(E(e,t.errMsg)))}})})},exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{C().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 db57ed307..fba488472 100644
--- a/desktop/public/sdk/cjs/index.wechat.js
+++ b/desktop/public/sdk/cjs/index.wechat.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class y{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new y(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function w(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function x(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const b=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},S=new Map,M=new Set;for(const e of b)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function C(e){return T(e)?.editorType??"unknown"}function E(e){return T(e)?.addressableType??null}function A(e){for(const t of b)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function k(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function F(){const e=[];for(const t of b)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function z(e){return v[e.toLowerCase()]}function U(e){const t=T(e);return t?.wechatPackInclude??!1}function W(e){const t=T(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function $(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function D(e){return T(e)?.buildTransform}let L=null;function O(){return L||(L=wx.getFileSystemManager()),L}function H(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(U(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 j(e){return new Promise((t,n)=>{O().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(H(e,t.errMsg)))}})})}function V(e,t="utf-8"){return new Promise((n,s)=>{O().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(H(e,t.errMsg)))}})})}function N(e){return new Promise(t=>{O().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=O();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{O().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function q(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 G(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 K(e){return G(await q(e))}let J=!1;const Q=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return O().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return O().readFileSync(e,t)}(W(e))}async fileExists(e){return X(W(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch{}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch{}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch{}}},Z=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,de="default",he={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function fe(e){e.Text&&(e.Text._default.fontFamily=he.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=he.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=he.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=he.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(he.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(he.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(he.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(he.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(he.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");he.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(he.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(he.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(he.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(he.assetFailureCooldown=t.assetFailureCooldown)}const ge=0,ye=4294967295,_e=4294967295,we=0,xe=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function Pe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Pe);const t={};for(const n in e)t[n]=Pe(e[n]);return t}let Te=0;function Ce(e,t){const n=++Te,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?{...Pe(t),...e}:Pe(t):e?{...t,...e}:{...t}}}function Ee(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ae(e,t){const n=Ue.get(e)??Ee().get(e);if(n)return n;const s=Ce(e,t);return Ee().set(e,s),Ue.set(e,s),Be(e,t,!1),s}function Re(e){const t=Ue.get(e)??Ee().get(e);if(t)return t;const n=Ce(e,{});return Ee().set(e,n),Ue.set(e,n),Be(e,{},!0),n}function Ie(e){return Ee().get(e)}function ke(){const e=Ee();for(const t of e.keys())Ue.delete(t);e.clear()}function Fe(e){Ee().delete(e),Ue.delete(e)}function Be(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ze(e){return!0===e._builtin}const Ue=new Map;function We(e,t){Ue.set(e,t)}function $e(e){return Ue.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ue.set(e,n),n}const Le={Perspective:0,Orthographic:1},Oe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},He={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},je=De("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}}),Ve=je,Ne=je,Xe=De("Sprite",{texture:ye,color:{r:1,g:1,b:1,a:1},size:{x:se.x,y:se.y},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Ye=De("Camera",{projectionType:Le.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:Oe.ColorAndDepth}),qe=De("Canvas",{designResolution:{x:Z,y:ee},pixelsPerUnit:100,scaleMode:He.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ge=De("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ke=De("Parent",{entity:0}),Je=De("Children",{entities:[]}),Qe=De("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_e,enabled:!0}),Ze=De("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}),et={Point:0,Circle:1,Rectangle:2,Cone:3},tt={World:0,Local:1},nt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=De("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:et.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:nt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:nt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:tt.World,enabled:!0}),it=Ae("Name",{value:""}),ot=Ae("SceneOwner",{scene:"",persistent:!1}),rt=Ae("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function at(e){const t=$e(e);return t?Pe(t._default):null}const lt=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ct=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),dt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),ht={Static:0,Kinematic:1,Dynamic:2};let ft=0;function pt(e,t){const n=++ft;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function mt(e){return{_type:"res",_resource:e}}function gt(e){return{_type:"res_mut",_resource:e}}class yt{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 _t{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 yt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const wt=pt({delta:0,elapsed:0,frameCount:0},"Time"),xt="esengine:",bt={getString(e,n){const s=t().getStorageItem(xt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(xt+e,n)},getNumber(e,n){const s=t().getStorageItem(xt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(xt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(xt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(xt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(xt+e);if(null===s)return n;try{return JSON.parse(s)}catch{return n}},setJSON(e,n){t().setStorageItem(xt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(xt+e)},has:e=>null!==t().getStorageItem(xt+e),clear(){t().clearStorage(xt)}};function vt(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=St(t[e]),o=St(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function St(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Mt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Pt=null;function Tt(e){Pt=e}function Ct(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Pt&&Pt(e,t)}function Et(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 At=1;const Rt=new WeakMap;function It(e){let t=Rt.get(e);return void 0===t&&(t=At++,Rt.set(e,t)),t}const kt=[];function Ft(e,t=[],n=[]){kt.length=0;for(const t of e)kt.push(It(t));kt.sort((e,t)=>e-t);let s=kt.join(",");if(t.length>0){kt.length=0;for(const e of t)kt.push(It(e));kt.sort((e,t)=>e-t),s+="|+"+kt.join(",")}if(n.length>0){kt.length=0;for(const e of n)kt.push(It(e));kt.sort((e,t)=>e-t),s+="|-"+kt.join(",")}return s}class Bt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ct(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ct(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Ct(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ct(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ze(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ze(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Et(o))}catch(n){Ct(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 ze(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ze(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ze(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Ct(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.");ze(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=vt(t._name,s,i);if(e.length>0)throw new Error(Mt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Et(o))}catch(n){Ct(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return Ct(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 Ct(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ct(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=vt(t._name,t._default,e);if(i.length>0)throw new Error(Mt(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Ue)if(ze(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=Ee();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??Ft(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!ze(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function zt(e){return{_type:"mut",_component:e}}function Ut(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Wt(e){return{_filterType:"added",_component:e}}function $t(e){return{_filterType:"changed",_component:e}}function Dt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Lt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ot(e){return Ut(e)||Dt(e)||Lt(e)?e._component:e}function Ht(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Ut(e)&&s.push(t),Dt(e)?i.push({index:t,component:e._component}):Lt(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Ht(e,[...t,...s],n),without:(...s)=>Ht(e,t,[...n,...s])}}function jt(...e){return Ht(e)}class Vt{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Ot),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_=Ft(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of n)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Nt(e){return{_type:"removed",_component:e}}class Xt{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 Yt(){return{_type:"commands"}}class qt{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=ze(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 Gt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new qt(this,null);return this.spawned_.push(e),e}entity(e){return new qt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Kt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Jt{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 Qt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Jt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Jt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Zt(e){return{_type:"event_writer",_event:e}}function en(e){return{_type:"event_reader",_event:e}}class tn{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class nn{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var sn;function on(){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"}(sn||(sn={}));let rn=0;function an(e,t,n){const s=++rn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function ln(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function cn(e){ln().push({schedule:sn.Update,system:e})}function un(e){ln().push({schedule:sn.Startup,system:e})}function dn(e,t){ln().push({schedule:e,system:t})}class hn{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Gt&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Vt(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 Gt(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 tn(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new nn(n)}case"removed":{const t=e;return new Xt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class fn{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 pn=pt(new fn,"Input");class mn{constructor(e){this.target_=e??null}build(e){const n=new fn;e.insertResource(pn,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(sn.Last,an([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const gn=new mn,yn=pt({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var _n;function wn(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"}(_n||(_n={}));let xn=null,bn=null,vn=1;const Sn=new Map;function Mn(e){xn=e,bn=e.getResourceManager(),Bn()}function Pn(){0!==An&&xn&&(xn._free(An),An=0),Sn.clear(),vn=1,En=!1,In.clear(),kn=null,bn=null,xn=null}function Tn(){if(!bn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return bn}const Cn={createShader:(e,t)=>Tn().createShader(e,t),releaseShader(e){e>0&&Tn().releaseShader(e)},create(e){const t=vn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??_n.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 Sn.set(t,n),t},get:e=>Sn.get(e),setUniform(e,t,n){const s=Sn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,xn?.invalidateMaterialCache(e))},getUniform(e,t){const n=Sn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Sn.get(e);n&&(n.blendMode=t,xn?.invalidateMaterialCache(e))},getBlendMode(e){const t=Sn.get(e);return t?.blendMode??_n.Normal},setDepthTest(e,t){const n=Sn.get(e);n&&(n.depthTest=t,xn?.invalidateMaterialCache(e))},getShader(e){const t=Sn.get(e);return t?.shader??0},release(e){Sn.delete(e),xn?.invalidateMaterialCache(e)},isValid:e=>Sn.has(e),releaseAll(){Sn.clear(),xn?.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??_n.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Sn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=vn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Sn.set(n,s),n},toAssetData(e,t){const n=Sn.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=Sn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let En=!1,An=0;const Rn=16384,In=new Map;let kn=null;function Fn(e){const t=(0===An&&xn&&(An=xn._malloc(Rn)),An);if(0===t||!xn)return{ptr:0,count:0};let n=0,s=0;const i=xn.HEAPU8,o=xn.HEAPU32,r=xn.HEAPF32;for(const[a,l]of e){if(wn(l))continue;let e=In.get(a);e||(kn||(kn=new TextEncoder),e=kn.encode(a),In.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Rn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Rn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Bn(){if(!xn||En)return;xn.materialDataProvider=(e,t,n,s,i)=>{const o=Sn.get(e);if(!o)return xn.HEAPU32[t>>2]=0,xn.HEAPU32[n>>2]=0,xn.HEAPU32[s>>2]=0,void(xn.HEAPU32[i>>2]=0);xn.HEAPU32[t>>2]=o.shader,xn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Fn(o.uniforms);xn.HEAPU32[s>>2]=r,xn.HEAPU32[i>>2]=a},En=!0}const zn={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 Un{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=he.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.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&&(this.failed_.set(e,{error:t,expiry:Date.now()+he.assetFailureCooldown}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Wn{constructor(e,t=""){this.cache_=new Un,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&&(Cn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Cn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Cn.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function $n(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Dn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const Ln=new Map;function On(e){Ln.set(e.name,e)}function Hn(e){Ln.delete(e)}function jn(e){return Ln.get(e)}function Vn(){Ln.clear()}const Nn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Xn(e,t){const n=e.getEntitiesWithComponents([Nn]);for(const s of n){const n=e.get(s,Nn);if(!n.enabled||!n.playing||!n.clip)continue;const i=Ln.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,Xe)){const t=i.frames[n.currentFrame],o=e.get(s,Xe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Xe,o)}a&&e.insert(s,Nn,n)}}class Yn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}Yn.mixer_=null,Yn.bufferCache_=new Map,Yn.bgmHandle_=null,Yn.bgmVolume_=1,Yn.fadeAnimId_=0,Yn.disposed_=!1;const qn=new Map,Gn=new Map;function Kn(e,t,n){qn.set(e,{width:t,height:n})}function Jn(e){return qn.get(e)}function Qn(){qn.clear()}function Zn(e,t){Gn.set(e,t)}function es(e){return Gn.get(e)}function ts(){Gn.clear()}let ns=null;function ss(e){ns=e}function is(){ns=null}const os={initLayer(e,t,n,s,i){ns?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){ns?.tilemap_destroyLayer(e)},setTile(e,t,n,s){ns?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>ns?ns.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){ns?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!ns)return;const n=t.byteLength,s=ns._malloc(n);new Uint16Array(ns.HEAPU8.buffer,s,t.length).set(t),ns.tilemap_setTiles(e,s,t.length),ns._free(s)},hasLayer:e=>!!ns&&ns.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w){ns?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w)}},rs=Ae("Tilemap",{source:""}),as=Ae("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function ls(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function cs(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function us(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function ds(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=us(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=cs(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:f})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.properties;if(n)for(const s of n)"collision"===s.name&&!0===s.value&&d.push(e.id+t)}}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function hs(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function fs(e,t){const n=ns;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?ls(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}const ps=Math.PI/180;function ms(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,d=o+(u-t.row*c)-.5*s,h=e.spawn();e.insert(h,je,{position:{x:r,y:d,z:0}}),e.insert(h,lt,{bodyType:ht.Static}),e.insert(h,ct,{halfExtents:{x:.5*n,y:.5*s}}),a.push(h)}return a}function gs(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,je,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,as,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,d=-t.rotation*ps;if(e.insert(r,je,{position:{x:c,y:u,z:0}}),e.insert(r,lt,{bodyType:ht.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,ut,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ct,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ct,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,je,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=ms(e,n,t,a,0,0);i.push(...s)}return i}const ys=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function _s(e,t){ys.set(e,t)}function ws(e){const t=ys.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 xs(e){return ys.get(e)?.fields??[]}function bs(e){return ys.get(e)?.spine??null}const vs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ss(e,t){vs.set(e,t)}function Ms(e){return vs.get(e)}function Ps(e,t){const n=vs.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Ts(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,it,{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)Ps(i,n),Rs(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 Cs(e,t){return Ts(e,t)}async function Es(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of As.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ys.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...As.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ys.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Ts(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const As=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),Kn(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=$n(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);On(Dn(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Yn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=ds(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=hs(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),Kn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Zn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Rs(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=$e(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Is(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function ks(e,t){const n=e.getEntitiesWithComponents([it]);for(const s of n){const n=e.get(s,it);if(n&&n.value===t)return s}return null}class Fs{constructor(e){this.textureCache_=new Un,this.shaderCache_=new Un,this.jsonCache_=new Un,this.textCache_=new Un,this.binaryCache_=new Un,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Un,this.prefabCache_=new Un,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=d(he.textCanvasSize,he.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 Wn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Cn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===T(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=T(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of ws(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=bs(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Es(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Cn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Cn.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(W(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Bs=pt(null,"Assets");class zs{build(e){const t=e.wasmModule;t?e.insertResource(Bs,new Fs(t)):console.warn("AssetPlugin: No WASM module available")}}const Us=new zs;class Ws{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 $s(e,t){const n=e.getResource(Bs);n&&n.registerEmbeddedAssets(t)}async function Ds(e,t,n){const{entities:s,rootId:i}=await Os(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Es(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const Ls=10;async function Os(e,t,n,s,i,o=0){if(o>Ls)throw new Error(`Prefab nesting depth exceeded ${Ls}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Os(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Hs(d.components,r),js(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Hs(e,t){for(const n of e){const e=Ms(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 js(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 Vs{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 Ds(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ns=pt(null,"Prefabs");class Xs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Bs]}build(e){const t=e.getResource(Bs);e.insertResource(Ns,new Vs(e.world,t))}}const Ys=new Xs;let qs=null,Gs=0,Ks=0,Js=0;const Qs=new Float32Array(256);function Zs(e){qs=e,Gs=qs._malloc(64),Ks=qs._malloc(64),Js=qs._malloc(1024)}function ei(){qs&&(Gs&&(qs._free(Gs),Gs=0),Ks&&(qs._free(Ks),Ks=0),Js&&(qs._free(Js),Js=0)),qs=null}function ti(){if(!qs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return qs}const ni={r:1,g:1,b:1,a:1},si={begin(e){const t=ti();try{t.HEAPF32.set(e,Gs/4),t.draw_begin(Gs)}catch(e){Ct(e,"Draw.begin")}},end(){try{ti().draw_end()}catch(e){Ct(e,"Draw.end")}},line(e,t,n,s=1){try{ti().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.line")}},rect(e,t,n,s=!0){try{ti().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{ti().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{ti().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ct(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{ti().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ct(e,"Draw.circleOutline")}},texture(e,t,n,s=ni){try{ti().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ct(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ni){try{ti().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Ct(e,"Draw.textureRotated")}},setLayer(e){ti().draw_setLayer(e)},setDepth(e){ti().draw_setDepth(e)},getDrawCallCount:()=>qs?qs.draw_getDrawCallCount():0,getPrimitiveCount:()=>qs?qs.draw_getPrimitiveCount():0,setBlendMode(e){ti().draw_setBlendMode(e)},setDepthTest(e){ti().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ti();s.HEAPF32.set(n,Ks/4),s.draw_mesh(e,t,Ks)}catch(n){Ct(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ti(),i=Cn.get(t);if(!i)return;if(si.setBlendMode(i.blendMode),si.setDepthTest(i.depthTest),0===i.uniforms.size)return void si.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Ks/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ri(t);if(!(s<0)){if(wn(n))Qs[o++]=10,Qs[o++]=s,Qs[o++]=n.slot??e++,Qs[o++]=n.textureId;else if("number"==typeof n)Qs[o++]=1,Qs[o++]=s,Qs[o++]=n;else if(Array.isArray(n)){Qs[o++]=n.length,Qs[o++]=s;for(let e=0;e<n.length;e++)Qs[o++]=n[e]}else"w"in n?(Qs[o++]=4,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y,Qs[o++]=n.z,Qs[o++]=n.w):"z"in n?(Qs[o++]=3,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y,Qs[o++]=n.z):(Qs[o++]=2,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(Qs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Ks);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Js/4),s.draw_meshWithUniforms(e,i.shader,Ks,Js,o)}catch(n){Ct(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ii={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},oi=new Set;function ri(e){const t=ii[e];return void 0!==t?t:(oi.has(e)||(oi.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ii).join(", ")}`)),-1)}const ai=new Map;function li(e,t,n){ai.set(e,{fn:t,scene:n??""})}function ci(e){ai.delete(e)}function ui(){ai.clear()}var di;!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"}(di||(di={}));let hi=null,fi=0,pi=0,mi=0;function gi(e){hi=e,fi=hi._malloc(262144),pi=hi._malloc(65536),mi=hi._malloc(256)}function yi(){hi&&(fi&&hi._free(fi),pi&&hi._free(pi),mi&&hi._free(mi),fi=0,pi=0,mi=0),hi=null}function _i(){if(!hi)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return hi}const wi={create(e){const t=_i(),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,fi/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,mi,i).set(o),t.geometry_init(n,fi,s,mi,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,pi,s).set(e.indices),t.geometry_setIndices16(n,pi,s)}else{new Uint32Array(t.HEAPU8.buffer,pi,s).set(e.indices),t.geometry_setIndices32(n,pi,s)}}return n},updateVertices(e,t,n=0){const s=_i(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,fi/4),s.geometry_updateVertices(e,fi,i,n)},release(e){e>0&&_i().geometry_release(e)},isValid:e=>!(!hi||e<=0)&&hi.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return wi.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:di.Float2},{name:"a_texCoord",type:di.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return wi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:di.Float2},{name:"a_texCoord",type:di.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return wi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:di.Float2},{name:"a_texCoord",type:di.Float2}],indices:new Uint16Array(r)})}};let xi=1;const bi=new Map,vi=new Map;function Si(){return bi}function Mi(){return vi}class Pi{constructor(){this.passes_=[],this.destroyed_=!1,this.id=xi++,bi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of vi)t===this&&vi.delete(e);bi.delete(this.id)}}}const Ti="#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";let Ci=null;function Ei(e){Ci=e}function Ai(){for(const e of Si().values())e.destroy();Si().clear(),Mi().clear(),Ci&&Ii.isInitialized()&&Ii.shutdown(),Ci=null}function Ri(){if(!Ci)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ci}const Ii={createStack:()=>new Pi,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");Mi().set(e,t)},unbind(e){Mi().delete(e)},getStack:e=>Mi().get(e)??null,init(e,t){try{return Ri().postprocess_init(e,t)}catch(n){return Ct(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ri().postprocess_shutdown()}catch(e){Ct(e,"PostProcess.shutdown")}},resize(e,t){try{Ri().postprocess_resize(e,t)}catch(n){Ct(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Ci)return!1;try{return Ci.postprocess_isInitialized()}catch(e){return Ct(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ri().postprocess_setBypass(e)}catch(e){Ct(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{Ri().postprocess_setOutputViewport(e,t,n,s)}catch(e){Ct(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=Mi().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Ii.isInitialized()||Ii.init(1,1),Ii.setBypass(!1),function(e){const t=Ri();try{t.postprocess_clearPasses()}catch(e){return void Ct(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Ct(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Ct(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Ct(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Ii.setBypass(!0)},_resetAfterCamera(){try{Ri().postprocess_clearPasses(),Ri().postprocess_setBypass(!0)}catch(e){Ct(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of Mi().keys())e(t)||Mi().delete(t)},screenStack:null,setScreenStack(e){Ii.screenStack=e},_beginScreenCapture(){try{Ri().postprocess_beginScreenCapture()}catch(e){Ct(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ri().postprocess_endScreenCapture()}catch(e){Ct(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Ii.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ri();try{t.postprocess_clearScreenPasses()}catch(e){return void Ct(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Ct(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Ct(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Ct(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ri().postprocess_executeScreenPasses()}catch(e){Ct(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Cn.createShader(Ti,"#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:()=>Cn.createShader(Ti,"#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:()=>Cn.createShader(Ti,"#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"),createBloom:()=>Cn.createShader(Ti,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Cn.createShader(Ti,"#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")},ki=new Map;function Fi(e){ki.set(e.type,e)}function Bi(e){return ki.get(e)}function zi(){return Array.from(ki.keys())}function Ui(){return Array.from(ki.values())}Fi({type:"blur",label:"Blur",factory:()=>Ii.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Fi({type:"bloom",label:"Bloom",factory:()=>Ii.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Fi({type:"vignette",label:"Vignette",factory:()=>Ii.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Fi({type:"grayscale",label:"Grayscale",factory:()=>Ii.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Fi({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Ii.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Wi=new Map,$i=new Map;function Di(e,t){let n=Wi.get(e),s=$i.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=Ii.createStack(),Wi.set(e,n)),s||(s=new Map,$i.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=Bi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Ii.bind(e,n)}else if(n&&(Ii.unbind(e),n.destroy(),Wi.delete(e)),s){for(const e of s.values())Cn.releaseShader(e);$i.delete(e)}}function Li(e){const t=Wi.get(e);t&&(Ii.unbind(e),t.destroy(),Wi.delete(e));const n=$i.get(e);if(n){for(const e of n.values())Cn.releaseShader(e);$i.delete(e)}}function Oi(){for(const e of Wi.keys())Li(e)}const Hi=pt({enabled:!0},"PostProcessVolumeConfig"),ji=new Map,Vi=new Map;function Ni(e){const t=Vi.get(e);if(void 0!==t)return t;const n=Bi(e);if(!n)return null;const s=n.factory();return Vi.set(e,s),s}function Xi(e,t){if(0===t.size){const t=ji.get(e);return void(t&&(Ii.unbind(e),t.destroy(),ji.delete(e)))}let n=ji.get(e);for(n||(n=Ii.createStack(),ji.set(e,n));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const[e,s]of t){if(!s.enabled)continue;const t=Ni(e);if(null!==t){n.addPass(e,t);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?Ii.bind(e,n):Ii.unbind(e)}const Yi=an([jt(rt,je)],e=>{const t=[];for(const[n,s,i]of e)t.push({data:s,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const n=[];for(const{data:e,tx:s}of t)e.isGlobal&&n.push({data:e,factor:1});if(n.length>0){const e=function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(n);for(const[t]of ji)Xi(t,e)}},{name:"PostProcessVolumeSystem"});class qi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Hi,{enabled:!0}),e.addSystemToSchedule(sn.PostUpdate,Yi)}cleanup(){Oi(),function(){for(const[e,t]of ji)Ii.unbind(e),t.destroy();ji.clear();for(const e of Vi.values())Cn.releaseShader(e);Vi.clear()}(),Ii.setScreenStack(null)}}const Gi=new qi;var Ki;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ki||(Ki={}));let Ji=null,Qi=0;function Zi(e){Ji=e,Qi=Ji._malloc(64)}function eo(){Ji&&Qi&&(Ji._free(Qi),Qi=0),Ji=null}const to={init(e,t){Ji?.renderer_init(e,t)},resize(e,t){Ji?.renderer_resize(e,t)},begin(e,t){if(Ji&&Qi)try{Ji.HEAPF32.set(e,Qi/4),Ji.renderer_begin(Qi,t??0)}catch(e){Ct(e,"Renderer.begin")}},flush(){try{Ji?.renderer_flush()}catch(e){Ct(e,"Renderer.flush")}},end(){try{Ji?.renderer_end()}catch(e){Ct(e,"Renderer.end")}},submitSprites(e){if(Ji)try{Ji.renderer_submitSprites(e._cpp)}catch(e){Ct(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ji)try{Ji.renderer_submitBitmapText(e._cpp)}catch(e){Ct(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ji)try{Ji.renderer_submitSpine?.(e._cpp)}catch(e){Ct(e,"Renderer.submitSpine")}},submitParticles(e){if(Ji)try{Ji.renderer_submitParticles?.(e._cpp)}catch(e){Ct(e,"Renderer.submitParticles")}},setStage(e){Ji?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Ji?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Ji?.renderer_releaseTarget(e)},getTargetTexture:e=>Ji?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ji?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Ji?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Ji?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Ji?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Ji?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Ji?Ji.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Ji?{drawCalls:Ji.renderer_getDrawCalls(),triangles:Ji.renderer_getTriangles(),sprites:Ji.renderer_getSprites(),text:Ji.renderer_getText(),spine:Ji.renderer_getSpine?.()??0,meshes:Ji.renderer_getMeshes(),culled:Ji.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let no=null;function so(e){no=e}function io(){no=null}const oo={enable(){no?.gl_enableErrorCheck(!0)},disable(){no?.gl_enableErrorCheck(!1)},check:e=>no?.gl_checkErrors(e)??0,diagnose(){no?.renderer_diagnose()}};class ro{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Ii.screenStack&&Ii.screenStack.enabledPassCount>0&&(Ii.isInitialized()||Ii.init(1,1),Ii._applyScreenStack(),Ii._beginScreenCapture())}endScreenCapture(){Ii.screenStack&&Ii.screenStack.enabledPassCount>0&&(Ii._endScreenCapture(),Ii._executeScreenPasses())}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(to.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),to.setViewport(0,0,s,i),to.clearBuffers(3),to.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),to.submitSprites(t),to.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):to.submitSpine(t),to.submitParticles(t),to.flush(),this.executeDrawCallbacks(n,o),to.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Ii.getStack(r);a&&(Ii._applyForCamera(r),Ii.resize(s.w,s.h),Ii.setOutputViewport(s.x,s.y,s.w,s.h)),to.setViewport(s.x,s.y,s.w,s.h),to.setScissor(s.x,s.y,s.w,s.h,!0),to.clearBuffers(i),to.setScissor(0,0,0,0,!1),to.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),to.submitSprites(t),to.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):to.submitSpine(t),to.submitParticles(t),to.flush(),this.executeDrawCallbacks(n,o),to.end(),a&&Ii._resetAfterCamera()}executeDrawCallbacks(e,t){const n=ai;if(n.size>0){si.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)}si.end();for(const e of s)ci(e)}}}const ao="__scene_transition_overlay__";class lo{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class co{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,ot,{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),li(e,t,this.instance_.config.name)}bindPostProcess(e,t){Ii.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Ii.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ot)){const n=this.app_.world.get(e,ot);n.persistent=t,this.app_.world.insert(e,ot,n)}}}class uo{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())ci(t);for(const t of e.postProcessBindings.keys())Ii.unbind(t)}this.transition_&&(ci(ao),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??he.sceneTransitionDuration,i=t.color??{...he.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},li(ao,()=>{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;si.setLayer(9999),si.setDepth(9999),si.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,ci(ao),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ci(ao),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 lo(t);this.scenes_.set(e,n);const s=new co(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Bs)?this.app_.getResource(Bs):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 lo(t);this.scenes_.set(e,n);const s=new co(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Bs)?this.app_.getResource(Bs):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,ot)){if(this.app_.world.get(e,ot).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ci(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Ii.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Bs)&&(i.assetServer=this.app_.getResource(Bs));const o=await Es(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ot,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=fo(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(Bs)?this.app_.getResource(Bs):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)Cn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Xe)){const t=n.get(e,Xe);s.sprite=t.color.a,t.color.a=0,n.insert(e,Xe,t),i=!0}if(n.has(e,Ze)){const t=n.get(e,Ze);s.spine=t.color.a,t.color.a=0,n.insert(e,Ze,t),i=!0}if(n.has(e,Qe)){const t=n.get(e,Qe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Qe,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Xe)){const t=n.get(e,Xe);t.color.a=s.sprite,n.insert(e,Xe,t)}if(void 0!==s.spine&&n.has(e,Ze)){const t=n.get(e,Ze);t.color.a=s.spine,n.insert(e,Ze,t)}if(void 0!==s.bitmapText&&n.has(e,Qe)){const t=n.get(e,Qe);t.color.a=s.bitmapText,n.insert(e,Qe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}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 ho=pt(null,"SceneManager");function fo(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ho).getSceneStatus(t)&&n._fn(...s)}}}const po=an([gt(ho),mt(wt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),mo={name:"SceneManager",build(e){const t=new uo(e);e.insertResource(ho,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ho),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(sn.Startup,n),e.addSystemToSchedule(sn.Last,po)}};class go{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 Qt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(sn.Last);else{this.runSchedule(sn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(sn.FixedPreUpdate),this.runSchedule(sn.FixedUpdate),this.runSchedule(sn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(sn.PreUpdate),this.runSchedule(sn.Update),this.runSchedule(sn.PostUpdate),this.runSchedule(sn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Bt,this.resources_=new _t;for(const e of Object.values(sn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new go}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(sn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(sn.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Tt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ho).register(e),this}setInitialScene(e){return this.getResource(ho).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new hn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(wt)||this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(sn.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(sn.Last);else{this.runSchedule(sn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(sn.FixedPreUpdate),this.runSchedule(sn.FixedUpdate),this.runSchedule(sn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(sn.PreUpdate),this.runSchedule(sn.Update),this.runSchedule(sn.PostUpdate),this.runSchedule(sn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new hn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(sn.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,ui();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=[io,eo,Ai,yi,Pn,ei];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(sn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(wt);t.delta=e,t.elapsed+=e,t.frameCount++}}function yo(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const _o=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function wo(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case He.FixedWidth:return o;case He.FixedHeight:return r;case He.Expand:return Math.max(o,r);case He.Shrink:return Math.min(o,r);case He.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const xo=[];function bo(e){if(e<xo.length)return xo[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 xo.push(t),t}function vo(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,ot);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,d=0;if(i.projectionType===Le.Orthographic){if(d=i.orthoSize,l){d=wo(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=Mo(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=To(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Eo(o.position.x,o.position.y,o.position.z),f=bo(c.length);f.entity=e,f.viewProjection.set(Ro(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=d,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const So=new Float32Array(16);function Mo(e,t,n,s,i,o){const r=So;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const Po=new Float32Array(16);function To(e,t,n,s){const i=Po;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const Co=new Float32Array(16);function Eo(e,t,n){const s=Co;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 Ao=new Float32Array(16);function Ro(e,t){const n=Ao;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 Io={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ko(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Fo=De("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 Bo=null,zo=null;function Uo(e,t){e.has(t,Xe)||e.insert(t,Xe,{texture:ye,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 Wo(e,t){switch(e){case Io.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Io.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Io.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 $o(e,t){switch(e){case Io.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Io.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Io.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 Do(e,t,n,s){switch(e){case Io.BottomToTop:case Io.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Lo(e,t,n,s){if(!e.has(t,Fo))return;const i=e.get(t,Fo),o=Wo(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Fo,i)}function Oo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ho(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function jo(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Ho(r.charCodeAt(0))&&s.length>0&&Ho(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Ho(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Vo(e){let t=1;for(;t<e;)t*=2;return t}function No(e,t){let n=0,s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;n++,s=t}return n}function Xo(e,t){if(Bo&&zo){const e=Bo.getUIRectComputedWidth(zo,t);if(e>0)return e}return e.size.x}function Yo(e,t){if(Bo&&zo){const e=Bo.getUIRectComputedHeight(zo,t);if(e>0)return e}return e.size.y}function qo(e,t,n,s,i,o){if(!e.has(t,Xe))return;const r=e.get(t,Xe);let a,l;switch(n){case Io.BottomToTop:case Io.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Xe,r))}function Go(e,t,n){let s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ko(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Jo(e,t,n,s,i){if(!e.has(t,Fo))return;const o=e.get(t,Fo),r=ko(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Xe,n))}if(e.has(t,je)){const n=e.get(t,je);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,je,n)}}function Qo(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 Zo=.1,er=30,tr={r:.3,g:.5,b:.8,a:1},nr={Left:0,Center:1,Right:2},sr={Top:0,Middle:1,Bottom:2},ir={Visible:0,Clip:1,Ellipsis:2},or=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:nr.Left,verticalAlign:sr.Top,wordWrap:!0,overflow:ir.Visible,lineHeight:1.2});class rr{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(he.textCanvasSize,he.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,Vo(this.frameMaxW_)),e.height=Math.max(e.height,Vo(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Vo(this.frameMaxW_),e.height=Vo(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=jo(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===ir.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Vo(f)),s.height=Math.max(s.height,Vo(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===ir.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 sr.Top:x=u;break;case sr.Middle:x=u+(p-2*u-w)/2;break;case sr.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let b=x;for(const t of l){let s;switch(e.align){case nr.Left:s=u;break;case nr.Center:s=f/2;break;case nr.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===ir.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.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 nr.Left:return"left";case nr.Center:return"center";case nr.Right:return"right"}}}const ar=Qo({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?Xo(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0});class lr{build(e){We("Text",or);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new rr(t),s=e.world,i=new Map;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,or));for(const e of i.keys())if(!s.valid(e)||!s.has(e,or)){if(s.valid(e)&&s.has(e,Xe)){const t=s.get(e,Xe);s.insert(e,Xe,{texture:ye,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([or]);for(const t of e){const e=s.get(t,or),o=s.has(t,Fo)?s.get(t,Fo):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ar.changed(a,r)){if(s.has(t,Xe)&&s.get(t,Xe).texture!==ye)continue}Uo(s,t);const l=o?{size:{x:Xo(o,t),y:Yo(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Xe);s.insert(t,Xe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,ar.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const cr=new lr,ur=0,dr=1,hr=De("UIMask",{enabled:!0,mode:ur});function fr(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function pr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-i*a,x=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=d*g-h*m,T=d*y-f*m,C=d*_-p*m,E=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let I=w*R-x*A+b*E+v*C-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*E)*I,n[1]=(o*A-i*R-r*E)*I,n[2]=(g*M-y*S+_*v)*I,n[3]=(f*S-h*M-p*v)*I,n[4]=(c*C-a*R-u*T)*I,n[5]=(s*R-o*C+r*T)*I,n[6]=(y*b-m*M-_*x)*I,n[7]=(d*M-f*b+p*x)*I,n[8]=(a*A-l*C+u*P)*I,n[9]=(i*C-s*A-r*P)*I,n[10]=(m*S-g*b+_*w)*I,n[11]=(h*b-d*S-p*w)*I,n[12]=(l*T-a*E-c*P)*I,n[13]=(s*E-i*T+o*P)*I,n[14]=(g*x-m*v-y*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function mr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function gr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function yr(e,t){return 2*Math.atan2(e,t)}function _r(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function wr(e,t,n,s,i,o,r,a,l,c){const u=yr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function xr(e,t,n,s,i,o,r){if(!e.has(t,Fo)||!e.has(t,je))return null;const a=e.get(t,Fo),l=e.get(t,je),c=Xo(a,t)*l.worldScale.x,u=Yo(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),y=-u*p,_=u*(1-p),w=yr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),b=Math.sin(w),v=[[d+m*x-y*b,h+m*b+y*x],[d+g*x-y*b,h+g*b+y*x],[d+g*x-_*b,h+g*b+_*x],[d+m*x-_*b,h+m*b+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=_r(e,t,n,s,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function br(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([hr]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,hr);n.enabled&&(d.add(e),n.mode===dr?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;Go(t,e,e=>{if(i.has(e)){if(t.get(e,hr).mode===ur)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,hr).mode===ur){const e=xr(t,n,o,r,a,l,c);e&&(s=fr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=xr(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Go(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class vr{build(e){if(We("UIMask",hr),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(br(e.wasmModule,e.world))}}const Sr=new vr,Mr=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Pr=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Tr={Normal:0,Hovered:1,Pressed:2,Disabled:3},Cr=Ae("Button",{state:Tr.Normal,transition:null});class Er{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 Ar=pt(new Er,"UIEvents");class Rr{build(e){We("UIRect",Fo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Bo=e,zo=t}(n,s);e.addSystemToSchedule(sn.PreUpdate,an([mt(yn)],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(sn.PostUpdate,an([mt(yn)],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(sn.PostUpdate,an([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ir=new Rr;let kr=!1,Fr=!1;function Br(e){kr=e}function zr(){return kr}function Ur(){return!kr}function Wr(e){Fr=e}function $r(){return Fr}const Dr=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&&(pr(t,e),n=!1),e)}}();function Lr(e,t,n,s){t.emit(n,s,n),Go(e,n,i=>{if(!e.has(i,Mr))return!1;const o=e.get(i,Mr);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Or{build(e){We("Interactable",Mr),We("Button",Cr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Er;e.insertResource(Ar,i);let o=null,r=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn)],(e,a)=>{if(i.drain(),zr()&&!$r())return;const l=t.getEntitiesWithComponents([Pr]);for(const e of l){const n=t.get(e,Pr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Pr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;Dr.update(a.viewProjection);const h=mr(u,d,Dr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,h.x,h.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Pr)){const e=t.get(o,Pr);e.hovered=!1,t.insert(o,Pr,e),i.emit(o,"hover_exit")}if(null!==_){Ko(t,_,Pr);const e=t.get(_,Pr);e.hovered=!0,t.insert(_,Pr,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Pr);e.pressed=!0,e.justPressed=!0,t.insert(_,Pr,e),r=_,Lr(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Pr)){const e=t.get(r,Pr);e.pressed=!1,e.justReleased=!0,t.insert(r,Pr,e),Lr(t,i,r,"release"),r===o&&Lr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(sn.Update,an([],()=>{const e=t.getEntitiesWithComponents([Cr]);for(const n of e){if(Ko(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const e=t.get(n,Pr),s=t.get(n,Cr),i=t.get(n,Mr),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Tr.Pressed:e.hovered?s.state=Tr.Hovered:s.state=Tr.Normal:s.state=Tr.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Xe)){const o=t.get(n,Xe);o.color=Oo(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Xe,o)}}},{name:"ButtonSystem"}))}}const Hr=new Or,jr=Ae("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Vr=Ae("Focusable",{tabIndex:0,isFocused:!1});class Nr{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 Xr=pt(new Nr,"FocusManager");class Yr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(We("TextInput",jr),zr()&&!$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=d(he.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Xr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,jr)?s:null}const g=()=>{l||null===m()||b()},y=()=>{l=!0},_=()=>{l=!1,b()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void v();const i=n.get(s,jr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ar).emit(s,"submit"),void v()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const s=n.get(t,jr);s.focused=!1,s.dirty=!0;e.getResource(Xr).blur()}};function b(){const t=m();if(null===t)return;const s=n.get(t,jr);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(Ar).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=n.get(t,jr);e.focused=!1,e.dirty=!0}e.getResource(Xr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,d){(i.width<u||i.height<d)&&(i.width=Vo(Math.max(i.width,u)),i.height=Vo(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,u,d),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=jo(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(p,y,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=jo(o,l.value,u-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(d-l.fontSize)/2,s=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,u,d),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const b=s.get(e);void 0!==b&&x.releaseTexture(b);const v=x.createTexture(u,d,r,w.length,1,!0);s.set(e,v);const S=n.get(e,Xe);S.texture=v,S.size.x=u,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,Xe,S)}e.addSystemToSchedule(sn.Update,an([mt(Xr)],e=>{const t=n.getEntitiesWithComponents([jr]);for(const e of t)Ko(n,e,Vr,{tabIndex:0,isFocused:!1}),Ko(n,e,Mr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,jr)){const e=n.get(M,jr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,jr);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(sn.PreUpdate,an([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,jr).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,jr)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([jr,Fo]);for(const e of a){const t=n.get(e,jr);if(!t.dirty)continue;const s=n.get(e,Fo),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Uo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const qr=new Yr,Gr={Simple:0,Sliced:1,Tiled:2,Filled:3},Kr={Horizontal:0,Vertical:1},Jr={Left:0,Right:1,Bottom:2,Top:3},Qr=Ae("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:Gr.Simple,fillMethod:Kr.Horizontal,fillOrigin:Jr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Zr=Qo({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?Xo(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class ea{build(e){We("Image",Qr);const t=e.world,n=new Map;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Qr)||n.delete(e);const e=t.getEntitiesWithComponents([Qr]);for(const s of e){const e=t.get(s,Qr),i=t.has(s,Fo)?t.get(s,Fo):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Zr.changed(r,o))continue;Uo(t,s);const a=t.get(s,Xe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Xo(i,s),a.size.y=Yo(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===Kr.Horizontal?e.fillOrigin===Jr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Jr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===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,Xe,a),n.set(s,Zr.take(o))}else a.color.a=0,t.insert(s,Xe,a),n.set(s,Zr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const ta=new ea,na=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),sa=Ae("ToggleGroup",{allowSwitchOff:!1});class ia{build(e){We("Toggle",na),We("ToggleGroup",sa);const t=e.world,n=new Set;e.addSystemToSchedule(sn.Update,an([mt(Ar)],e=>{const s=t.getEntitiesWithComponents([na]);if(!zr()||$r()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,na);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,na,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,na);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ko(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const s=t.get(n,Pr),i=t.get(n,na),r=t.get(n,Mr);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,sa);if(i.isOn&&r){if(!t.get(s,sa).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,na,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,na);i.isOn&&(i.isOn=!1,t.insert(s,na,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Xe)){const e=t.get(n,Xe);e.color=Oo(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Xe,e)}}}for(const e of s){const n=t.get(e,na);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Xe)){const e=t.get(n.graphicEntity,Xe);e.enabled=n.isOn,t.insert(n.graphicEntity,Xe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const oa=new ia,ra=Io,aa=Ae("ProgressBar",{value:0,fillEntity:0,direction:Io.LeftToRight});function la(e,t,n,s){if(!e.has(t,Fo))return;const i=e.get(t,Fo),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=ko(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Xe,n))}if(e.has(t,je)){const n=e.get(t,je),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,je,n))}}class ca{build(e){We("ProgressBar",aa);const t=e.world;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e=t.getEntitiesWithComponents([aa,Fo]);for(const n of e){const e=t.get(n,aa);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Fo),i=Math.max(0,Math.min(1,e.value));Lo(t,e.fillEntity,e.direction,i);const o=Xo(s,n),r=Yo(s,n);la(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const ua=new ca,da=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ha=Ae("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}});class fa{build(e){We("Draggable",da),We("DragState",ha);const t=e.world,n=e.getResource(Ar);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn)],(e,r)=>{if(zr()&&!$r())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([da,Pr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,da).enabled)continue;if(t.get(s,Pr).hovered){let e=0;t.has(s,Xe)&&(e=t.get(s,Xe).layer);const i=No(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,ha)||t.insert(n,ha);const e=t.get(n,ha),o=t.get(n,je);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ha)){t.get(s,ha).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,da);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,ha).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ha))return void(o=null);const s=t.get(o,ha),i=t.get(o,da),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,je)){const e=function(e,t,n,s){if(!e.has(t,Ke))return{x:n,y:s};const i=e.get(t,Ke).entity;if(!e.valid(i)||!e.has(i,je))return{x:n,y:s};const o=e.get(i,je),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=yr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,je);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,je,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const pa=new fa,ma=Ae("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function ga(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 ya(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class _a{build(e){We("ScrollView",ma);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(sn.PostUpdate,an([mt(pn),mt(yn),mt(wt)],(e,i,o)=>{const r=zr()&&!$r(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([ma,Fo]);for(const o of l){Ko(t,o,hr,{enabled:!0,mode:ur});const l=t.get(o,ma),c=t.get(o,Fo);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const d=Xo(c,o),h=Yo(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,Je)){const e=t.get(l.contentEntity,Je).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,je))continue;const e=t.get(r,je);let a=0,l=0,c=.5,u=.5;if(t.has(r,Fo)){const e=t.get(r,Fo);a=Xo(e,r)||e.size.x,l=Yo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Xe)){const e=t.get(r,Xe);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);d<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){Ko(t,o,Mr,{enabled:!0,blockRaycast:!0});const n=t.has(o,Pr)?t.get(o,Pr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=ga(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=ga(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ga(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ga(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=ya(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Zo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Zo?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=ya(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Zo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Zo?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,je)){const e=t.get(l.contentEntity,je),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,je,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const wa=new _a,xa=Io,ba=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:Io.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function va(e,t,n,s,i,o){const r=Xo(s,i)*n.worldScale.x,a=Yo(s,i)*n.worldScale.y,l=yr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Io.LeftToRight:return r>0?(f-m)/r:0;case Io.RightToLeft:return r>0?1-(f-m)/r:0;case Io.BottomToTop:return a>0?(p-g)/a:0;case Io.TopToBottom:return a>0?1-(p-g)/a:0}}function Sa(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Io.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Io.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Io.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Io.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Ma{build(e){We("Slider",ba);const t=e.world;let n=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn),mt(Ar)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([ba,Fo]);for(const r of o){const o=t.get(r,ba),a=t.get(r,Fo);if(!zr()||$r()){if(t.has(r,je)){Ko(t,r,Mr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ko(t,o.handleEntity,Mr,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,Pr)?t.get(r,Pr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Pr)&&(u=t.get(o.handleEntity,Pr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=va(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,ba,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Xo(a,r),d=Yo(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Lo(t,o.fillEntity,o.direction,c),Jo(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Fo)){const e=t.get(o.handleEntity,Fo);Sa(e,o.direction,c),t.insert(o.handleEntity,Fo,e),Jo(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pa=new Ma;class Ta{build(e){We("Focusable",Vr);const t=e.world,n=new Nr;e.insertResource(Xr,n),e.addSystemToSchedule(sn.Update,an([mt(pn),mt(Ar)],(e,s)=>{if(zr()&&!$r())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Vr]);for(const e of i){if(!t.has(e,Pr))continue;t.get(e,Pr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Mr)){if(!t.get(n,Mr).enabled)continue}const s=t.get(n,Vr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Vr)){t.get(i,Vr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Vr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Ca=new Ta,Ea=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Aa(){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")}}()}class Ra{build(e){We("SafeArea",Ea);const t=e.world;let n=Aa(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Aa(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Aa(),s=!0});e.addSystemToSchedule(sn.PreUpdate,an([mt(yn)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Ea,Fo]);for(const e of u){const s=t.get(e,Ea),i=t.get(e,Fo),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Fo,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ia=new Ra,ka=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Fa=null;function Ba(e,t){if(!Fa)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Fa.get(e);n?n.renderer=t:Fa.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class za{build(e){We("ListView",ka);const t=e.world,n=new Map;Fa=n,e.addSystemToSchedule(sn.PostUpdate,an([mt(pn)],e=>{const s=zr()&&!$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([ka,Fo]);for(const o of i){Ko(t,o,Mr,{enabled:!0,blockRaycast:!0}),Ko(t,o,hr,{enabled:!0,mode:ur});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,ka),a=t.get(o,Fo),l=Yo(a,o),c=Xo(a,o);if(!s){const n=t.has(o,Pr)?t.get(o,Pr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,it,{value:`ListItem_${e}`}),t.insert(n,Fo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,je)){const s=t.get(n,je);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,je,s)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ua=new za,Wa=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class $a{build(e){We("Dropdown",Wa);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,je))return;const n=t.get(e,je);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,je,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,Xe)){const n=t.get(e,Xe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Xe,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,Xe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*er;t.insert(i,Fo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,je,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,Xe,{texture:ye,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*er;t.insert(o,it,{value:`Option_${e}`}),t.insert(o,Fo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*er},offsetMax:{x:0,y:0},size:{x:r,y:er},pivot:{x:.5,y:.5}}),t.insert(o,je,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,Xe,{texture:ye,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:er},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Mr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,je,{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,or,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:nr.Left,verticalAlign:sr.Middle,wordWrap:!1,overflow:ir.Clip,lineHeight:1.2}),t.insert(c,Fo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:er},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,or))return;const s=t.get(n,or);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,or,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,Mr)&&t.insert(e,Mr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Xe))){const s=t.get(e,Xe);t.insert(e,Xe,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Xe))continue;const i=n===e.highlightIndex?{...tr}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Xe,{texture:ye,color:i,size:{x:e.ddWidth,y:er},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).hovered)return!0}return!1}e.addSystemToSchedule(sn.Update,an([mt(pn),mt(Ar)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=zr()&&!$r(),p=t.getEntitiesWithComponents([Wa]);for(const m of p){const p=t.get(m,Wa);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Ko(t,m,Mr,{enabled:!0,blockRaycast:!0});const y=t.has(m,Pr)?t.get(m,Pr):null;if(y?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,Pr))continue;if(t.get(s,Pr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Da=new $a,La=0,Oa=0,Ha=2,ja=Ae("LayoutGroup",{direction:La,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Oa,reverseOrder:!1});class Va{build(e){We("LayoutGroup",ja);const t=e.world;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e=t.getEntitiesWithComponents([ja,Fo,Je]);for(const n of e){const e=t.get(n,ja),s=t.get(n,Fo),i=t.get(n,Je);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Fo)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,Fo)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Xo(s,n),a=Yo(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===La;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=Xo(s.rect,s.entity),f=Yo(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===Oa?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ha?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,n<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Oa?-l*r+u.left+p*i:e.childAlignment===Ha?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const _=t.get(s.entity,je);_.position.x=g,_.position.y=y,t.insert(s.entity,je,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Na=new Va;class Xa{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(sn.PostUpdate,an([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Ya=new Xa;async function qa(e,t,n){const s=e.getResource(ho);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Ga(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 Ka=pt({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Ja={r:.2,g:.4,b:1,a:.7},Qa={r:.2,g:1,b:.2,a:.7},Za={r:.2,g:1,b:1,a:.7},el={r:1,g:1,b:.2,a:.5},tl={r:1,g:.2,b:.2,a:.8},nl={r:1,g:.2,b:.2,a:1},sl=1.5,il=16;function ol(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function rl(e){switch(e){case ht.Static:return Ja;case ht.Kinematic:return Za;default:return Qa}}function al(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)si.line(l[e],l[(e+1)%4],o,sl)}function ll(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),d=l(-n,-s),h=l(n,-s);si.line(c,d,o,sl),si.line(u,h,o,sl);for(let e=0;e<il;e++){const t=e/il*Math.PI,i=(e+1)/il*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));si.line(r,a,o,sl)}for(let e=0;e<il;e++){const t=Math.PI+e/il*Math.PI,i=Math.PI+(e+1)/il*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));si.line(r,a,o,sl)}}function cl(e,t,n,s){const i=e+.5*n,o=t+.5*s;si.line({x:e,y:t},{x:i,y:o},tl,sl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));si.line({x:i,y:o},{x:u,y:d},tl,sl),si.line({x:i,y:o},{x:h,y:f},tl,sl)}function ul(e,t,n){if(zr()&&!$r())return;const s=e.getResource(Ka);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([lt,je]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,lt);if(!n.enabled)continue;const o=e.world.get(t,je),a=o.worldPosition.x,l=o.worldPosition.y,c=ol(o.worldRotation);if(s.showColliders){if(e.world.has(t,ct)){const s=e.world.get(t,ct),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);al(a+r*d-u*h,l+r*h+u*d,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,ut)){const s=e.world.get(t,ut),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c),f=a+r*d-u*h,p=l+r*h+u*d;si.circleOutline({x:f,y:p},s.radius*i,o,sl,32)}if(e.world.has(t,dt)){const s=e.world.get(t,dt),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);ll(a+r*d-u*h,l+r*h+u*d,s.radius*i,s.halfHeight*i,c,o)}}if(s.showVelocity&&r&&n.bodyType===ht.Dynamic){const e=r.getLinearVelocity(t);cl(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)si.circle({x:e.contactX,y:e.contactY},3,nl,!0,32)}}const dl=pt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),hl=pt(null,"PhysicsAPI");function fl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function pl(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ml{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,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(dl,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ga(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([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(sn.PostUpdate,an([mt(wt)],a=>{if(zr()&&!$r())return;const l=r.getEntitiesWithComponents([lt,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,lt),l=r.get(i,je);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=fl(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),_l(e,s,i,this.config_.collisionLayerMasks),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===ht.Kinematic){const e=fl(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,je);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(r,Ke)){const t=e.world.get(r,Ke);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,je)){const n=e.world.get(t.entity,je),s=fl(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=pl(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,je,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(dl,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(hl,wl._fromModule(s)),function(e,t,n){e.insertResource(Ka,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),li("physics-debug-draw",()=>{ul(e,t,n)})}(e,hl,dl),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}const gl=16;function yl(e,t,n){if(!n)return t;for(let t=0;t<gl;t++)if(e===1<<t)return n[t];return t}function _l(e,t,n,s){const i=e.world;if(i.has(n,ct)){const e=i.get(n,ct),o=e.categoryBits??1,r=yl(o,e.maskBits??65535,s);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,ut)){const e=i.get(n,ut),o=e.categoryBits??1,r=yl(o,e.maskBits??65535,s);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,dt)){const e=i.get(n,dt),o=e.categoryBits??1,r=yl(o,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}}class wl{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(wl.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)}static setDebugDraw(e,t){const n=e.getResource(Ka);n&&(n.enabled=t,e.insertResource(Ka,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Ka);n&&e.insertResource(Ka,{...n,...t})}}const xl={nearest:0,linear:1},bl={repeat:0,clamp:1,mirror:2};function vl(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=xl[s.filterMode??"linear"]??1,a=bl[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Sl(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 Ml(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Pl(e){const{app:t,module:n,sceneData:s,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=xs(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=vl(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!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)}}}}(n,s,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=bs(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===T(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=Sl(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=vl(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,h,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new ml("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=xs(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=T(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=vl(e,c,!1),d=e.getResourceManager();s[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(n,s,i),p=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=xs(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Cn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Cn.createFromAsset(e,r)}catch{n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=xs(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=$n(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,vl(e,s))}catch{r.set(t,0)}On(Dn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=xs(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=ds(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=hs(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=vl(e,t),Kn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Zn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=xs(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Yn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Yn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),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=xs(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,f,p);const m=Cs(t.world,s);if(c&&t.hasResource(ho))for(const e of m.values())t.world.insert(e,ot,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=bs(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,s,d,m);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=le);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Ze)?c.get(o,Ze):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,je)){const e=Ml(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(t,n,o,h,e)}if(l){const e=t.getResource(Bs);e&&e.setAddressableManifest(l)}}function Tl(e,t,n){return{name:e,async setup(){await Pl({...n,sceneData:t,sceneName:e})}}}async function Cl(e){const{app:t,firstScene:n,aspectRatio:s}=e;yo(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ho);for(const t of e.scenes)o.register(Tl(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Is(t.world,s)}class El{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=bs(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===T(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=xs(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=T(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Al="__preview__";class Rl{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(ho);t.register({name:Al,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Al),this.loadPromise_=t.load(Al).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new El(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Pl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Al})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([qe]);for(const i of s){const s=e.get(i,qe);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(ho).getScene(Al),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,je,r);const a={isActive:!0,projectionType:Le.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Oe.ColorAndDepth};e.insert(o,Ye,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ho);await e.switchTo(Al),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 Il={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=to.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:to.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){to.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(to.releaseRenderTarget(e._handle),Il.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){to.begin(t,e._handle)},end(){to.end()},getDepthTexture:e=>to.getTargetDepthTexture(e._handle)};var kl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(kl||(kl={}));class Fl{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${kl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case kl.Debug:console.debug(t,n);break;case kl.Info:console.log(t,n);break;case kl.Warn:console.warn(t,n);break;case kl.Error:console.error(t,n)}}}class Bl{constructor(){this.handlers_=[],this.minLevel_=kl.Info,this.addHandler(new Fl)}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(kl.Debug,e,t,n)}info(e,t,n){this.log(kl.Info,e,t,n)}warn(e,t,n){this.log(kl.Warn,e,t,n)}error(e,t,n){this.log(kl.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 zl=new Bl;function Ul(){return zl}function Wl(e){zl.setMinLevel(e)}function $l(e,t,n){zl.debug(e,t,n)}function Dl(e,t,n){zl.info(e,t,n)}function Ll(e,t,n){zl.warn(e,t,n)}function Ol(e,t,n){zl.error(e,t,n)}const Hl={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},jl={Running:0,Paused:1,Completed:2,Cancelled:3},Vl={None:0,Restart:1,PingPong:2};const Nl=1.70158,Xl=2.70158,Yl=2.5949095;const ql=2*Math.PI/3,Gl=2*Math.PI/4.5;const Kl=7.5625,Jl=2.75;const Ql=1e-6;function Zl(e,t,n){switch(e){case Hl.Linear:return t;case Hl.EaseInQuad:return function(e){return e*e}(t);case Hl.EaseOutQuad:return function(e){return e*(2-e)}(t);case Hl.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Hl.EaseInCubic:return function(e){return e*e*e}(t);case Hl.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Hl.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Hl.EaseInBack:return function(e){return Xl*e*e*e-Nl*e*e}(t);case Hl.EaseOutBack:return function(e){const t=e-1;return 1+Xl*t*t*t+Nl*t*t}(t);case Hl.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Yl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Yl)+2)/2}(t);case Hl.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*ql)}(t);case Hl.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*ql)+1}(t);case Hl.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Gl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Gl)/2+1}(t);case Hl.EaseOutBounce:return function(e){return e<1/Jl?Kl*e*e:e<2/Jl?Kl*(e-=1.5/Jl)*e+.75:e<2.5/Jl?Kl*(e-=2.25/Jl)*e+.9375:Kl*(e-=2.625/Jl)*e+.984375}(t);case Hl.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<Ql)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<Ql)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Hl.Step:return function(e){return e<1?0:1}(t);default:return t}}const ec=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Hl.Linear,bezierPoints:null,state:jl.Running,loop:i?.loop??Vl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===jl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==jl.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Zl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Vl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Vl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=jl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===jl.Running&&(t.state=jl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===jl.Paused&&(t.state=jl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=jl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:jl.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class tc{constructor(e){this.id=e}get state(){return ec.getState(this.id)}bezier(e,t,n,s){return ec.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof tc?ec.setSequenceNext(this.id,e.id):ec.setSequenceNextExternal(this.id,e),this}pause(){ec.pause(this.id)}resume(){ec.resume(this.id)}cancel(){ec.cancel(this.id)}}const nc={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class sc{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof tc?(ec.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ic=null,oc=null;function rc(e,t){ic=e,oc=t,ec.init(e,t)}function ac(){ec.shutdown(),ic=null,oc=null}function lc(){if(!ic)throw new Error("Tween API not initialized");return ic}function cc(){if(!oc)throw new Error("Tween API not initialized");return oc}const uc={to(e,t,n,s,i,o){const r=lc(),a=cc(),l=o?.easing??Hl.Linear,c=o?.delay??0,u=o?.loop??Vl.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new sc(r,a,h)},value(e,t,n,s,i){const o=ec.create(e,t,n,s,i);return new tc(o)},cancel(e){lc()._anim_cancelTween(cc(),e.entity)},cancelAll(e){lc()._anim_cancelAllTweens(cc(),e)},update(e){lc()._anim_updateTweens(cc(),e),ec.update(e)}};class dc{constructor(){this.name="AnimationPlugin"}build(e){rc(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{uc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Xn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ac()}}const hc=new dc;var fc;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(fc||(fc={}));const pc={model:fc.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function mc(e,t=pc){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case fc.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case fc.Inverse:a=s/Math.max(r,s);break;case fc.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function gc(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const yc=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:fc.Inverse,rolloff:1,priority:0,enabled:!0}),_c=Ae("AudioListener",{enabled:!0});class wc{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;Yn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(sn.PreUpdate,an([mt(wt)],t=>{if(!(!zr()||$r()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,d=!1;const h=s.getEntitiesWithComponents([_c,Ne]);for(const e of h){if(s.get(e,_c).enabled){const t=s.get(e,Ne);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([yc]);a.clear();for(const e of f){const t=s.get(e,yc);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=Yn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Ne),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=mc(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=gc(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Yn.dispose()}}const xc=new wc;let bc=null,vc=null;function Sc(e,t){bc=e,vc=t}function Mc(){bc=null,vc=null}const Pc={update(e){bc&&vc&&bc.particle_update?.(vc,e)},play(e){bc&&vc&&bc.particle_play?.(vc,e)},stop(e){bc&&vc&&bc.particle_stop?.(vc,e)},reset(e){bc&&vc&&bc.particle_reset?.(vc,e)},getAliveCount:e=>bc?bc.particle_getAliveCount?.(e)??0:0};class Tc{constructor(){this.name="ParticlePlugin"}build(e){Sc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Pc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Mc()}}const Cc=new Tc,Ec=1e6;class Ac{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ss(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(yn),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Ec,l=i?.valid?i.worldTop:Ec,c=t.getEntitiesWithComponents([as,je]);for(const e of c){const s=t.tryGet(e,as),i=t.tryGet(e,je);if(!s||!i)continue;if(!s.visible)continue;const c=s.texture;if(!c)continue;const u=Jn(c);if(!u)continue;if(!n.has(e)){if(os.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];os.setTiles(e,t)}n.add(e)}const d=s.tileWidth/u.width,h=s.tileHeight/u.height,f=s.tint,p=s.parallaxFactor;os.submitLayer(e,c,s.layer,0,s.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,s.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([rs,je]);for(const e of u){if(t.tryGet(e,as))continue;const i=t.tryGet(e,rs),c=t.tryGet(e,je);if(!i?.source||!c)continue;const u=es(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];os.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&os.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const d=s.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],n=u.tilesets[0];if(!n)continue;const s=Jn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,h=u.tileHeight/s.height;os.submitLayer(t,n.textureHandle,e,0,n.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)os.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Qn(),is()}}const Rc=new Ac;function Ic(e,t){return e.toFixed(t)}function kc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Fc{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ic(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ic(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of n){s+=`<div>${kc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ic(t,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Bc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const zc=pt(Bc(),"Stats");class Uc{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Wc="StatsCollect";class $c{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Dc{constructor(e){this.name="Stats",this.collector_=new $c,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(zc,Bc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Fc(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=an([mt(wt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(zc);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Wc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=to.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Wc});e.addSystemToSchedule(sn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Lc=new Dc;class Oc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Hc(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function jc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(Bs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Hc(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Hc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Oc(s);await Cl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Vc=[cr,Sr,Ir,ta,ua,Hr,pa,wa,Pa,oa,qr,Ca,Ia,Ua,Da,Na,Ya],Nc=[...Vc,hc,xc,Cc,Rc,Gi];function Xc(e,t){return function(e,t){const n=go.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Zs(e),Mn(e),gi(e),Ei(e),Zi(e),so(e);const i=new ro;n.setPipeline(i);let o=h();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=vo(e,s,t,i));const r=n.getResource(yn);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(yn,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;to.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(to.resize(t,l),n.hasResource(ho)){const e=n.getResource(ho).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=vo(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:_o,width:t,height:l,elapsed:u});else{i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),to.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(sn.First,l),n.addSystemToSchedule(sn.Last,c),n.addPlugin(Us),n.addPlugin(Ys),n.addPlugin(gn),n.addPlugin(mo),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Nc,...t})}class Yc{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function qc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Gc(e,t){try{return await e({instantiateWasm:qc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Kc(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=W(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:qc("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),d=Xc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await Gc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Gc(e.physicsFactory,"physics.wasm"));const p=new Yc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Cl({app:d,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),d.run()}J||(J=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await w(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return x(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Q;export{Wt as Added,dc as AnimationPlugin,go as App,zs as AssetPlugin,Ws as AssetRefCounter,Fs as AssetServer,Bs as Assets,Un as AsyncCache,fc as AttenuationModel,Yn as Audio,p as AudioBus,_c as AudioListener,m as AudioMixer,wc as AudioPlugin,g as AudioPool,yc as AudioSource,Qe as BitmapText,_n as BlendMode,ht as BodyType,ct as BoxCollider,Cr as Button,Tr as ButtonState,Ye as Camera,qe as Canvas,dt as CapsuleCollider,$t as Changed,Je as Children,ut as CircleCollider,Oe as ClearFlags,Yt as Commands,Gt as CommandsInstance,ee as DEFAULT_DESIGN_HEIGHT,Z as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,de as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,di as DataType,fa as DragPlugin,ha as DragState,da as Draggable,si as Draw,Wa as Dropdown,$a as DropdownPlugin,Hl as EasingType,et as EmitterShape,qt as EntityCommands,en as EventReader,nn as EventReaderInstance,Qt as EventRegistry,Zt as EventWriter,tn as EventWriterInstance,Io as FillDirection,Kr as FillMethod,Jr as FillOrigin,Xr as FocusManager,Nr as FocusManagerState,Ta as FocusPlugin,Vr as Focusable,Uc as FrameHistory,oo as GLDebug,wi as Geometry,on as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,we as INVALID_MATERIAL,ye as INVALID_TEXTURE,Qr as Image,ea as ImagePlugin,Gr as ImageType,pn as Input,mn as InputPlugin,fn as InputState,Mr as Interactable,Va as LayoutGroupPlugin,ka as ListView,za as ListViewPlugin,Ve as LocalTransform,kl as LogLevel,Bl as Logger,Vl as LoopMode,Cn as Material,Wn as MaterialLoader,zt as Mut,it as Name,Ke as Parent,Pc as Particle,nt as ParticleEasing,st as ParticleEmitter,Tc as ParticlePlugin,wl as Physics,dl as PhysicsEvents,ml as PhysicsPlugin,Ii as PostProcess,qi as PostProcessPlugin,Pi as PostProcessStack,rt as PostProcessVolume,Vs as PrefabServer,Ns as Prefabs,Xs as PrefabsPlugin,Rl as PreviewPlugin,aa as ProgressBar,ra as ProgressBarDirection,ca as ProgressBarPlugin,Le as ProjectionType,jt as Query,Vt as QueryInstance,Nt as Removed,Xt as RemovedQueryInstance,ro as RenderPipeline,Ki as RenderStage,Il as RenderTexture,to as Renderer,mt as Res,gt as ResMut,lt as RigidBody,he as RuntimeConfig,Ea as SafeArea,Ra as SafeAreaPlugin,He as ScaleMode,ho as SceneManager,uo as SceneManagerState,ot as SceneOwner,sn as Schedule,ma as ScrollView,_a as ScrollViewPlugin,zn as ShaderSources,tt as SimulationSpace,ba as Slider,xa as SliderDirection,Ma as SliderPlugin,Ze as SpineAnimation,Xe as Sprite,Nn as SpriteAnimator,zc as Stats,$c as StatsCollector,Fc as StatsOverlay,Dc as StatsPlugin,bt as Storage,hn as SystemRunner,or as Text,nr as TextAlign,jr as TextInput,Yr as TextInputPlugin,ir as TextOverflow,lr as TextPlugin,rr as TextRenderer,sr as TextVerticalAlign,rs as Tilemap,os as TilemapAPI,as as TilemapLayer,Ac as TilemapPlugin,wt as Time,na as Toggle,ia as TogglePlugin,je as Transform,uc as Tween,sc as TweenHandle,jl as TweenState,nc as TweenTarget,yn as UICameraInfo,Er as UIEventQueue,Ar as UIEvents,Pr as UIInteraction,Or as UIInteractionPlugin,Rr as UILayoutPlugin,hr as UIMask,vr as UIMaskPlugin,Fo as UIRect,Xa as UIRenderOrderPlugin,Ge as Velocity,Yc as WeChatAssetProvider,El as WebAssetProvider,Bt as World,Ne as WorldTransform,un as addStartupSystem,cn as addSystem,dn as addSystemToSchedule,hc as animationPlugin,me as applyBuildRuntimeConfig,Lo as applyDirectionalFill,fe as applyRuntimeConfig,Us as assetPlugin,xc as audioPlugin,mc as calculateAttenuation,gc as calculatePanning,Oi as cleanupAllPostProcessVolumes,Li as cleanupPostProcessVolume,Vn as clearAnimClips,ui as clearDrawCallbacks,Qn as clearTextureDimensionsCache,ts as clearTilemapSourceCache,ke as clearUserComponents,Se as color,Wo as computeFillAnchors,Do as computeFillSize,$o as computeHandleAnchors,ko as computeUIRectLayout,br as createMaskProcessor,Tl as createRuntimeSceneConfig,Xc as createWebApp,$l as debug,Bc as defaultFrameStats,Ae as defineComponent,Kt as defineEvent,pt as defineResource,an as defineSystem,Re as defineTag,pa as dragPlugin,Da as dropdownPlugin,Ol as error,$n as extractAnimClipTexturePaths,ks as findEntityByName,yo as flushPendingSystems,Ca as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Ui as getAllEffectDefs,jn as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,xs as getComponentAssetFieldDescriptors,ws as getComponentAssetFields,at as getComponentDefaults,Ms as getComponentEntityFields,bs as getComponentSpineFieldDescriptor,F as getCustomExtensions,C as getEditorType,Bi as getEffectDef,zi as getEffectTypes,Ul as getLogger,t as getPlatform,s as getPlatformType,Jn as getTextureDimensions,es as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,ta as imagePlugin,Dl as info,Zs as initDrawAPI,so as initGLDebugAPI,gi as initGeometryAPI,Mn as initMaterialAPI,Sc as initParticleAPI,jc as initPlayableRuntime,Ei as initPostProcessAPI,Zi as initRendererAPI,Cl as initRuntime,ss as initTilemapAPI,rc as initTweenAPI,Kc as initWeChatRuntime,gn as inputPlugin,Ds as instantiatePrefab,fr as intersectRects,pr as invertMatrix4,ze as isBuiltinComponent,U as isCustomExtension,zr as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,$r as isPlayMode,Ur as isRuntime,wn as isTextureRef,i as isWeChat,o as isWeb,Na as layoutGroupPlugin,Ua as listViewPlugin,Rs as loadComponent,Ga as loadPhysicsModule,Pl as loadRuntimeScene,Cs as loadSceneData,Es as loadSceneWithAssets,gs as loadTiledMap,k as looksLikeAssetPath,Dn as parseAnimClipData,fs as parseTiledMap,ds as parseTmjJson,Cc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,wr as pointInOBB,gr as pointInWorldRect,Gi as postProcessPlugin,Ys as prefabsPlugin,ua as progressBarPlugin,Me as quat,On as registerAnimClip,$ as registerAssetBuildTransform,We as registerComponent,_s as registerComponentAssetFields,Ss as registerComponentEntityFields,li as registerDrawCallback,$s as registerEmbeddedAssets,Bn as registerMaterialCallback,Kn as registerTextureDimensions,Zn as registerTilemapSource,Ps as remapEntityFields,hs as resolveRelativePath,Ia as safeAreaPlugin,mo as sceneManagerPlugin,mr as screenToWorld,wa as scrollViewPlugin,Br as setEditorMode,Ba as setListViewRenderer,Wl as setLogLevel,Wr as setPlayMode,Tt as setWasmErrorHandler,ei as shutdownDrawAPI,io as shutdownGLDebugAPI,yi as shutdownGeometryAPI,Pn as shutdownMaterialAPI,Mc as shutdownParticleAPI,Ai as shutdownPostProcessAPI,eo as shutdownRendererAPI,is as shutdownTilemapAPI,ac as shutdownTweenAPI,Pa as sliderPlugin,Xn as spriteAnimatorSystemUpdate,Lc as statsPlugin,qo as syncFillSpriteSize,Di as syncPostProcessVolume,qr as textInputPlugin,cr as textPlugin,Rc as tilemapPlugin,W as toBuildPath,oa as togglePlugin,qa as transitionTo,Hr as uiInteractionPlugin,Ir as uiLayoutPlugin,Sr as uiMaskPlugin,Vc as uiPlugins,Ya as uiRenderOrderPlugin,Hn as unregisterAnimClip,Fe as unregisterComponent,ci as unregisterDrawCallback,Is as updateCameraAspectRatio,xe as vec2,be as vec3,ve as vec4,Ll as warn,fo as wrapSceneSystem,N as wxFileExists,X as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,V as wxReadTextFile,Y as wxWriteFile};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function n(){return null!==e}function s(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,n){return t().fetch(e,n)}async function a(e){return t().readFile(e)}async function l(e){return t().readTextFile(e)}async function c(e){return t().fileExists(e)}async function u(e,n){return t().instantiateWasm(e,n)}function d(e,n){return t().createCanvas(e,n)}function h(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class p{constructor(e,t){this.muted_=!1,this.volume_=1,this.children_=[],this.name_=t.name,this.gainNode_=e.createGain(),this.volume_=Math.max(0,Math.min(1,t.volume??1)),this.muted_=t.muted??!1,this.gainNode_.gain.value=this.muted_?0:this.volume_}get name(){return this.name_}get node(){return this.gainNode_}get volume(){return this.volume_}set volume(e){this.volume_=Math.max(0,Math.min(1,e)),this.muted_||this.gainNode_.gain.setTargetAtTime(this.volume_,this.gainNode_.context.currentTime,.015)}get muted(){return this.muted_}set muted(e){this.muted_=e,this.gainNode_.gain.setTargetAtTime(e?0:this.volume_,this.gainNode_.context.currentTime,.015)}connect(e){e instanceof p?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class m{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new p(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new p(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new p(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new p(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new p(e,{name:"voice",volume:t.voiceVolume??1}),this.master.addChild(this.voice),this.buses_.set("master",this.master),this.buses_.set("music",this.music),this.buses_.set("sfx",this.sfx),this.buses_.set("ui",this.ui),this.buses_.set("voice",this.voice)}getBus(e){return this.buses_.get(e)}createBus(e){const t=new p(this.context_,e),n=e.parent?this.buses_.get(e.parent):this.master;return n&&n.addChild(t),this.buses_.set(e.name,t),t}}class g{constructor(e,t=16){this.pool_=[],this.activeCount_=0,this.context_=e;for(let e=0;e<t;e++)this.pool_.push(this.createNode())}createNode(){const e=this.context_.createGain(),t=this.context_.createStereoPanner();return e.connect(t),{gain:e,panner:t,source:null,inUse:!1,startTime:0}}acquire(){let e=this.pool_.find(e=>!e.inUse);return e||(e=this.createNode(),this.pool_.push(e)),e.inUse=!0,e.startTime=this.context_.currentTime,e.gain.gain.value=1,e.panner.pan.value=0,this.activeCount_++,e}release(e){if(e.inUse){if(e.source){try{e.source.stop()}catch(e){}e.source.disconnect(),e.source=null}e.inUse=!1,this.activeCount_--}}get activeCount(){return this.activeCount_}get capacity(){return this.pool_.length}}class y{constructor(e,t,n){this.panWarned_=!1,this.id=e,this.ctx_=t,this.contexts_=n}stop(){this.ctx_.stop(),this.ctx_.destroy(),this.contexts_.delete(this.id)}pause(){this.ctx_.pause()}resume(){this.ctx_.play()}setVolume(e){this.ctx_.volume=e}setPan(e){this.panWarned_||(console.warn("[Audio] WeChat InnerAudioContext does not support stereo panning"),this.panWarned_=!0)}setLoop(e){this.ctx_.loop=e}setPlaybackRate(e){this.ctx_.playbackRate=e}get isPlaying(){return!this.ctx_.paused}get currentTime(){return this.ctx_.currentTime}get duration(){return this.ctx_.duration}}class _{constructor(){this.name="WeChat",this.contexts_=new Map,this.urlCache_=new Map,this.nextId_=0}get mixer(){return null}get isReady(){return!0}async initialize(e){}async ensureResumed(){}async loadBuffer(e){const t=++this.nextId_;return this.urlCache_.set(t,e),{id:t,duration:0}}async loadBufferFromData(e,t){return this.loadBuffer(e)}unloadBuffer(e){this.urlCache_.delete(e.id)}play(e,t){const n=this.urlCache_.get(e.id);if(!n)throw new Error(`Buffer ${e.id} not found`);const s=wx.createInnerAudioContext();s.loop=t.loop??!1,s.volume=t.volume??1,s.playbackRate=t.playbackRate??1,s.startTime=t.startOffset??0,s.obeyMuteSwitch=!1;const i=++this.nextId_;this.contexts_.set(i,s);const o=new y(i,s,this.contexts_);return s.onEnded(()=>{o.onEnd?.(),s.loop||(s.destroy(),this.contexts_.delete(i))}),s.onError(e=>{console.error(`[WeChatAudio] Playback error for "${n}":`,e.errMsg)}),s.src=n,s.play(),o}suspend(){for(const e of this.contexts_.values())e.pause()}resume(){for(const e of this.contexts_.values())e.paused&&e.play()}dispose(){for(const e of this.contexts_.values())e.destroy();this.contexts_.clear(),this.urlCache_.clear()}}function w(e,t){return new Promise((n,s)=>{const i=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===i?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,s={};if(e.header)for(const t of Object.keys(e.header))s[t.toLowerCase()]=e.header[t];n({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:s,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,n="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(n).buffer)}})},fail:e=>{s(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function x(e,t){if("undefined"==typeof WXWebAssembly)throw new Error("WXWebAssembly is not available. Requires WeChat base library >= 2.13.0");const n=e.startsWith("/")?e.slice(1):e;try{const e=await WXWebAssembly.instantiate(n,t);return{instance:e.instance??e,module:e.module}}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`WXWebAssembly.instantiate failed for "${n}": ${t}`)}}const b=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg","aac","flac","webm"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esanim"],contentType:"json",editorType:"anim-clip",addressableType:null,wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["tmj"],contentType:"json",editorType:"tilemap",addressableType:"json",wechatPackInclude:!0,hasTransitiveDeps:!0}],v={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",aac:"audio/aac",flac:"audio/flac",webm:"audio/webm",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",esanim:"application/json",bmfont:"application/json",fnt:"text/plain"},S=new Map,M=new Set;for(const e of b)for(const t of e.extensions)S.set(t,e),M.add(t);function P(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function T(e){return S.get(P(e))}function C(e){return T(e)?.editorType??"unknown"}function E(e){return T(e)?.addressableType??null}function A(e){for(const t of b)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function R(e){return M.has(e.toLowerCase())}function I(){return M}function k(e){return"string"==typeof e&&(!!e.includes("/")&&R(P(e)))}function F(){const e=[];for(const t of b)if(t.wechatPackInclude)for(const n of t.extensions)e.push(`.${n}`);return e}function B(){return F().map(e=>({type:"suffix",value:e}))}function z(e){return v[e.toLowerCase()]}function U(e){const t=T(e);return t?.wechatPackInclude??!1}function W(e){const t=T(e);if(!t||!t.wechatPackInclude)return e;if("json"!==t.contentType)return e;const n=e.lastIndexOf(".");return n>=0?e.substring(0,n)+".json":e}function $(e,t){for(const n of b)n.editorType===e&&(n.buildTransform=t)}function D(e){return T(e)?.buildTransform}let L=null;function O(){return L||(L=wx.getFileSystemManager()),L}function H(e,t){const n=t.toLowerCase();if(n.includes("permission denied")){if(U(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 j(e){return new Promise((t,n)=>{O().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{n(new Error(H(e,t.errMsg)))}})})}function V(e,t="utf-8"){return new Promise((n,s)=>{O().readFile({filePath:e,encoding:t,success:e=>{n(e.data)},fail:t=>{s(new Error(H(e,t.errMsg)))}})})}function N(e){return new Promise(t=>{O().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function X(e){const t=O();try{return t.accessSync(e),!0}catch{return!1}}function Y(e,t){return new Promise((n,s)=>{O().writeFile({filePath:e,data:t,success:()=>n(),fail:t=>{s(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function q(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 G(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 K(e){return G(await q(e))}let J=!1;const Q=new class{constructor(){this.name="wechat",this.inputCleanup_=null}async fetch(e,t){return w(e,t)}async readFile(e){return function(e){return O().readFileSync(e)}(W(e))}async readTextFile(e){return function(e,t="utf-8"){return O().readFileSync(e,t)}(W(e))}async fileExists(e){return X(W(e))}async loadImagePixels(e){return K(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return x(e,t)}createImage(){return wx.createImage()}createCanvas(e,t){const n=wx.createCanvas();return n.width=e,n.height=t,n}now(){return Date.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const n=t=>e.onKeyDown(t.code),s=t=>e.onKeyUp(t.code),i="function"==typeof wx.onKeyDown;i&&(wx.onKeyDown(n),wx.onKeyUp(s));const o=t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX,n.clientY)},r=t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX,n.clientY)},a=t=>{for(const n of t.changedTouches)e.onPointerUp(n.identifier)};wx.onTouchStart(o),wx.onTouchMove(r),wx.onTouchEnd(a),this.inputCleanup_=()=>{i&&(wx.offKeyDown(n),wx.offKeyUp(s)),wx.offTouchStart(o),wx.offTouchMove(r),wx.offTouchEnd(a)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new _}getStorageItem(e){try{const t=wx.getStorageSync(e);return"string"==typeof t?t:null}catch{return null}}setStorageItem(e,t){try{wx.setStorageSync(e,t)}catch{}}removeStorageItem(e){try{wx.removeStorageSync(e)}catch{}}clearStorage(e){try{const{keys:t}=wx.getStorageInfoSync();for(const n of t)n.startsWith(e)&&wx.removeStorageSync(n)}catch{}}},Z=1920,ee=1080,te=100,ne=512,se={x:100,y:100},ie="Arial",oe=24,re=1.2,ae=.5,le=1/60,ce={x:0,y:-9.81},ue=1/60,de="default",he={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function fe(e){e.Text&&(e.Text._default.fontFamily=he.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=he.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=he.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=he.canvasMatchWidthOrHeight)}const pe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function me(e,t){if(void 0!==t.maxDeltaTime&&(he.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(he.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(he.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(he.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(he.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");he.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(he.canvasScaleMode=pe[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(he.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(he.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(he.assetFailureCooldown=t.assetFailureCooldown)}const ge=0,ye=4294967295,_e=4294967295,we=0,xe=(e=0,t=0)=>({x:e,y:t}),be=(e=0,t=0,n=0)=>({x:e,y:t,z:n}),ve=(e=0,t=0,n=0,s=1)=>({x:e,y:t,z:n,w:s}),Se=(e=1,t=1,n=1,s=1)=>({r:e,g:t,b:n,a:s}),Me=(e=1,t=0,n=0,s=0)=>({w:e,x:t,y:n,z:s});function Pe(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(Pe);const t={};for(const n in e)t[n]=Pe(e[n]);return t}let Te=0;function Ce(e,t){const n=++Te,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?{...Pe(t),...e}:Pe(t):e?{...t,...e}:{...t}}}function Ee(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function Ae(e,t){const n=Ue.get(e)??Ee().get(e);if(n)return n;const s=Ce(e,t);return Ee().set(e,s),Ue.set(e,s),Be(e,t,!1),s}function Re(e){const t=Ue.get(e)??Ee().get(e);if(t)return t;const n=Ce(e,{});return Ee().set(e,n),Ue.set(e,n),Be(e,{},!0),n}function Ie(e){return Ee().get(e)}function ke(){const e=Ee();for(const t of e.keys())Ue.delete(t);e.clear()}function Fe(e){Ee().delete(e),Ue.delete(e)}function Be(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}function ze(e){return!0===e._builtin}const Ue=new Map;function We(e,t){Ue.set(e,t)}function $e(e){return Ue.get(e)??Ie(e)}function De(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return Ue.set(e,n),n}const Le={Perspective:0,Orthographic:1},Oe={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},He={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},je=De("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}}),Ve=je,Ne=je,Xe=De("Sprite",{texture:ye,color:{r:1,g:1,b:1,a:1},size:{x:se.x,y:se.y},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),Ye=De("Camera",{projectionType:Le.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:Oe.ColorAndDepth}),qe=De("Canvas",{designResolution:{x:Z,y:ee},pixelsPerUnit:100,scaleMode:He.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Ge=De("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ke=De("Parent",{entity:0}),Je=De("Children",{entities:[]}),Qe=De("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:_e,enabled:!0}),Ze=De("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}),et={Point:0,Circle:1,Rectangle:2,Cone:3},tt={World:0,Local:1},nt={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=De("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:et.Cone,shapeRadius:100,shapeSize:{x:100,y:100},shapeAngle:25,speedMin:500,speedMax:500,angleSpreadMin:0,angleSpreadMax:360,startSizeMin:100,startSizeMax:100,endSizeMin:100,endSizeMax:100,sizeEasing:nt.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:nt.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:ye,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:tt.World,enabled:!0}),it=Ae("Name",{value:""}),ot=Ae("SceneOwner",{scene:"",persistent:!1}),rt=Ae("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function at(e){const t=$e(e);return t?Pe(t._default):null}const lt=De("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ct=De("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),dt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),ht={Static:0,Kinematic:1,Dynamic:2};let ft=0;function pt(e,t){const n=++ft;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}function mt(e){return{_type:"res",_resource:e}}function gt(e){return{_type:"res_mut",_resource:e}}class yt{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 _t{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 yt(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const wt=pt({delta:0,elapsed:0,frameCount:0},"Time"),xt="esengine:",bt={getString(e,n){const s=t().getStorageItem(xt+e);return null!==s?s:n},setString(e,n){t().setStorageItem(xt+e,n)},getNumber(e,n){const s=t().getStorageItem(xt+e);if(null===s)return n;const i=Number(s);return Number.isNaN(i)?n:i},setNumber(e,n){t().setStorageItem(xt+e,String(n))},getBoolean(e,n){const s=t().getStorageItem(xt+e);return null===s?n:"true"===s},setBoolean(e,n){t().setStorageItem(xt+e,String(n))},getJSON(e,n){const s=t().getStorageItem(xt+e);if(null===s)return n;try{return JSON.parse(s)}catch{return n}},setJSON(e,n){t().setStorageItem(xt+e,JSON.stringify(n))},remove(e){t().removeStorageItem(xt+e)},has:e=>null!==t().getStorageItem(xt+e),clear(){t().clearStorage(xt)}};function vt(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=St(t[e]),o=St(i);"null"!==n&&"undefined"!==n&&(n!==o&&null!=i&&s.push({field:e,expected:n,actual:o,value:i}))}return s}function St(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Mt(e,t){const n=[`Invalid component data for "${e}":`];for(const e of t)n.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return n.join("\n")}let Pt=null;function Tt(e){Pt=e}function Ct(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Pt&&Pt(e,t)}function Et(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 At=1;const Rt=new WeakMap;function It(e){let t=Rt.get(e);return void 0===t&&(t=At++,Rt.set(e,t)),t}const kt=[];function Ft(e,t=[],n=[]){kt.length=0;for(const t of e)kt.push(It(t));kt.sort((e,t)=>e-t);let s=kt.join(",");if(t.length>0){kt.length=0;for(const e of t)kt.push(It(e));kt.sort((e,t)=>e-t),s+="|+"+kt.join(",")}if(n.length>0){kt.length=0;for(const e of n)kt.push(It(e));kt.sort((e,t)=>e-t),s+="|-"+kt.join(",")}return s}class Bt{constructor(){this.cppRegistry_=null,this.module_=null,this.entities_=new Map,this.tsStorage_=new Map,this.entityComponents_=new Map,this.queryPool_=[],this.queryPoolIdx_=0,this.worldVersion_=0,this.queryCache_=new Map,this.builtinMethodCache_=new Map,this.iterationDepth_=0,this.nextEntityId_=0,this.nextGeneration_=0,this.spawnCallbacks_=[],this.despawnCallbacks_=[],this.worldTick_=0,this.componentAddedTicks_=new Map,this.componentChangedTicks_=new Map,this.componentRemovedBuffer_=new Map}connectCpp(e,t){this.cppRegistry_=e,this.module_=t??null,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.module_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==this.cppRegistry_}getCppRegistry(){return this.cppRegistry_}spawn(){if(this.isIterating())throw new Error("Cannot spawn entity during query iteration. Use Commands to defer entity creation until after iteration completes.");let e;if(this.cppRegistry_)try{e=this.cppRegistry_.create()}catch(e){throw Ct(e,"spawn"),e}else e=++this.nextEntityId_;let t=0;if(this.module_&&this.cppRegistry_)try{t=this.module_.registry_getGeneration(this.cppRegistry_,e)}catch{}else t=++this.nextGeneration_;this.entities_.set(e,t),this.worldVersion_++;for(const t of this.spawnCallbacks_)try{t(e)}catch{}return e}despawn(e){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const t of this.despawnCallbacks_)try{t(e)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Ct(t,`despawn(entity=${e})`)}this.entities_.delete(e),this.worldVersion_++;const t=this.entityComponents_.get(e);if(t){for(const n of t){this.tsStorage_.get(n)?.delete(e),this.componentAddedTicks_.get(n)?.delete(e),this.componentChangedTicks_.get(n)?.delete(e);let t=this.componentRemovedBuffer_.get(n);t||(t=[],this.componentRemovedBuffer_.set(n,t)),t.push({entity:e,tick:this.worldTick_})}this.entityComponents_.delete(e)}}onSpawn(e){return this.spawnCallbacks_.push(e),()=>{const t=this.spawnCallbacks_.indexOf(e);-1!==t&&this.spawnCallbacks_.splice(t,1)}}onDespawn(e){return this.despawnCallbacks_.push(e),()=>{const t=this.despawnCallbacks_.indexOf(e);-1!==t&&this.despawnCallbacks_.splice(t,1)}}valid(e){return this.cppRegistry_?this.cppRegistry_.valid(e):this.entities_.has(e)}entityCount(){return this.entities_.size}getWorldVersion(){return this.worldVersion_}beginIteration(){this.iterationDepth_++}endIteration(){this.iterationDepth_--,this.iterationDepth_<0&&(console.warn("World.endIteration: mismatched begin/end calls"),this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_.keys())}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(n){Ct(n,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Ct(t,`removeParent(entity=${e})`)}}insert(e,t,n){return ze(t)?this.insertBuiltin(e,t,n):this.insertScript(e,t,n)}set(e,t,n){if(ze(t)){if(this.cppRegistry_)try{const s=t._default,i=n;let o=i;for(const e of Object.keys(i))e in s||(o===i&&(o={...i}),delete o[e]);this.getBuiltinMethods(t._cppName).add(e,Et(o))}catch(n){Ct(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 ze(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return ze(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(ze(t)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(t._cppName);return n.has(e)?n.get(e):null}catch(n){return Ct(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.");ze(t)?this.removeBuiltin(e,t):this.removeScript(e,t)}getBuiltinMethods(e){let t=this.builtinMethodCache_.get(e);if(t)return t;const n=this.cppRegistry_,s=n[`add${e}`],i=n[`get${e}`],o=n[`has${e}`],r=n[`remove${e}`];if("function"!=typeof s||"function"!=typeof i||"function"!=typeof o||"function"!=typeof r)throw new Error(`C++ Registry missing methods for component "${e}". Expected: add${e}, get${e}, has${e}, remove${e}`);return t={add:s.bind(n),get:i.bind(n),has:o.bind(n),remove:r.bind(n)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,n){const s=t._default,i={};if(null!=n&&"object"==typeof n){for(const[e,t]of Object.entries(n))void 0!==t&&e in s&&(i[e]=t);const e=vt(t._name,s,i);if(e.length>0)throw new Error(Mt(t._name,e))}const o={...t._default,...i};let r=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(t._cppName);r=!n.has(e),n.add(e,Et(o))}catch(n){Ct(n,`insertBuiltin(${t._name}, entity=${e})`)}return r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),o}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(e,t){let n=!1;for(const s of Object.keys(t)){const i=t[s];if(null!=i&&"object"==typeof i&&!Array.isArray(i)&&"r"in i&&"g"in i&&"b"in i&&"a"in i){const t=e[s];if(null!=t&&"object"==typeof t&&"x"in t&&!("r"in t)){n=!0;break}}}if(!n)return e;const s={};for(const n of Object.keys(e)){const i=e[n],o=t[n];if(null==i||"object"!=typeof i||Array.isArray(i)||null==o||"object"!=typeof o||Array.isArray(o))s[n]=i;else{const e=i,t=o;s[n]="r"in t&&"g"in t&&"b"in t&&"a"in t&&"x"in e&&!("r"in e)?{r:e.x,g:e.y,b:e.z,a:e.w}:i}}return s}(this.getBuiltinMethods(t._cppName).get(e),t._default)}catch(n){return Ct(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 Ct(n,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(n){Ct(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=vt(t._name,t._default,e);if(i.length>0)throw new Error(Mt(t._name,i));s=e}const i=t.create(s),o=this.getStorage(t),r=!o.has(e);o.set(e,i);let a=this.entityComponents_.get(e);return a||(a=[],this.entityComponents_.set(e,a)),-1===a.indexOf(t._id)&&a.push(t._id),r&&(this.worldVersion_++,this.recordAddedTick_(t,e)),this.recordChangedTick_(t,e),i}getScript(e,t){const n=this.tsStorage_.get(t._id);if(!n)throw new Error(`Component not found: ${t._name}`);return n.get(e)}hasScript(e,t){const n=this.tsStorage_.get(t._id);return n?.has(e)??!1}removeScript(e,t){const n=this.tsStorage_.get(t._id);n?.delete(e),this.recordRemovedTick_(t,e),this.worldVersion_++;const s=this.entityComponents_.get(e);if(s){const e=s.indexOf(t._id);-1!==e&&s.splice(e,1)}}getStorage(e){let t=this.tsStorage_.get(e._id);return t||(t=new Map,this.tsStorage_.set(e._id,t)),t}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(e){const t=new Set;for(const[n,s]of this.builtinMethodCache_)try{s.has(e)&&t.add(n)}catch{}if(this.cppRegistry_)for(const[n,s]of Ue)if(ze(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=Ee();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??Ft(e,t,n),o=this.queryCache_.get(i);if(o&&o.version===this.worldVersion_)return o.result;let r=null,a=1/0;for(const t of e)if(!ze(t)){const e=this.tsStorage_.get(t._id),n=e?e.size:0;n<a&&(a=n,r=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const l=this.queryPool_[this.queryPoolIdx_++];l.length=0;const c=r?r.keys():this.entities_.keys();for(const s of c){let i=!0;for(const t of e)if(!this.has(s,t)){i=!1;break}if(i)for(const e of t)if(!this.has(s,e)){i=!1;break}if(i)for(const e of n)if(this.has(s,e)){i=!1;break}i&&l.push(s)}return this.queryCache_.set(i,{version:this.worldVersion_,result:l.slice()}),l}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(e,t,n){const s=this.componentAddedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}isChangedSince(e,t,n){const s=this.componentChangedTicks_.get(t._id);if(!s)return!1;const i=s.get(e);return void 0!==i&&i>n}getRemovedEntitiesSince(e,t){const n=this.componentRemovedBuffer_.get(e._id);if(!n)return[];const s=[];for(const e of n)e.tick>t&&s.push(e.entity);return s}cleanRemovedBuffer(e){for(const[t,n]of this.componentRemovedBuffer_){let s=0;for(let t=0;t<n.length;t++)n[t].tick>=e&&(n[s++]=n[t]);n.length=s,0===s&&this.componentRemovedBuffer_.delete(t)}}recordAddedTick_(e,t){let n=this.componentAddedTicks_.get(e._id);n||(n=new Map,this.componentAddedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordChangedTick_(e,t){let n=this.componentChangedTicks_.get(e._id);n||(n=new Map,this.componentChangedTicks_.set(e._id,n)),n.set(t,this.worldTick_)}recordRemovedTick_(e,t){let n=this.componentRemovedBuffer_.get(e._id);n||(n=[],this.componentRemovedBuffer_.set(e._id,n)),n.push({entity:t,tick:this.worldTick_}),this.componentAddedTicks_.get(e._id)?.delete(t),this.componentChangedTicks_.get(e._id)?.delete(t)}}function zt(e){return{_type:"mut",_component:e}}function Ut(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Wt(e){return{_filterType:"added",_component:e}}function $t(e){return{_filterType:"changed",_component:e}}function Dt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function Lt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function Ot(e){return Ut(e)||Dt(e)||Lt(e)?e._component:e}function Ht(e,t=[],n=[]){const s=[],i=[],o=[];return e.forEach((e,t)=>{Ut(e)&&s.push(t),Dt(e)?i.push({index:t,component:e._component}):Lt(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:s,_with:t,_without:n,_addedFilters:i,_changedFilters:o,with:(...s)=>Ht(e,[...t,...s],n),without:(...s)=>Ht(e,t,[...n,...s])}}function jt(...e){return Ht(e)}class Vt{constructor(e,t,n=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=n,this.actualComponents_=t._components.map(Ot),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_=Ft(this.allRequired_,t._with,t._without)}passesChangeFilters_(e){const{_addedFilters:t,_changedFilters:n}=this.descriptor_;if(0===t.length&&0===n.length)return!0;const s=this.lastRunTick_;for(const n of t)if(!this.world_.isAddedSince(e,n.component,s))return!1;for(const t of n)if(!this.world_.isChangedSince(e,t.component,s))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:e}=this.descriptor_,t=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),s=t.length,i=e.length>0,o=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,r=this.result_,a=this.mutData_,l=a.length;let c=null;this.world_.beginIteration();try{for(const u of n)if(!o||this.passesChangeFilters_(u)){if(null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}r[0]=u;for(let e=0;e<s;e++)r[e+1]=this.world_.get(u,t[e]);if(i){for(let t=0;t<l;t++)a[t].data=r[e[t]+1];c=u}yield r}}finally{if(this.world_.endIteration(),null!==c&&i)for(let e=0;e<l;e++){const t=a[e];this.world_.set(c,t.component,t.data)}}}forEach(e){for(const[t,...n]of this)e(t,...n)}single(){for(const e of this)return e;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Nt(e){return{_type:"removed",_component:e}}class Xt{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 Yt(){return{_type:"commands"}}class qt{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=ze(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 Gt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new qt(this,null);return this.spawned_.push(e),e}entity(e){return new qt(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,n){this.pending_.push({type:"insert",entity:e,component:t,data:n})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const n=this.world_.spawn();t.entity=n;for(const t of e)this.world_.insert(n,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}function Kt(e){return{_id:Symbol(`Event_${e}`),_name:e}}class Jt{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 Qt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new Jt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new Jt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function Zt(e){return{_type:"event_writer",_event:e}}function en(e){return{_type:"event_reader",_event:e}}class tn{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class nn{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var sn;function on(){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"}(sn||(sn={}));let rn=0;function an(e,t,n){const s=++rn;return{_id:Symbol(`System_${s}_${n?.name??""}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}function ln(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function cn(e){ln().push({schedule:sn.Update,system:e})}function un(e){ln().push({schedule:sn.Startup,system:e})}function dn(e,t){ln().push({schedule:e,system:t})}class hn{constructor(e,t,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=e,this.resources_=t,this.eventRegistry_=n??null}setTimingEnabled(e){this.timings_=e?new Map:null}getTimings(){return this.timings_}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t)),this.currentLastRunTick_=this.systemTicks_.get(e._id)??-1;for(let n=0;n<e._params.length;n++)t[n]=this.resolveParam(e._params[n]);const n=this.timings_?performance.now():0;try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Gt&&t[e].flush()}finally{this.timings_&&this.timings_.set(e._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(e._id,this.world_.getWorldTick())}}resolveParam(e){switch(e._type){case"query":return new Vt(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 Gt(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 tn(n)}case"event_reader":{const t=e,n=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new nn(n)}case"removed":{const t=e;return new Xt(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class fn{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 pn=pt(new fn,"Input");class mn{constructor(e){this.target_=e??null}build(e){const n=new fn;e.insertResource(pn,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(sn.Last,an([],()=>{n.keysPressed.clear(),n.keysReleased.clear(),n.mouseButtonsPressed.clear(),n.mouseButtonsReleased.clear(),n.scrollDeltaX=0,n.scrollDeltaY=0},{name:"InputClearSystem"}))}}const gn=new mn,yn=pt({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1},"UICameraInfo");var _n;function wn(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"}(_n||(_n={}));let xn=null,bn=null,vn=1;const Sn=new Map;function Mn(e){xn=e,bn=e.getResourceManager(),Bn()}function Pn(){0!==An&&xn&&(xn._free(An),An=0),Sn.clear(),vn=1,En=!1,In.clear(),kn=null,bn=null,xn=null}function Tn(){if(!bn)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return bn}const Cn={createShader:(e,t)=>Tn().createShader(e,t),releaseShader(e){e>0&&Tn().releaseShader(e)},create(e){const t=vn++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??_n.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 Sn.set(t,n),t},get:e=>Sn.get(e),setUniform(e,t,n){const s=Sn.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0,xn?.invalidateMaterialCache(e))},getUniform(e,t){const n=Sn.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=Sn.get(e);n&&(n.blendMode=t,xn?.invalidateMaterialCache(e))},getBlendMode(e){const t=Sn.get(e);return t?.blendMode??_n.Normal},setDepthTest(e,t){const n=Sn.get(e);n&&(n.depthTest=t,xn?.invalidateMaterialCache(e))},getShader(e){const t=Sn.get(e);return t?.shader??0},release(e){Sn.delete(e),xn?.invalidateMaterialCache(e)},isValid:e=>Sn.has(e),releaseAll(){Sn.clear(),xn?.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??_n.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Sn.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=vn++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Sn.set(n,s),n},toAssetData(e,t){const n=Sn.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=Sn.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let En=!1,An=0;const Rn=16384,In=new Map;let kn=null;function Fn(e){const t=(0===An&&xn&&(An=xn._malloc(Rn)),An);if(0===t||!xn)return{ptr:0,count:0};let n=0,s=0;const i=xn.HEAPU8,o=xn.HEAPU32,r=xn.HEAPF32;for(const[a,l]of e){if(wn(l))continue;let e=In.get(a);e||(kn||(kn=new TextEncoder),e=kn.encode(a),In.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(n+(4+u+4+16)>Rn){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Rn} bytes), skipping remaining uniforms`);break}o[t+n>>2]=c,n+=4,i.set(e,t+n),n+=u;let d=0,h=[0,0,0,0];if("number"==typeof l)d=0,h[0]=l;else if(Array.isArray(l)){d=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)h[e]=l[e]}else"w"in l?(d=3,h=[l.x,l.y,l.z,l.w]):"z"in l?(d=2,h=[l.x,l.y,l.z,0]):"y"in l&&(d=1,h=[l.x,l.y,0,0]);o[t+n>>2]=d,n+=4;for(let e=0;e<4;e++)r[t+n>>2]=h[e],n+=4;s++}return{ptr:t,count:s}}function Bn(){if(!xn||En)return;xn.materialDataProvider=(e,t,n,s,i)=>{const o=Sn.get(e);if(!o)return xn.HEAPU32[t>>2]=0,xn.HEAPU32[n>>2]=0,xn.HEAPU32[s>>2]=0,void(xn.HEAPU32[i>>2]=0);xn.HEAPU32[t>>2]=o.shader,xn.HEAPU32[n>>2]=o.blendMode;const{ptr:r,count:a}=Fn(o.uniforms);xn.HEAPU32[s>>2]=r,xn.HEAPU32[i>>2]=a},En=!0}const zn={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 Un{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,n=he.assetLoadTimeout){const s=this.cache_.get(e);if(void 0!==s)return s;const i=this.failed_.get(e);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(e);const o=this.pending_.get(e);if(o&&!o.aborted)return o.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&&(this.failed_.set(e,{error:t,expiry:Date.now()+he.assetFailureCooldown}),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(),this.failed_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Wn{constructor(e,t=""){this.cache_=new Un,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&&(Cn.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Cn.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const n=await l(t);if(!n)throw new Error(`Failed to read material file: ${t}`);const s=JSON.parse(n);if("material"!==s.type)throw new Error(`Invalid material file type: ${s.type}`);const i=this.resolveShaderPath(e,s.shader),o=await this.shaderLoader_.load(i);return{handle:Cn.createFromAsset(s,o),shaderHandle:o,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const n=e.substring(0,e.lastIndexOf("/"));return n?`${n}/${t}`:t}}function $n(e){const t=new Set;for(const n of e.frames)n.texture&&t.add(n.texture);return Array.from(t)}function Dn(e,t,n){return{name:e,fps:t.fps??12,loop:t.loop??!0,frames:t.frames.map(e=>{const t={texture:n.get(e.texture)??0};if(e.atlasFrame){const n=e.atlasFrame;t.uvOffset={x:n.x/n.pageWidth,y:1-(n.y+n.height)/n.pageHeight},t.uvScale={x:n.width/n.pageWidth,y:n.height/n.pageHeight}}return t})}}const Ln=new Map;function On(e){Ln.set(e.name,e)}function Hn(e){Ln.delete(e)}function jn(e){return Ln.get(e)}function Vn(){Ln.clear()}const Nn=Ae("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function Xn(e,t){const n=e.getEntitiesWithComponents([Nn]);for(const s of n){const n=e.get(s,Nn);if(!n.enabled||!n.playing||!n.clip)continue;const i=Ln.get(n.clip);if(!i||0===i.frames.length)continue;const o=1/(i.fps*n.speed),r=0===n.frameTimer&&0===n.currentFrame;n.frameTimer+=t;let a=r;if(n.frameTimer>=o&&(n.frameTimer-=o,n.currentFrame++,n.currentFrame>=i.frames.length&&(n.loop&&i.loop?n.currentFrame=0:(n.currentFrame=i.frames.length-1,n.playing=!1)),a=!0),a&&e.has(s,Xe)){const t=i.frames[n.currentFrame],o=e.get(s,Xe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(s,Xe,o)}a&&e.insert(s,Nn,n)}}class Yn{static init(e,t=null){this.backend_=e,this.mixer_=t,this.bufferCache_.clear(),this.bgmHandle_=null,this.bgmVolume_=1,this.disposed_=!1,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0)}static async preload(e){if(this.bufferCache_.has(e))return;const t=await this.backend_.loadBuffer(e);this.bufferCache_.set(e,t)}static async preloadAll(e){await Promise.all(e.map(e=>this.preload(e)))}static async preloadFromData(e,t){if(this.bufferCache_.has(e))return;const n=await this.backend_.loadBufferFromData(e,t);this.bufferCache_.set(e,n)}static playSFX(e,t){const n={bus:"sfx",volume:t?.volume,playbackRate:t?.pitch,pan:t?.pan,priority:t?.priority??0},s=this.bufferCache_.get(e);if(!s){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const s=this.bufferCache_.get(e);s&&t.resolve(this.backend_.play(s,n))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(s,n)}static playBGM(e,t){const n=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const n=t?.volume??1,s=this.bgmVolume_;this.bgmVolume_=n,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,s):this.bgmHandle_&&this.bgmHandle_.stop();const i=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:i?0:n,loop:!0}),i&&this.fadeIn(this.bgmHandle_,i,n)},s=this.bufferCache_.get(e);s?n(s):this.preload(e).then(()=>{if(this.disposed_)return;const t=this.bufferCache_.get(e);t&&n(t)}).catch(t=>{console.warn(`Failed to preload BGM: ${e}`,t)})}static stopAll(){this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null)}static stopBGM(e){if(this.bgmHandle_)if(this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),e&&e>0){const t=this.bgmHandle_;this.bgmHandle_=null,this.fadeOut(t,e,this.bgmVolume_)}else this.bgmHandle_.stop(),this.bgmHandle_=null}static setMasterVolume(e){this.mixer_&&(this.mixer_.master.volume=e)}static setMusicVolume(e){this.mixer_&&(this.mixer_.music.volume=e)}static setSFXVolume(e){this.mixer_&&(this.mixer_.sfx.volume=e)}static setUIVolume(e){this.mixer_&&(this.mixer_.ui.volume=e)}static muteBus(e,t){const n=this.mixer_?.getBus(e);n&&(n.muted=t)}static getBufferHandle(e){return this.bufferCache_.get(e)}static dispose(){this.disposed_=!0,this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0),this.bgmHandle_&&(this.bgmHandle_.stop(),this.bgmHandle_=null);for(const e of this.bufferCache_.values())this.backend_?.unloadBuffer(e);this.bufferCache_.clear(),this.backend_?.dispose(),this.mixer_=null}static fadeIn(e,t,n){e.setVolume(0);const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(r*n),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(i)}static fadeOut(e,t,n){const s=performance.now(),i=()=>{const o=(performance.now()-s)/1e3,r=Math.min(o/t,1);e.setVolume(n*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(i):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(i)}static createDeferredHandle(){let e=null;return{id:-1,stop(){e?.stop()},pause(){e?.pause()},resume(){e?.resume()},setVolume(t){e?.setVolume(t)},setPan(t){e?.setPan(t)},setLoop(t){e?.setLoop(t)},setPlaybackRate(t){e?.setPlaybackRate(t)},get isPlaying(){return e?.isPlaying??!1},get currentTime(){return e?.currentTime??0},get duration(){return e?.duration??0},resolve(t){e=t}}}}Yn.mixer_=null,Yn.bufferCache_=new Map,Yn.bgmHandle_=null,Yn.bgmVolume_=1,Yn.fadeAnimId_=0,Yn.disposed_=!1;const qn=new Map,Gn=new Map;function Kn(e,t,n){qn.set(e,{width:t,height:n})}function Jn(e){return qn.get(e)}function Qn(){qn.clear()}function Zn(e,t){Gn.set(e,t)}function es(e){return Gn.get(e)}function ts(){Gn.clear()}let ns=null;function ss(e){ns=e}function is(){ns=null}const os={initLayer(e,t,n,s,i){ns?.tilemap_initLayer(e,t,n,s,i)},destroyLayer(e){ns?.tilemap_destroyLayer(e)},setTile(e,t,n,s){ns?.tilemap_setTile(e,t,n,s)},getTile:(e,t,n)=>ns?ns.tilemap_getTile(e,t,n):0,fillRect(e,t,n,s,i,o){ns?.tilemap_fillRect(e,t,n,s,i,o)},setTiles(e,t){if(!ns)return;const n=t.byteLength,s=ns._malloc(n);new Uint16Array(ns.HEAPU8.buffer,s,t.length).set(t),ns.tilemap_setTiles(e,s,t.length),ns._free(s)},hasLayer:e=>!!ns&&ns.tilemap_hasLayer(e),submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w){ns?.tilemap_submitLayer(e,t,n,s,i,o,r,a,l,c,u,d,h,f,p,m,g,y,_,w)}},rs=Ae("Tilemap",{source:""}),as=Ae("TilemapLayer",{width:10,height:10,tileWidth:32,tileHeight:32,texture:0,tilesetColumns:1,layer:0,tiles:[],tint:{r:1,g:1,b:1,a:1},opacity:1,visible:!0,parallaxFactor:{x:1,y:1}});function ls(e){if(0===e)return{r:1,g:1,b:1,a:1};const t=(e>>>24&255)/255;return{r:(e>>>16&255)/255,g:(e>>>8&255)/255,b:(255&e)/255,a:0===t?1:t}}function cs(e){if(!e)return{r:1,g:1,b:1,a:1};const t=e.startsWith("#")?e.slice(1):e;if(8===t.length){const e=parseInt(t.slice(0,2),16)/255;return{r:parseInt(t.slice(2,4),16)/255,g:parseInt(t.slice(4,6),16)/255,b:parseInt(t.slice(6,8),16)/255,a:e}}if(6===t.length){return{r:parseInt(t.slice(0,2),16)/255,g:parseInt(t.slice(2,4),16)/255,b:parseInt(t.slice(4,6),16)/255,a:1}}return{r:1,g:1,b:1,a:1}}function us(e,t){if(0===e)return 0;let n=0;2147483648&e&&(n|=8192),1073741824&e&&(n|=16384),536870912&e&&(n|=32768);return(536870911&e)-t+1|n}function ds(e){const t=e.width,n=e.height,s=e.tilewidth??0,i=e.tileheight??0;if(!(t&&n&&s&&i))return null;const o=e.tilesets,r=[],a=[];if(o)for(const e of o){const t=e.firstgid??1;a.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??s,tileHeight:e.tileheight??i,columns:e.columns??1,tileCount:e.tilecount??0})}const l=e.layers,c=[];if(l)for(const e of l){if("tilelayer"!==e.type)continue;const s=e.width??t,i=e.height??n,o=!1!==e.visible,r=e.data,l=new Uint16Array(s*i);if(r){const e=a[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=us(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,d=cs(e.tintcolor),h="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:s,height:i,visible:o,tiles:l,opacity:u,tintColor:d,parallaxX:h,parallaxY:f})}const u=[],d=[];if(l)for(const e of l){if("objectgroup"!==e.type)continue;const t=e.objects;if(!t)continue;const n=[];for(const e of t){const t=new Map,s=e.properties;if(s)for(const e of s)t.set(e.name,e.value);let i="rect",o=null;if(e.ellipse)i="ellipse";else if(e.point)i="point";else if(e.polygon){i="polygon";const t=e.polygon;o=[];for(const e of t)o.push(e.x,e.y)}else if(e.polyline){i="polygon";const t=e.polyline;o=[];for(const e of t)o.push(e.x,e.y)}n.push({shape:i,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:o,properties:t})}u.push({name:e.name??"",objects:n})}if(o)for(const e of o){const t=e.firstgid??1,n=e.tiles;if(n)for(const e of n){const n=e.properties;if(n)for(const s of n)"collision"===s.name&&!0===s.value&&d.push(e.id+t)}}return{width:t,height:n,tileWidth:s,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:d}}function hs(e,t){const n=e.lastIndexOf("/"),s=((n>=0?e.substring(0,n+1):"")+t).split("/"),i=[];for(const e of s)".."===e?i.pop():"."!==e&&""!==e&&i.push(e);return i.join("/")}async function fs(e,t){const n=ns;if(!n)return null;const s=new TextEncoder,i=s.encode(e),o=n._malloc(i.byteLength);n.HEAPU8.set(i,o);const r=n.tiled_loadMap(o,i.byteLength);if(n._free(o),0===r)return null;try{const e=n.tiled_getExternalTilesetCount(r);for(let i=0;i<e;i++){const e=n.tiled_getExternalTilesetSource(r,i);if(!t)return n.tiled_freeMap(r),null;const o=await t(e),a=s.encode(o),l=n._malloc(a.byteLength);n.HEAPU8.set(a,l);const c=n.tiled_loadExternalTileset(r,i,l,a.byteLength);if(n._free(l),!c)return n.tiled_freeMap(r),null}if(!n.tiled_finalize(r))return n.tiled_freeMap(r),null;const i={width:n.tiled_getMapWidth(r),height:n.tiled_getMapHeight(r),tileWidth:n.tiled_getMapTileWidth(r),tileHeight:n.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},o=n.tiled_getLayerCount(r);for(let e=0;e<o;e++){const t=n.tiled_getLayerWidth(r,e),s=n.tiled_getLayerHeight(r,e),o=t*s,a=2*o,l=n._malloc(a);n.tiled_getLayerTiles(r,e,l,o);const c=new Uint16Array(o);c.set(new Uint16Array(n.HEAPU8.buffer,l,o)),n._free(l),i.layers.push({name:n.tiled_getLayerName(r,e),width:t,height:s,visible:n.tiled_getLayerVisible(r,e),tiles:c,opacity:n.tiled_getLayerOpacity(r,e),tintColor:n.tiled_getLayerTintColor?ls(n.tiled_getLayerTintColor(r,e)):{r:1,g:1,b:1,a:1},parallaxX:n.tiled_getLayerParallaxX(r,e),parallaxY:n.tiled_getLayerParallaxY(r,e)})}const a=n.tiled_getTilesetCount(r);for(let e=0;e<a;e++)i.tilesets.push({name:n.tiled_getTilesetName(r,e),image:n.tiled_getTilesetImage(r,e),tileWidth:n.tiled_getTilesetTileWidth(r,e),tileHeight:n.tiled_getTilesetTileHeight(r,e),columns:n.tiled_getTilesetColumns(r,e),tileCount:n.tiled_getTilesetTileCount(r,e)});return n.tiled_freeMap(r),i}catch{return n.tiled_freeMap(r),null}}const ps=Math.PI/180;function ms(e,t,n,s,i,o){const r=function(e,t,n,s){const i=new Uint8Array(t*n),o=[],r=(o,r)=>{if(o>=t||r>=n)return!1;const a=r*t+o;if(i[a])return!1;const l=8191&e[a];return 0!==l&&s.has(l)};for(let e=0;e<n;e++)for(let s=0;s<t;s++){if(!r(s,e))continue;let a=1;for(;r(s+a,e);)a++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=n)break;for(let e=0;e<a;e++)if(!r(s+e,t)){c=!1;break}c&&l++}for(let n=0;n<l;n++)for(let o=0;o<a;o++)i[(e+n)*t+(s+o)]=1;o.push({col:s,row:e,width:a,height:l})}return o}(t.tiles,t.width,t.height,s),a=[],l=n.tileWidth,c=n.tileHeight,u=n.height*c;for(const t of r){const n=t.width*l,s=t.height*c,r=i+t.col*l+.5*n,d=o+(u-t.row*c)-.5*s,h=e.spawn();e.insert(h,je,{position:{x:r,y:d,z:0}}),e.insert(h,lt,{bodyType:ht.Static}),e.insert(h,ct,{halfExtents:{x:.5*n,y:.5*s}}),a.push(h)}return a}function gs(e,t,n,s={}){const i=[],o=t.tilesets[0];let r=0;for(const s of t.layers){if(!s.visible)continue;const a=e.spawn();e.insert(a,je,{});const l=o?n.get(o.image)??0:0,c=o?.columns??1;e.insert(a,as,{width:s.width,height:s.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:l,tilesetColumns:c,layer:r,tiles:Array.from(s.tiles),tint:{...s.tintColor},opacity:s.opacity,visible:s.visible,parallaxFactor:{x:s.parallaxX,y:s.parallaxY}}),i.push(a),r++}if(!1!==s.generateObjectCollision&&t.objectGroups.length>0){const n=function(e,t,n,s){const i=[],o=t.height*t.tileHeight;for(const r of t.objectGroups)for(const t of r.objects){if("point"===t.shape)continue;const r=e.spawn(),a=t.x,l=t.y,c=n+a+.5*t.width,u=s+(o-l)-.5*t.height,d=-t.rotation*ps;if(e.insert(r,je,{position:{x:c,y:u,z:0}}),e.insert(r,lt,{bodyType:ht.Static}),"ellipse"===t.shape){const n=.5*Math.max(t.width,t.height);e.insert(r,ut,{radius:n})}else if("polygon"===t.shape&&t.vertices){let n=1/0,s=1/0,i=-1/0,o=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],a=t.vertices[e+1];r<n&&(n=r),r>i&&(i=r),a<s&&(s=a),a>o&&(o=a)}const a=i-n,l=o-s,c=.5*(n+i),u=.5*(s+o);e.insert(r,ct,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,ct,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==d){const t=.5*d;e.insert(r,je,{position:{x:c,y:u,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}i.push(r)}return i}(e,t,0,0);i.push(...n)}const a=new Set(s.collisionTileIds??t.collisionTileIds);if(a.size>0)for(const n of t.layers){if(!n.visible)continue;const s=ms(e,n,t,a,0,0);i.push(...s)}return i}const ys=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}],["Image",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpriteAnimator",{fields:[{field:"clip",type:"anim-clip"}]}],["AudioSource",{fields:[{field:"clip",type:"audio"}]}],["ParticleEmitter",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["Tilemap",{fields:[{field:"source",type:"tilemap"}]}]]);function _s(e,t){ys.set(e,t)}function ws(e){const t=ys.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 xs(e){return ys.get(e)?.fields??[]}function bs(e){return ys.get(e)?.spine??null}const vs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Ss(e,t){vs.set(e,t)}function Ms(e){return vs.get(e)}function Ps(e,t){const n=vs.get(e.type);if(!n)return;const s=e.data;for(const i of n){const n=s[i];if("number"==typeof n&&0!==n){const o=t.get(n);void 0===o&&console.warn(`[Scene] Entity reference not found: ${e.type}.${i} references entity ${n} which does not exist`),s[i]=void 0!==o?o:0}}}function Ts(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,it,{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)Ps(i,n),Rs(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 Cs(e,t){return Ts(e,t)}async function Es(e,t,n){const s=n?.assetServer,i=n?.assetBaseUrl??s?.baseUrl,o=new Map;s&&await async function(e,t,n,s,i){const o=new Map;for(const e of As.keys())o.set(e,new Set);const r=[],a=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ys.get(e.type);if(!t)continue;const n=e.data;if(t.spine){const e=n[t.spine.skeletonField],s=n[t.spine.atlasField];if(e&&s){const t=`${e}:${s}`;a.has(t)||(a.add(t),r.push({skeleton:e,atlas:s}))}}if(t.fields)for(const e of t.fields){const t=n[e.field];"string"==typeof t&&t&&o.get(e.type)?.add(t)}}const l=new Map,c=[...As.entries()].map(async([e,i])=>{const r=await i.load(o.get(e),t,n,s);l.set(e,r)}),u=r.map(async e=>{const s=await t.loadSpine(e.skeleton,e.atlas,n);s.success||console.warn(`Failed to load Spine: ${s.error}`)});if(await Promise.all([...c,...u]),i){for(const e of s.values())i.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&i.materialHandles.add(t);const t=o.get("font");if(t)for(const e of t)i.fontPaths.add(e);for(const e of a)i.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ys.get(e.type);if(!t?.fields)continue;const n=e.data;for(const e of t.fields){const t=l.get(e.type);if(!t)continue;const s=n[e.field];if("string"!=typeof s||!s)continue;const i=t.get(s);void 0!==i&&(n[e.field]=i)}}}(t,s,i,o,n?.collectAssets);const r=Ts(e,t);if(s&&t.textureMetadata)for(const[e,n]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&n.sliceBorder&&s.setTextureMetadataByPath(t,n.sliceBorder)}return r}const As=new Map([["texture",{async load(e,t,n,s){const i=new Map,o=[...e].map(async e=>{try{const o=e.startsWith("data:")?e:n?`${n}/${e}`:`/${e}`,r=await t.loadTexture(o);i.set(e,r.handle),s.set(e,o),Kn(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),i.set(e,0)}});return await Promise.all(o),i}}],["material",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadMaterial(e,n);s.set(e,i.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["font",{async load(e,t,n){const s=new Map,i=[...e].map(async e=>{try{const i=await t.loadBitmapFont(e,n);s.set(e,i)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),s.set(e,0)}});return await Promise.all(i),s}}],["anim-clip",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=await t.loadJson(e),o=$n(i),r=new Map,a=o.map(async e=>{try{const i=n?`${n}/${e}`:`/${e}`,o=await t.loadTexture(i);r.set(e,o.handle),s.set(e,i)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(a);On(Dn(e,i,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(i),new Map}}],["audio",{async load(e,t,n){const s=[...e].map(e=>n?`${n}/${e}`:`/${e}`);return await Yn.preloadAll(s).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,n,s){const i=[...e].map(async e=>{try{const i=ds(await t.loadJson(e));if(!i)return void console.warn(`Failed to parse tilemap: ${e}`);const o=[];for(const r of i.tilesets){const i=hs(e,r.image);let a=0;try{const e=n?`${n}/${i}`:`/${i}`,o=await t.loadTexture(e);a=o.handle,s.set(i,e),Kn(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}Zn(e,{tileWidth:i.tileWidth,tileHeight:i.tileHeight,layers:i.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(i),new Map}}]]);function Rs(e,t,n,s){if("LocalTransform"!==n.type&&"WorldTransform"!==n.type||(n.type="Transform"),"UIRect"===n.type){const e=n.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}if("UIMask"===n.type){const e=n.data;"scissor"===e.mode?e.mode=0:"stencil"===e.mode&&(e.mode=1)}const i=$e(n.type);if(i)e.insert(t,i,n.data);else{const e=s?` on entity "${s}"`:"";console.warn(`Unknown component type: ${n.type}${e}`)}}function Is(e,t){const n=e.getEntitiesWithComponents([Ye]);for(const s of n){const n=e.get(s,Ye);n&&(n.aspectRatio=t,e.insert(s,Ye,n))}}function ks(e,t){const n=e.getEntitiesWithComponents([it]);for(const s of n){const n=e.get(s,it);if(n&&n.value===t)return s}return null}class Fs{constructor(e){this.textureCache_=new Un,this.shaderCache_=new Un,this.jsonCache_=new Un,this.textCache_=new Un,this.binaryCache_=new Un,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new Un,this.prefabCache_=new Un,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=d(he.textCanvasSize,he.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 Wn(t)}registerEmbeddedAssets(e){for(const[t,n]of Object.entries(e))this.embedded_.set(t,n);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const n of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,n))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const n of[!0,!1]){const s=this.textureCacheKey(e,n),i=this.textureCache_.get(s);if(!i)continue;const o=(this.textureRefCounts_.get(s)??1)-1;o<=0?(t.releaseTexture(i.handle),this.textureCache_.delete(s),this.textureRefCounts_.delete(s)):this.textureRefCounts_.set(s,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Cn.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const n=this.textureCache_.get(this.textureCacheKey(e,!0));return!!n&&(this.setTextureMetadata(n.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,n){const s=`${e}:${t}`;if(this.loadedSpines_.has(s))return{success:!0};try{const i=this.resolveUrl(t,n),o=await this.fetchText(i);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),l=[];for(const e of a){const t=r?`${r}/${e}`:e,s=this.resolveUrl(t,n);try{const n=await this.loadTextureRaw(s);this.module_.getResourceManager().registerTextureWithPath(n.handle,t),l.push({name:e,info:n})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const c=this.resolveUrl(e,n),u="binary"===T(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(s),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),n=this.spineController_.getAtlasPageCount(e);for(let s=0;s<n;s++){const n=this.spineController_.getAtlasPageTextureName(e,s),i=l.find(e=>e.name===n);if(i){const n=t.getTextureGLId(i.info.handle);this.spineController_.setAtlasPageTexture(e,s,n,i.info.width,i.info.height)}}this.spineSkeletons_.set(s,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}releaseSpine(e){if(!this.loadedSpines_.has(e))return;this.loadedSpines_.delete(e);const t=this.spineSkeletons_.get(e);void 0!==t&&this.spineController_&&(this.spineController_.unloadSkeleton(t),this.spineSkeletons_.delete(e))}async loadBitmapFont(e,t){const n=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(n,async()=>{const t=T(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(n):this.loadFntFile(n)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),n=e.substring(0,e.lastIndexOf("/")),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!s)throw new Error("Invalid bmfont asset: no fnt file specified");const i=n?`${n}/${s}`:s;return this.loadFntFile(i)}async loadFntFile(e){const t=await this.fetchText(e),n=t.match(/file="([^"]+)"/);if(!n)throw new Error(`No page texture found in .fnt file: ${e}`);const s=n[1],i=e.substring(0,e.lastIndexOf("/")),o=i?`${i}/${s}`:s,r=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,r.handle,r.width,r.height)}setAssetRefResolver(e){this.assetRefResolver_=e}async loadPrefab(e,t){const n=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(n,async()=>{const e=await this.fetchJson(n);return this.assetRefResolver_&&this.resolvePrefabRefs_(e),e})}resolvePrefabRefs_(e){const t=this.assetRefResolver_;for(const n of e.entities){for(const e of n.components){if(!e.data)continue;for(const n of ws(e.type)){const s=e.data[n];if("string"==typeof s&&s){const i=t(s);i&&(e.data[n]=i)}}const n=bs(e.type);if(n)for(const s of[n.skeletonField,n.atlasField]){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}}if(n.nestedPrefab?.prefabPath){const e=t(n.nestedPrefab.prefabPath);e&&(n.nestedPrefab.prefabPath=e)}}}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(n):this.jsonCache_.getOrLoad(n,()=>this.fetchJson(n))}async loadText(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(n):this.textCache_.getOrLoad(n,()=>this.fetchText(n))}async loadBinary(e,t){const n=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(n):this.binaryCache_.getOrLoad(n,()=>this.fetchBinary(n))}async loadScene(e,t){return Es(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const n of Object.values(e.groups))n.assets&&t.push(...Object.values(n.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,n]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(n.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let n=this.labelIndex_.get(e);n||(n=[],this.labelIndex_.set(e,n)),n.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},n=[];for(const s of e){const e=s.address??s.path;switch(s.type){case"texture":n.push(this.loadTexture(s.path).then(n=>{t.textures.set(e,n)}));break;case"material":n.push(this.loadMaterial(s.path).then(n=>{t.materials.set(e,n)}));break;case"spine":{const i=s.metadata?.atlas;i&&n.push(this.loadSpine(s.path,i).then(n=>{t.spine.set(e,n)}));break}case"bitmap-font":n.push(this.loadBitmapFont(s.path).then(n=>{t.fonts.set(e,n)}));break;case"prefab":n.push(this.loadPrefab(s.path).then(n=>{t.prefabs.set(e,n)}));break;case"audio":case"binary":default:n.push(this.loadBinary(s.path).then(n=>{t.binary.set(e,n)}));break;case"json":n.push(this.loadJson(s.path).then(n=>{t.json.set(e,n)}));break;case"text":n.push(this.loadText(s.path).then(n=>{t.text.set(e,n)}))}}const s=await Promise.allSettled(n);for(const e of s)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const n=this.textureCacheKey(e,t),s=await this.textureCache_.getOrLoad(n,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(n,(this.textureRefCounts_.get(n)??0)+1),s}async loadTextureInternal(e,t){const n=await this.loadImage(e);return this.createTextureFromImage(n,t)}async loadImage(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.loadImageFromSrc(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((n,s)=>{const i=t().createImage();i.crossOrigin="anonymous",i.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(i,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void n(e)}catch{}n(i)},i.onerror=()=>s(new Error(`Failed to load image: ${e}`)),i.src=e})}createTextureFromImage(e,t){const{width:n,height:s}=e,i=this.getWebGL2Context();return i?this.createTextureWebGL2(i,e,n,s,t):this.createTextureFallback(e,n,s,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,n,s,i){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,i?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,a=r.getNewId(r.textures);r.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,n,s),width:n,height:s}}createTextureFallback(e,t,n,s){(this.canvas_.width<t||this.canvas_.height<n)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(n))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const i=this.ctx_.getImageData(0,0,t,n),o=new Uint8Array(i.data.buffer);this.unpremultiplyAlpha(o);const r=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const l=r.createTexture(t,n,a,o.length,1,s);return this.module_._free(a),{handle:l,width:t,height:n}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const n=e[t+3];if(n>0&&n<255){const s=255/n;e[t]=Math.min(255,Math.round(e[t]*s)),e[t+1]=Math.min(255,Math.round(e[t+1]*s)),e[t+2]=Math.min(255,Math.round(e[t+2]*s))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.getEmbedded(t);if(n){const t=this.decodeDataUrlText(n),{vertex:s,fragment:i}=this.parseEsShader(t);if(!s||!i)throw new Error(`Invalid shader format: ${e}`);return Cn.createShader(s,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const s=await l(t);if(!s)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(s);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Cn.createShader(i,o)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),n=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:n?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")&&!e.startsWith("asset://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}getEmbedded(e){return this.embedded_.get(e)??this.embedded_.get(W(e))}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return JSON.parse(this.decodeDataUrlText(n));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await l(t);return JSON.parse(s)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch JSON: ${e} (${n.status})`);return n.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlText(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch text: ${e} (${n.status})`);return n.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const n=this.getEmbedded(t);if(n)return this.decodeDataUrlBinary(n);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(e);if(!n.ok)throw new Error(`Failed to fetch binary: ${e} (${n.status})`);return n.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const n=this.module_.FS;if(!n)return!1;try{return this.ensureVirtualDir(e),n.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;const s=n.split("/").filter(e=>e);let i="";for(const e of s){i=i?`${i}/${e}`:e;try{t.analyzePath(i).exists||t.mkdir(i)}catch{try{t.mkdir(i)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const n=t??this.baseUrl;return n?`${n}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const n of e.split("\n")){const e=n.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Bs=pt(null,"Assets");class zs{build(e){const t=e.wasmModule;t?e.insertResource(Bs,new Fs(t)):console.warn("AssetPlugin: No WASM module available")}}const Us=new zs;class Ws{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 $s(e,t){const n=e.getResource(Bs);n&&n.registerEmbeddedAssets(t)}async function Ds(e,t,n){const{entities:s,rootId:i}=await Os(t,n?.overrides??[],n,void 0,new Set),o={version:t.version,name:t.name,entities:s.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},r=await Es(e,o,{assetServer:n?.assetServer,assetBaseUrl:n?.assetBaseUrl}),a=r.get(i);return void 0!==n?.parent&&e.setParent(a,n.parent),{root:a,entities:r}}const Ls=10;async function Os(e,t,n,s,i,o=0){if(o>Ls)throw new Error(`Prefab nesting depth exceeded ${Ls}. Check for deep or circular nesting in: ${e.name}`);const r=new Map;let a;if(void 0===s){a=0;for(const t of e.entities)t.nestedPrefab||(r.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=s;for(const t of e.entities)t.nestedPrefab||r.set(t.prefabEntityId,a++)}const l=[];for(const s of e.entities){if(s.nestedPrefab){if(!n?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${s.nestedPrefab.prefabPath}`);if(i?.has(s.nestedPrefab.prefabPath))throw new Error(`[Prefab] Circular reference detected: "${s.nestedPrefab.prefabPath}" is already being instantiated in the current prefab chain`);i?.add(s.nestedPrefab.prefabPath);const e=await n.assetServer.loadPrefab(s.nestedPrefab.prefabPath,n.assetBaseUrl),t=await Os(e,s.nestedPrefab.overrides,n,a,i,o+1);r.set(s.prefabEntityId,t.rootId),a=t.nextId;const c=t.entities.find(e=>e.id===t.rootId);c&&(c.parent=null!==s.parent?r.get(s.parent)??null:null),l.push(...t.entities);continue}const c=r.get(s.prefabEntityId),u=s.prefabEntityId===e.rootEntityId,d={id:c,prefabEntityId:s.prefabEntityId,name:s.name,parent:u?null:null!==s.parent?r.get(s.parent)??null:null,children:s.children.map(e=>r.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(s.components)),visible:s.visible};Hs(d.components,r),js(d,t),l.push(d)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Hs(e,t){for(const n of e){const e=Ms(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 js(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 Vs{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 Ds(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Ns=pt(null,"Prefabs");class Xs{constructor(){this.name="PrefabsPlugin",this.dependencies=[Bs]}build(e){const t=e.getResource(Bs);e.insertResource(Ns,new Vs(e.world,t))}}const Ys=new Xs;let qs=null,Gs=0,Ks=0,Js=0;const Qs=new Float32Array(256);function Zs(e){qs=e,Gs=qs._malloc(64),Ks=qs._malloc(64),Js=qs._malloc(1024)}function ei(){qs&&(Gs&&(qs._free(Gs),Gs=0),Ks&&(qs._free(Ks),Ks=0),Js&&(qs._free(Js),Js=0)),qs=null}function ti(){if(!qs)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return qs}const ni={r:1,g:1,b:1,a:1},si={begin(e){const t=ti();try{t.HEAPF32.set(e,Gs/4),t.draw_begin(Gs)}catch(e){Ct(e,"Draw.begin")}},end(){try{ti().draw_end()}catch(e){Ct(e,"Draw.end")}},line(e,t,n,s=1){try{ti().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.line")}},rect(e,t,n,s=!0){try{ti().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{ti().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){Ct(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,i=32){try{ti().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ct(e,"Draw.circle")}},circleOutline(e,t,n,s=1,i=32){try{ti().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,i)}catch(e){Ct(e,"Draw.circleOutline")}},texture(e,t,n,s=ni){try{ti().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){Ct(e,"Draw.texture")}},textureRotated(e,t,n,s,i=ni){try{ti().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,i.r,i.g,i.b,i.a)}catch(e){Ct(e,"Draw.textureRotated")}},setLayer(e){ti().draw_setLayer(e)},setDepth(e){ti().draw_setDepth(e)},getDrawCallCount:()=>qs?qs.draw_getDrawCallCount():0,getPrimitiveCount:()=>qs?qs.draw_getPrimitiveCount():0,setBlendMode(e){ti().draw_setBlendMode(e)},setDepthTest(e){ti().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=ti();s.HEAPF32.set(n,Ks/4),s.draw_mesh(e,t,Ks)}catch(n){Ct(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=ti(),i=Cn.get(t);if(!i)return;if(si.setBlendMode(i.blendMode),si.setDepthTest(i.depthTest),0===i.uniforms.size)return void si.drawMesh(e,i.shader,n);let o;if(s.HEAPF32.set(n,Ks/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,n]of i.uniforms){const s=ri(t);if(!(s<0)){if(wn(n))Qs[o++]=10,Qs[o++]=s,Qs[o++]=n.slot??e++,Qs[o++]=n.textureId;else if("number"==typeof n)Qs[o++]=1,Qs[o++]=s,Qs[o++]=n;else if(Array.isArray(n)){Qs[o++]=n.length,Qs[o++]=s;for(let e=0;e<n.length;e++)Qs[o++]=n[e]}else"w"in n?(Qs[o++]=4,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y,Qs[o++]=n.z,Qs[o++]=n.w):"z"in n?(Qs[o++]=3,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y,Qs[o++]=n.z):(Qs[o++]=2,Qs[o++]=s,Qs[o++]=n.x,Qs[o++]=n.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!i.cachedBuffer_||i.cachedBuffer_.length<o)&&(i.cachedBuffer_=new Float32Array(o)),i.cachedBuffer_.set(Qs.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void s.draw_mesh(e,i.shader,Ks);s.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Js/4),s.draw_meshWithUniforms(e,i.shader,Ks,Js,o)}catch(n){Ct(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ii={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},oi=new Set;function ri(e){const t=ii[e];return void 0!==t?t:(oi.has(e)||(oi.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ii).join(", ")}`)),-1)}const ai=new Map;function li(e,t,n){ai.set(e,{fn:t,scene:n??""})}function ci(e){ai.delete(e)}function ui(){ai.clear()}var di;!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"}(di||(di={}));let hi=null,fi=0,pi=0,mi=0;function gi(e){hi=e,fi=hi._malloc(262144),pi=hi._malloc(65536),mi=hi._malloc(256)}function yi(){hi&&(fi&&hi._free(fi),pi&&hi._free(pi),mi&&hi._free(mi),fi=0,pi=0,mi=0),hi=null}function _i(){if(!hi)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return hi}const wi={create(e){const t=_i(),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,fi/4);const i=e.layout.length,o=new Int32Array(i);for(let t=0;t<i;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,mi,i).set(o),t.geometry_init(n,fi,s,mi,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,pi,s).set(e.indices),t.geometry_setIndices16(n,pi,s)}else{new Uint32Array(t.HEAPU8.buffer,pi,s).set(e.indices),t.geometry_setIndices32(n,pi,s)}}return n},updateVertices(e,t,n=0){const s=_i(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);s.HEAPF32.set(t,fi/4),s.geometry_updateVertices(e,fi,i,n)},release(e){e>0&&_i().geometry_release(e)},isValid:e=>!(!hi||e<=0)&&hi.geometry_isValid(e),createQuad(e=1,t=1){const n=e/2,s=t/2;return wi.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:di.Float2},{name:"a_texCoord",type:di.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const n=[],s=[];n.push(0,0,.5,.5);for(let s=0;s<=t;s++){const i=s/t*Math.PI*2,o=Math.cos(i)*e,r=Math.sin(i)*e,a=(Math.cos(i)+1)/2,l=(Math.sin(i)+1)/2;n.push(o,r,a,l)}for(let e=1;e<=t;e++)s.push(0,e,e+1);return wi.create({vertices:new Float32Array(n),layout:[{name:"a_position",type:di.Float2},{name:"a_texCoord",type:di.Float2}],indices:new Uint16Array(s)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of e)t=Math.min(t,o.x),n=Math.min(n,o.y),s=Math.max(s,o.x),i=Math.max(i,o.y);const o=[];for(const r of e){const e=(r.x-t)/(s-t),a=(r.y-n)/(i-n);o.push(r.x,r.y,e,a)}const r=[];for(let t=1;t<e.length-1;t++)r.push(0,t,t+1);return wi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:di.Float2},{name:"a_texCoord",type:di.Float2}],indices:new Uint16Array(r)})}};let xi=1;const bi=new Map,vi=new Map;function Si(){return bi}function Mi(){return vi}class Pi{constructor(){this.passes_=[],this.destroyed_=!1,this.id=xi++,bi.set(this.id,this)}addPass(e,t){return this.passes_.push({name:e,shader:t,enabled:!0,floatUniforms:new Map,vec4Uniforms:new Map}),this}removePass(e){const t=this.passes_.findIndex(t=>t.name===e);return-1!==t&&this.passes_.splice(t,1),this}setEnabled(e,t){const n=this.passes_.find(t=>t.name===e);return n&&(n.enabled=t),this}setUniform(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.floatUniforms.set(t,n),this}setUniformVec4(e,t,n){const s=this.passes_.find(t=>t.name===e);return s&&s.vec4Uniforms.set(t,{...n}),this}setAllPassesEnabled(e){for(const t of this.passes_)t.enabled=e}get passCount(){return this.passes_.length}get enabledPassCount(){let e=0;for(const t of this.passes_)t.enabled&&e++;return e}get passes(){return this.passes_}get isDestroyed(){return this.destroyed_}destroy(){if(!this.destroyed_){this.destroyed_=!0;for(const[e,t]of vi)t===this&&vi.delete(e);bi.delete(this.id)}}}const Ti="#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";let Ci=null;function Ei(e){Ci=e}function Ai(){for(const e of Si().values())e.destroy();Si().clear(),Mi().clear(),Ci&&Ii.isInitialized()&&Ii.shutdown(),Ci=null}function Ri(){if(!Ci)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Ci}const Ii={createStack:()=>new Pi,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");Mi().set(e,t)},unbind(e){Mi().delete(e)},getStack:e=>Mi().get(e)??null,init(e,t){try{return Ri().postprocess_init(e,t)}catch(n){return Ct(n,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ri().postprocess_shutdown()}catch(e){Ct(e,"PostProcess.shutdown")}},resize(e,t){try{Ri().postprocess_resize(e,t)}catch(n){Ct(n,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Ci)return!1;try{return Ci.postprocess_isInitialized()}catch(e){return Ct(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ri().postprocess_setBypass(e)}catch(e){Ct(e,"PostProcess.setBypass")}},setOutputViewport(e,t,n,s){try{Ri().postprocess_setOutputViewport(e,t,n,s)}catch(e){Ct(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=Mi().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(Ii.isInitialized()||Ii.init(1,1),Ii.setBypass(!1),function(e){const t=Ri();try{t.postprocess_clearPasses()}catch(e){return void Ct(e,"PostProcess._applyForCamera:clearPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addPass(n.name,n.shader)}catch(e){Ct(e,`PostProcess._applyForCamera:addPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setUniformFloat(n.name,e,s)}catch(t){Ct(t,`PostProcess._applyForCamera:setUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Ct(t,`PostProcess._applyForCamera:setUniformVec4("${n.name}", "${e}")`)}}}(t)):Ii.setBypass(!0)},_resetAfterCamera(){try{Ri().postprocess_clearPasses(),Ri().postprocess_setBypass(!0)}catch(e){Ct(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of Mi().keys())e(t)||Mi().delete(t)},screenStack:null,setScreenStack(e){Ii.screenStack=e},_beginScreenCapture(){try{Ri().postprocess_beginScreenCapture()}catch(e){Ct(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Ri().postprocess_endScreenCapture()}catch(e){Ct(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=Ii.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Ri();try{t.postprocess_clearScreenPasses()}catch(e){return void Ct(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const n of e.passes)if(n.enabled){try{t.postprocess_addScreenPass(n.name,n.shader)}catch(e){Ct(e,`PostProcess._applyScreenStack:addScreenPass("${n.name}")`);continue}for(const[e,s]of n.floatUniforms)try{t.postprocess_setScreenUniformFloat(n.name,e,s)}catch(t){Ct(t,`PostProcess._applyScreenStack:setScreenUniform("${n.name}", "${e}")`)}for(const[e,s]of n.vec4Uniforms)try{t.postprocess_setScreenUniformVec4(n.name,e,s.x,s.y,s.z,s.w)}catch(t){Ct(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${n.name}", "${e}")`)}}},_executeScreenPasses(){try{Ri().postprocess_executeScreenPasses()}catch(e){Ct(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Cn.createShader(Ti,"#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:()=>Cn.createShader(Ti,"#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:()=>Cn.createShader(Ti,"#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"),createBloom:()=>Cn.createShader(Ti,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_threshold;\nuniform float u_intensity;\nuniform float u_radius;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 texelSize = 1.0 / u_resolution;\n\n vec3 bloom = vec3(0.0);\n float total = 0.0;\n for (float x = -3.0; x <= 3.0; x += 1.0) {\n for (float y = -3.0; y <= 3.0; y += 1.0) {\n vec2 offset = vec2(x, y) * texelSize * u_radius;\n vec4 s = texture(u_texture, v_texCoord + offset);\n float brightness = dot(s.rgb, vec3(0.2126, 0.7152, 0.0722));\n float w = max(brightness - u_threshold, 0.0);\n bloom += s.rgb * w;\n total += w;\n }\n }\n if (total > 0.0) bloom /= total;\n\n fragColor = vec4(color.rgb + bloom * u_intensity, color.a);\n}\n"),createChromaticAberration:()=>Cn.createShader(Ti,"#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")},ki=new Map;function Fi(e){ki.set(e.type,e)}function Bi(e){return ki.get(e)}function zi(){return Array.from(ki.keys())}function Ui(){return Array.from(ki.values())}Fi({type:"blur",label:"Blur",factory:()=>Ii.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),Fi({type:"bloom",label:"Bloom",factory:()=>Ii.createBloom(),uniforms:[{name:"u_threshold",label:"Threshold",min:0,max:2,step:.01,defaultValue:.8},{name:"u_intensity",label:"Intensity",min:0,max:10,step:.1,defaultValue:1.5},{name:"u_radius",label:"Radius",min:0,max:20,step:.1,defaultValue:4}]}),Fi({type:"vignette",label:"Vignette",factory:()=>Ii.createVignette(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:3,step:.01,defaultValue:.8},{name:"u_softness",label:"Softness",min:0,max:2,step:.01,defaultValue:.3}]}),Fi({type:"grayscale",label:"Grayscale",factory:()=>Ii.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),Fi({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>Ii.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Wi=new Map,$i=new Map;function Di(e,t){let n=Wi.get(e),s=$i.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(n||(n=Ii.createStack(),Wi.set(e,n)),s||(s=new Map,$i.set(e,s));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const e of i){const t=Bi(e.type);if(!t)continue;let i=s.get(e.type);void 0===i&&(i=t.factory(),s.set(e.type,i)),n.addPass(e.type,i);for(const s of t.uniforms){const t=e.uniforms[s.name]??s.defaultValue;n.setUniform(e.type,s.name,t)}}Ii.bind(e,n)}else if(n&&(Ii.unbind(e),n.destroy(),Wi.delete(e)),s){for(const e of s.values())Cn.releaseShader(e);$i.delete(e)}}function Li(e){const t=Wi.get(e);t&&(Ii.unbind(e),t.destroy(),Wi.delete(e));const n=$i.get(e);if(n){for(const e of n.values())Cn.releaseShader(e);$i.delete(e)}}function Oi(){for(const e of Wi.keys())Li(e)}const Hi=pt({enabled:!0},"PostProcessVolumeConfig"),ji=new Map,Vi=new Map;function Ni(e){const t=Vi.get(e);if(void 0!==t)return t;const n=Bi(e);if(!n)return null;const s=n.factory();return Vi.set(e,s),s}function Xi(e,t){if(0===t.size){const t=ji.get(e);return void(t&&(Ii.unbind(e),t.destroy(),ji.delete(e)))}let n=ji.get(e);for(n||(n=Ii.createStack(),ji.set(e,n));n.passCount>0;){const e=n.passes;n.removePass(e[e.length-1].name)}for(const[e,s]of t){if(!s.enabled)continue;const t=Ni(e);if(null!==t){n.addPass(e,t);for(const[t,i]of s.uniforms)n.setUniform(e,t,i)}}n.enabledPassCount>0?Ii.bind(e,n):Ii.unbind(e)}const Yi=an([jt(rt,je)],e=>{const t=[];for(const[n,s,i]of e)t.push({data:s,tx:{x:i.position.x,y:i.position.y}});if(0===t.length)return;const n=[];for(const{data:e,tx:s}of t)e.isGlobal&&n.push({data:e,factor:1});if(n.length>0){const e=function(e){const t=new Map,n=[...e].sort((e,t)=>e.data.priority-t.data.priority);for(const{data:e,factor:s}of n)if(!(s<=0))for(const n of e.effects){if(!n.enabled)continue;const e=t.get(n.type);if(e)for(const[t,i]of Object.entries(n.uniforms)){const n=e.uniforms.get(t)??0;e.uniforms.set(t,n+(i-n)*s)}else{const e=new Map;for(const[t,i]of Object.entries(n.uniforms))e.set(t,i*s);t.set(n.type,{enabled:!0,uniforms:e})}}return t}(n);for(const[t]of ji)Xi(t,e)}},{name:"PostProcessVolumeSystem"});class qi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Hi,{enabled:!0}),e.addSystemToSchedule(sn.PostUpdate,Yi)}cleanup(){Oi(),function(){for(const[e,t]of ji)Ii.unbind(e),t.destroy();ji.clear();for(const e of Vi.values())Cn.releaseShader(e);Vi.clear()}(),Ii.setScreenStack(null)}}const Gi=new qi;var Ki;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ki||(Ki={}));let Ji=null,Qi=0;function Zi(e){Ji=e,Qi=Ji._malloc(64)}function eo(){Ji&&Qi&&(Ji._free(Qi),Qi=0),Ji=null}const to={init(e,t){Ji?.renderer_init(e,t)},resize(e,t){Ji?.renderer_resize(e,t)},begin(e,t){if(Ji&&Qi)try{Ji.HEAPF32.set(e,Qi/4),Ji.renderer_begin(Qi,t??0)}catch(e){Ct(e,"Renderer.begin")}},flush(){try{Ji?.renderer_flush()}catch(e){Ct(e,"Renderer.flush")}},end(){try{Ji?.renderer_end()}catch(e){Ct(e,"Renderer.end")}},submitSprites(e){if(Ji)try{Ji.renderer_submitSprites(e._cpp)}catch(e){Ct(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ji)try{Ji.renderer_submitBitmapText(e._cpp)}catch(e){Ct(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ji)try{Ji.renderer_submitSpine?.(e._cpp)}catch(e){Ct(e,"Renderer.submitSpine")}},submitParticles(e){if(Ji)try{Ji.renderer_submitParticles?.(e._cpp)}catch(e){Ct(e,"Renderer.submitParticles")}},setStage(e){Ji?.renderer_setStage(e)},createRenderTarget:(e,t,n=1)=>Ji?.renderer_createTarget(e,t,n)??0,releaseRenderTarget(e){Ji?.renderer_releaseTarget(e)},getTargetTexture:e=>Ji?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ji?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,n,s){Ji?.renderer_setClearColor?.(e,t,n,s)},setViewport(e,t,n,s){Ji?.renderer_setViewport(e,t,n,s)},setScissor(e,t,n,s,i){Ji?.renderer_setScissor(e,t,n,s,i)},clearBuffers(e){Ji?.renderer_clearBuffers(e)},measureBitmapText:(e,t,n,s)=>Ji?Ji.getResourceManager().measureBitmapText(e,t,n,s):{width:0,height:0},getStats:()=>Ji?{drawCalls:Ji.renderer_getDrawCalls(),triangles:Ji.renderer_getTriangles(),sprites:Ji.renderer_getSprites(),text:Ji.renderer_getText(),spine:Ji.renderer_getSpine?.()??0,meshes:Ji.renderer_getMeshes(),culled:Ji.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let no=null;function so(e){no=e}function io(){no=null}const oo={enable(){no?.gl_enableErrorCheck(!0)},disable(){no?.gl_enableErrorCheck(!1)},check:e=>no?.gl_checkErrors(e)??0,diagnose(){no?.renderer_diagnose()}};class ro{constructor(){this.spineRenderer_=null,this.tilemapRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}setTilemapRenderer(e){this.tilemapRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}beginScreenCapture(){Ii.screenStack&&Ii.screenStack.enabledPassCount>0&&(Ii.isInitialized()||Ii.init(1,1),Ii._applyScreenStack(),Ii._beginScreenCapture())}endScreenCapture(){Ii.screenStack&&Ii.screenStack.enabledPassCount>0&&(Ii._endScreenCapture(),Ii._executeScreenPasses())}render(e){const{registry:t,viewProjection:n,width:s,height:i,elapsed:o}=e;s===this.lastWidth_&&i===this.lastHeight_||(to.resize(s,i),this.lastWidth_=s,this.lastHeight_=i),to.setViewport(0,0,s,i),to.clearBuffers(3),to.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,0,0,s,i),this.tilemapRenderer_&&this.tilemapRenderer_(),to.submitSprites(t),to.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):to.submitSpine(t),to.submitParticles(t),to.flush(),this.executeDrawCallbacks(n,o),to.end()}renderCamera(e){const{registry:t,viewProjection:n,viewportPixels:s,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==Ii.getStack(r);a&&(Ii._applyForCamera(r),Ii.resize(s.w,s.h),Ii.setOutputViewport(s.x,s.y,s.w,s.h)),to.setViewport(s.x,s.y,s.w,s.h),to.setScissor(s.x,s.y,s.w,s.h,!0),to.clearBuffers(i),to.setScissor(0,0,0,0,!1),to.begin(n),this.maskProcessor_&&this.maskProcessor_(t._cpp,n,s.x,s.y,s.w,s.h),this.tilemapRenderer_&&this.tilemapRenderer_(),to.submitSprites(t),to.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):to.submitSpine(t),to.submitParticles(t),to.flush(),this.executeDrawCallbacks(n,o),to.end(),a&&Ii._resetAfterCamera()}executeDrawCallbacks(e,t){const n=ai;if(n.size>0){si.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)}si.end();for(const e of s)ci(e)}}}const ao="__scene_transition_overlay__";class lo{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessBindings=new Map,this.savedAlphas=new Map,this.loadedAssets=null,this.status="loading",this.config=e}}class co{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,ot,{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),li(e,t,this.instance_.config.name)}bindPostProcess(e,t){Ii.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){Ii.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,ot)){const n=this.app_.world.get(e,ot);n.persistent=t,this.app_.world.insert(e,ot,n)}}}class uo{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}reset(){for(const e of this.scenes_.values()){for(const t of e.drawCallbacks.keys())ci(t);for(const t of e.postProcessBindings.keys())Ii.unbind(t)}this.transition_&&(ci(ao),this.transition_=null),this.configs_.clear(),this.scenes_.clear(),this.contexts_.clear(),this.additiveScenes_.clear(),this.pausedScenes_.clear(),this.sleepingScenes_.clear(),this.loadOrder_.length=0,this.activeScene_=null,this.initialScene_=null,this.switching_=!1,this.loadPromises_.clear()}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??he.sceneTransitionDuration,i=t.color??{...he.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:s,color:i,targetScene:e,options:t,resolve:n},li(ao,()=>{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;si.setLayer(9999),si.setDepth(9999),si.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,ci(ao),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,ci(ao),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 lo(t);this.scenes_.set(e,n);const s=new co(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Bs)?this.app_.getResource(Bs):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 lo(t);this.scenes_.set(e,n);const s=new co(n,this.app_);this.contexts_.set(e,s);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(Bs)?this.app_.getResource(Bs):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,ot)){if(this.app_.world.get(e,ot).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}n.entities.clear();for(const e of n.drawCallbacks.keys())ci(e);n.drawCallbacks.clear();for(const e of n.postProcessBindings.keys())Ii.unbind(e);n.postProcessBindings.clear(),this.releaseSceneAssets_(n),this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const o=this.loadOrder_.indexOf(e);-1!==o&&this.loadOrder_.splice(o,1),this.activeScene_===e&&(this.activeScene_=null)}async loadSceneData_(e,t,n,s){if(s){const n={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},i={collectAssets:n};this.app_.hasResource(Bs)&&(i.assetServer=this.app_.getResource(Bs));const o=await Es(this.app_.world,s,i);e.loadedAssets=n;for(const n of o.values())e.entities.add(n),this.app_.world.insert(n,ot,{scene:t,persistent:!1})}if(n.systems)for(const{schedule:e,system:s}of n.systems){const n=fo(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(Bs)?this.app_.getResource(Bs):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)Cn.release(e);e.loadedAssets=null}pause(e){const t=this.scenes_.get(e);t&&"running"===t.status&&(t.status="paused",this.pausedScenes_.add(e),this.setPostProcessPassesEnabled(t,!1))}resume(e){const t=this.scenes_.get(e);t&&"paused"===t.status&&(t.status="running",this.pausedScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0))}sleep(e){const t=this.scenes_.get(e);if(!t||"running"!==t.status)return;t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s={};let i=!1;if(n.has(e,Xe)){const t=n.get(e,Xe);s.sprite=t.color.a,t.color.a=0,n.insert(e,Xe,t),i=!0}if(n.has(e,Ze)){const t=n.get(e,Ze);s.spine=t.color.a,t.color.a=0,n.insert(e,Ze,t),i=!0}if(n.has(e,Qe)){const t=n.get(e,Qe);s.bitmapText=t.color.a,t.color.a=0,n.insert(e,Qe,t),i=!0}i&&t.savedAlphas.set(e,s)}}wake(e){const t=this.scenes_.get(e);if(!t||"sleeping"!==t.status)return;t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);const n=this.app_.world;for(const e of t.entities){if(!n.valid(e))continue;const s=t.savedAlphas.get(e);if(s){if(void 0!==s.sprite&&n.has(e,Xe)){const t=n.get(e,Xe);t.color.a=s.sprite,n.insert(e,Xe,t)}if(void 0!==s.spine&&n.has(e,Ze)){const t=n.get(e,Ze);t.color.a=s.spine,n.insert(e,Ze,t)}if(void 0!==s.bitmapText&&n.has(e,Qe)){const t=n.get(e,Qe);t.color.a=s.bitmapText,n.insert(e,Qe,t)}}}t.savedAlphas.clear()}setPostProcessPassesEnabled(e,t){for(const n of e.postProcessBindings.values())n.setAllPassesEnabled(t)}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 ho=pt(null,"SceneManager");function fo(e,t,n){return{_id:Symbol(`SceneScoped_${n._name}_${t}`),_name:`${n._name}@${t}`,_params:n._params,_fn:(...s)=>{"running"===e.getResource(ho).getSceneStatus(t)&&n._fn(...s)}}}const po=an([gt(ho),mt(wt)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),mo={name:"SceneManager",build(e){const t=new uo(e);e.insertResource(ho,t);const n={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ho),n=t.getInitial();n&&t.load(n).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(sn.Startup,n),e.addSystemToSchedule(sn.Last,po)}};class go{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 Qt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.statsEnabled_=!1,this.phaseTimings_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=h(),t=e-this.lastTime_;this.lastTime_=e;const n=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(n),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(sn.Last);else{this.runSchedule(sn.First),this.fixedAccumulator_+=n;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(sn.FixedPreUpdate),this.runSchedule(sn.FixedUpdate),this.runSchedule(sn.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(sn.PreUpdate),this.runSchedule(sn.Update),this.runSchedule(sn.PostUpdate),this.runSchedule(sn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Bt,this.resources_=new _t;for(const e of Object.values(sn))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new go}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(sn.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(sn.Startup,e)}removeSystem(e){let t=!1;for(const[n,s]of this.systems_){const i=s.filter(t=>t.system._id!==e);i.length!==s.length&&(this.systems_.set(n,i),this.sortedSystemsCache_.delete(n),t=!0)}return t}connectCpp(e,t){return this.world_.connectCpp(e,t),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return Tt(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}enableStats(){return this.statsEnabled_=!0,this.phaseTimings_=new Map,this.runner_?.setTimingEnabled(!0),this}getSystemTimings(){return this.runner_?.getTimings()??null}getPhaseTimings(){return this.phaseTimings_}getEntityCount(){return this.world_.entityCount()}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ho).register(e),this}setInitialScene(e){return this.getResource(ho).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new hn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(wt)||this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(sn.Startup)),this.eventRegistry_.swapAll(),this.world_.advanceTick(),this.updateTime(e),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(sn.Last);else{this.runSchedule(sn.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(sn.FixedPreUpdate),this.runSchedule(sn.FixedUpdate),this.runSchedule(sn.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(sn.PreUpdate),this.runSchedule(sn.Update),this.runSchedule(sn.PostUpdate),this.runSchedule(sn.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new hn(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(wt,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(sn.Startup),this.lastTime_=h(),this.mainLoop())}quit(){this.running_=!1,ui();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=[io,eo,Ai,yi,Pn,ei];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}finishPlugins_(){if(!this.pluginsFinished_){this.pluginsFinished_=!0;for(const e of this.installed_plugins_)try{e.finish?.(this)}catch(t){console.error(`[ESEngine] Plugin "${e.name??"unknown"}" finish error:`,t)}}}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let n=0;n<e.length;n++)t.set(e[n].system._name,n);for(const n of e)if(n.runBefore)for(const s of n.runBefore){const i=t.get(s);if(void 0!==i){const t=e[i];t.runAfter||(t.runAfter=[]),t.runAfter.includes(n.system._name)||t.runAfter.push(n.system._name)}}const n=[],s=new Set,i=new Set,o=r=>{if(s.has(r))return;if(i.has(r)){const t=e[r].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}i.add(r);const a=e[r];if(a.runAfter)for(const e of a.runAfter){const n=t.get(e);void 0!==n&&o(n)}i.delete(r),s.add(r),n.push(a)};for(let t=0;t<e.length;t++)o(t);return n}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let n=this.sortedSystemsCache_.get(e);n||(n=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,n));const s=this.phaseTimings_?performance.now():0;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)}}this.phaseTimings_&&this.phaseTimings_.set(sn[e],performance.now()-s)}updateTime(e){const t=this.resources_.get(wt);t.delta=e,t.elapsed+=e,t.frameCount++}}function yo(e){const t=globalThis.__esengine_pendingSystems;if(t&&0!==t.length){for(const n of t)e.addSystemToSchedule(n.schedule,n.system);t.length=0}}const _o=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function wo(e,t,n,s,i){const o=e*t/n,r=e;switch(s){case He.FixedWidth:return o;case He.FixedHeight:return r;case He.Expand:return Math.max(o,r);case He.Shrink:return Math.min(o,r);case He.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const xo=[];function bo(e){if(e<xo.length)return xo[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 xo.push(t),t}function vo(e,t,n,s,i,o){if(0===n||0===s)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,ot);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const n=e.registry_getCanvasEntity(t);return n<0?null:t.getCanvas(n)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*n/(i.viewportH*s);let a,u=0,d=0;if(i.projectionType===Le.Orthographic){if(d=i.orthoSize,l){d=wo(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=Mo(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=To(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Eo(o.position.x,o.position.y,o.position.z),f=bo(c.length);f.entity=e,f.viewProjection.set(Ro(a,h)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=d,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const So=new Float32Array(16);function Mo(e,t,n,s,i,o){const r=So;r.fill(0);const a=t-e,l=s-n,c=o-i;return r[0]=2/a,r[5]=2/l,r[10]=-2/c,r[12]=-(t+e)/a,r[13]=-(s+n)/l,r[14]=-(o+i)/c,r[15]=1,r}const Po=new Float32Array(16);function To(e,t,n,s){const i=Po;i.fill(0);const o=1/Math.tan(e/2),r=n-s;return i[0]=o/t,i[5]=o,i[10]=(s+n)/r,i[11]=-1,i[14]=2*s*n/r,i}const Co=new Float32Array(16);function Eo(e,t,n){const s=Co;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 Ao=new Float32Array(16);function Ro(e,t){const n=Ao;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 Io={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function ko(e,t,n,s,i,o,r={x:.5,y:.5}){const a=o.right-o.left,l=o.top-o.bottom,c=o.left+e.x*a,u=o.left+t.x*a,d=o.bottom+e.y*l,h=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+n.x-i.x*r.x,m=f+i.x):(f=c+n.x,m=u+s.x),e.y===t.y?(p=d+n.y-i.y*r.y,g=p+i.y):(p=d+n.y,g=h+s.y);const y=Math.max(0,m-f),_=Math.max(0,g-p);return{originX:f+r.x*y,originY:p+r.y*_,width:y,height:_,rect:{left:f,bottom:p,right:m,top:g}}}const Fo=De("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 Bo=null,zo=null;function Uo(e,t){e.has(t,Xe)||e.insert(t,Xe,{texture:ye,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 Wo(e,t){switch(e){case Io.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Io.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case Io.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 $o(e,t){switch(e){case Io.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case Io.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case Io.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 Do(e,t,n,s){switch(e){case Io.BottomToTop:case Io.TopToBottom:return{x:n,y:s*t};default:return{x:n*t,y:s}}}function Lo(e,t,n,s){if(!e.has(t,Fo))return;const i=e.get(t,Fo),o=Wo(n,s);i.anchorMin=o.anchorMin,i.anchorMax=o.anchorMax,o.anchorMin.x===o.anchorMax.x&&(i.size={...i.size,x:0}),o.anchorMin.y===o.anchorMax.y&&(i.size={...i.size,y:0}),e.insert(t,Fo,i)}function Oo(e,t,n,s){return t?n?{...e.pressedColor}:s?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Ho(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function jo(e,t,n){if(!t)return[""];if(n<=0)return t.split("\n");const s=t.split("\n"),i=[];for(const t of s){if(!t){i.push("");continue}let s="";for(let o=0;o<t.length;o++){const r=t[o],a=s+r;if(e.measureText(a).width>n&&s){if(Ho(r.charCodeAt(0))&&s.length>0&&Ho(s.charCodeAt(s.length-1))){let e=-1;for(let t=s.length-1;t>=0;t--)if(!Ho(s.charCodeAt(t))){e=t;break}e>=0?(i.push(s.substring(0,e+1)),s=s.substring(e+1)+r):(i.push(s),s=r)}else i.push(s),s=r}else s=a}s&&i.push(s)}return i.length>0?i:[""]}function Vo(e){let t=1;for(;t<e;)t*=2;return t}function No(e,t){let n=0,s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;n++,s=t}return n}function Xo(e,t){if(Bo&&zo){const e=Bo.getUIRectComputedWidth(zo,t);if(e>0)return e}return e.size.x}function Yo(e,t){if(Bo&&zo){const e=Bo.getUIRectComputedHeight(zo,t);if(e>0)return e}return e.size.y}function qo(e,t,n,s,i,o){if(!e.has(t,Xe))return;const r=e.get(t,Xe);let a,l;switch(n){case Io.BottomToTop:case Io.TopToBottom:a=i,l=o*s;break;default:a=i*s,l=o}r.size.x===a&&r.size.y===l||(r.size.x=a,r.size.y=l,e.insert(t,Xe,r))}function Go(e,t,n){let s=t;for(;e.has(s,Ke);){const t=e.get(s,Ke).entity;if(!e.valid(t))break;if(n(t))return;s=t}}function Ko(e,t,n,s){e.has(t,n)||e.insert(t,n,s)}function Jo(e,t,n,s,i){if(!e.has(t,Fo))return;const o=e.get(t,Fo),r=ko(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,n,o.pivot),a=r.rect.right-r.rect.left,l=r.rect.top-r.rect.bottom;if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===a&&n.size.y===l||(n.size.x=a,n.size.y=l,e.insert(t,Xe,n))}if(e.has(t,je)){const n=e.get(t,je);n.position.x=r.originX-s,n.position.y=r.originY-i,e.insert(t,je,n)}}function Qo(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 Zo=.1,er=30,tr={r:.3,g:.5,b:.8,a:1},nr={Left:0,Center:1,Right:2},sr={Top:0,Middle:1,Bottom:2},ir={Visible:0,Clip:1,Ellipsis:2},or=Ae("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:nr.Left,verticalAlign:sr.Top,wordWrap:!0,overflow:ir.Visible,lineHeight:1.2});class rr{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=d(he.textCanvasSize,he.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,Vo(this.frameMaxW_)),e.height=Math.max(e.height,Vo(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Vo(this.frameMaxW_),e.height=Vo(this.frameMaxH_),this.shrinkCounter_=0)):this.shrinkCounter_=0),this.frameMaxW_=0,this.frameMaxH_=0}renderText(e,t){try{return this.renderTextInner(e,t)}catch(e){return console.error("TextRenderer: render failed",e),{textureHandle:0,width:0,height:0}}}renderTextInner(e,t){const n=this.ctx,s=this.canvas;n.font=`${e.fontSize}px ${e.fontFamily}`;const i=t&&t.size.x>0&&t.size.y>0,o=i?t.size.x:0,r=i?t.size.y:0,a=e.wordWrap&&i;let l=jo(n,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(l)),h=Math.ceil(l.length*c),f=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===ir.Ellipsis&&h>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(s.width<f||s.height<p)&&(s.width=Math.max(s.width,Vo(f)),s.height=Math.max(s.height,Vo(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),y=Math.round(255*e.color.b),_=e.color.a;n.clearRect(0,0,s.width,s.height),n.font=`${e.fontSize}px ${e.fontFamily}`,n.textAlign=this.mapAlign(e.align),n.textBaseline="top",n.fillStyle=`rgba(${m}, ${g}, ${y}, ${_})`,i&&e.overflow===ir.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 sr.Top:x=u;break;case sr.Middle:x=u+(p-2*u-w)/2;break;case sr.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let b=x;for(const t of l){let s;switch(e.align){case nr.Left:s=u;break;case nr.Center:s=f/2;break;case nr.Right:s=f-u;break;default:s=u}n.fillText(t,s,b),b+=c}i&&e.overflow===ir.Clip&&n.restore();const v=n.getImageData(0,0,f,p),S=new Uint8Array(v.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 nr.Left:return"left";case nr.Center:return"center";case nr.Right:return"right"}}}const ar=Qo({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?Xo(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0});class lr{build(e){We("Text",or);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const n=new rr(t),s=e.world,i=new Map;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{n.beginFrame(),n.cleanupOrphaned(e=>s.valid(e)&&s.has(e,or));for(const e of i.keys())if(!s.valid(e)||!s.has(e,or)){if(s.valid(e)&&s.has(e,Xe)){const t=s.get(e,Xe);s.insert(e,Xe,{texture:ye,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([or]);for(const t of e){const e=s.get(t,or),o=s.has(t,Fo)?s.get(t,Fo):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!ar.changed(a,r)){if(s.has(t,Xe)&&s.get(t,Xe).texture!==ye)continue}Uo(s,t);const l=o?{size:{x:Xo(o,t),y:Yo(o,t)}}:null,c=n.renderForEntity(t,e,l),u=s.get(t,Xe);s.insert(t,Xe,{texture:c.textureHandle,color:{r:u.color.r,g:u.color.g,b:u.color.b,a:u.color.a},size:{x:c.width,y:c.height},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:u.layer,flipX:u.flipX,flipY:u.flipY,material:u.material,enabled:u.enabled}),i.set(t,ar.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const cr=new lr,ur=0,dr=1,hr=De("UIMask",{enabled:!0,mode:ur});function fr(e,t){const n=Math.max(e.x,t.x),s=Math.max(e.y,t.y),i=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:n,y:s,w:Math.max(0,i-n),h:Math.max(0,o-s)}}function pr(e,t){const n=t??new Float32Array(16),s=e[0],i=e[1],o=e[2],r=e[3],a=e[4],l=e[5],c=e[6],u=e[7],d=e[8],h=e[9],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],w=s*l-i*a,x=s*c-o*a,b=s*u-r*a,v=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=d*g-h*m,T=d*y-f*m,C=d*_-p*m,E=h*y-f*g,A=h*_-p*g,R=f*_-p*y;let I=w*R-x*A+b*E+v*C-S*T+M*P;return 0===I||(I=1/I,n[0]=(l*R-c*A+u*E)*I,n[1]=(o*A-i*R-r*E)*I,n[2]=(g*M-y*S+_*v)*I,n[3]=(f*S-h*M-p*v)*I,n[4]=(c*C-a*R-u*T)*I,n[5]=(s*R-o*C+r*T)*I,n[6]=(y*b-m*M-_*x)*I,n[7]=(d*M-f*b+p*x)*I,n[8]=(a*A-l*C+u*P)*I,n[9]=(i*C-s*A-r*P)*I,n[10]=(m*S-g*b+_*w)*I,n[11]=(h*b-d*S-p*w)*I,n[12]=(l*T-a*E-c*P)*I,n[13]=(s*E-i*T+o*P)*I,n[14]=(g*x-m*v-y*w)*I,n[15]=(d*v-h*x+f*w)*I),n}function mr(e,t,n,s,i,o,r){const a=(e-s)/o*2-1,l=(t-i)/r*2-1,c=n[0]*a+n[4]*l+n[12],u=n[1]*a+n[5]*l+n[13],d=n[3]*a+n[7]*l+n[15];return{x:c/d,y:u/d}}function gr(e,t,n,s,i,o,r,a){return e>=n-i*r&&e<=n+i*(1-r)&&t>=s-o*a&&t<=s+o*(1-a)}function yr(e,t){return 2*Math.atan2(e,t)}function _r(e,t,n,s,i,o,r){const a=n[0]*e+n[4]*t+n[12],l=n[1]*e+n[5]*t+n[13],c=n[3]*e+n[7]*t+n[15];return[s+(.5*(a/c)+.5)*o,i+(.5*(l/c)+.5)*r]}function wr(e,t,n,s,i,o,r,a,l,c){const u=yr(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-n,p=t-s,m=f*h-p*d+n,g=f*d+p*h+s;return m>=n-i*r&&m<=n+i*(1-r)&&g>=s-o*a&&g<=s+o*(1-a)}function xr(e,t,n,s,i,o,r){if(!e.has(t,Fo)||!e.has(t,je))return null;const a=e.get(t,Fo),l=e.get(t,je),c=Xo(a,t)*l.worldScale.x,u=Yo(a,t)*l.worldScale.y,d=l.worldPosition.x,h=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),y=-u*p,_=u*(1-p),w=yr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),b=Math.sin(w),v=[[d+m*x-y*b,h+m*b+y*x],[d+g*x-y*b,h+g*b+y*x],[d+g*x-_*b,h+g*b+_*x],[d+m*x-_*b,h+m*b+_*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of v){const[a,l]=_r(e,t,n,s,i,o,r);S=Math.min(S,a),M=Math.min(M,l),P=Math.max(P,a),T=Math.max(T,l)}return{x:Math.round(S),y:Math.round(M),w:Math.round(P-S),h:Math.round(T-M)}}function br(e,t){return(n,s,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([hr]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const n=t.get(e,hr);n.enabled&&(d.add(e),n.mode===dr?(u.push(e),h.add(e)):c.push(e))}try{c.length>0&&function(e,t,n,s,i,o,r,a,l,c){const u=[];for(const e of s){let n=!0;Go(t,e,e=>{if(i.has(e)){if(t.get(e,hr).mode===ur)return n=!1,!0}return!1}),n&&u.push(e)}function d(s,u){const h=e.getChildEntities(n,s);for(const n of h){let s=u;if(i.has(n)){if(t.get(n,hr).mode===ur){const e=xr(t,n,o,r,a,l,c);e&&(s=fr(u,e))}}e.renderer_setEntityClipRect(n,s.x,s.y,s.w,s.h),d(n,s)}}for(const e of u){const n=xr(t,e,o,r,a,l,c);n&&d(e,n)}}(e,t,n,c,d,s,i,o,r,a),u.length>0&&function(e,t,n,s,i){e.renderer_clearStencil();const o=[];for(const e of s){let n=!0;Go(t,e,e=>!!i.has(e)&&(n=!1,!0)),n&&o.push(e)}let r=1,a=!1;function l(){return r>255?(a||console.warn("Stencil mask overflow"),a=!0,null):r++}function c(t,s){if(a)return;e.renderer_setEntityStencilMask(t,s);const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}function u(t,s){if(a)return;const o=e.getChildEntities(n,t);for(const t of o)if(i.has(t)){const e=l();if(null===e)return;c(t,e)}else e.renderer_setEntityStencilTest(t,s),u(t,s)}for(const e of o){if(a)break;const t=l();if(null===t)return;c(e,t)}}(e,t,n,u,h)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class vr{build(e){if(We("UIMask",hr),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(br(e.wasmModule,e.world))}}const Sr=new vr,Mr=De("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Pr=De("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Tr={Normal:0,Hovered:1,Pressed:2,Disabled:3},Cr=Ae("Button",{state:Tr.Normal,transition:null});class Er{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 Ar=pt(new Er,"UIEvents");class Rr{build(e){We("UIRect",Fo);const t=e.world,n=e.wasmModule,s=t.getCppRegistry();!function(e,t){Bo=e,zo=t}(n,s);e.addSystemToSchedule(sn.PreUpdate,an([mt(yn)],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(sn.PostUpdate,an([mt(yn)],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(sn.PostUpdate,an([],()=>{n.transform_update(s)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ir=new Rr;let kr=!1,Fr=!1;function Br(e){kr=e}function zr(){return kr}function Ur(){return!kr}function Wr(e){Fr=e}function $r(){return Fr}const Dr=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&&(pr(t,e),n=!1),e)}}();function Lr(e,t,n,s){t.emit(n,s,n),Go(e,n,i=>{if(!e.has(i,Mr))return!1;const o=e.get(i,Mr);return o.enabled&&t.emit(i,s,n),o.blockRaycast})}class Or{build(e){We("Interactable",Mr),We("Button",Cr);const t=e.world,n=e.wasmModule,s=t.getCppRegistry(),i=new Er;e.insertResource(Ar,i);let o=null,r=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn)],(e,a)=>{if(i.drain(),zr()&&!$r())return;const l=t.getEntitiesWithComponents([Pr]);for(const e of l){const n=t.get(e,Pr);(n.justPressed||n.justReleased)&&(n.justPressed=!1,n.justReleased=!1,t.insert(e,Pr,n))}if(!a.valid)return;const c=f(),u=e.mouseX*c,d=a.screenH-e.mouseY*c;Dr.update(a.viewProjection);const h=mr(u,d,Dr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=h.x,a.worldMouseY=h.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);n.uiHitTest_update(s,h.x,h.y,p,m,g);const y=n.uiHitTest_getHitEntity(),_=4294967295===y?null:y;if(null===o||t.valid(o)||(o=null),o!==_){if(null!==o&&t.valid(o)&&t.has(o,Pr)){const e=t.get(o,Pr);e.hovered=!1,t.insert(o,Pr,e),i.emit(o,"hover_exit")}if(null!==_){Ko(t,_,Pr);const e=t.get(_,Pr);e.hovered=!0,t.insert(_,Pr,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Pr);e.pressed=!0,e.justPressed=!0,t.insert(_,Pr,e),r=_,Lr(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Pr)){const e=t.get(r,Pr);e.pressed=!1,e.justReleased=!0,t.insert(r,Pr,e),Lr(t,i,r,"release"),r===o&&Lr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(sn.Update,an([],()=>{const e=t.getEntitiesWithComponents([Cr]);for(const n of e){if(Ko(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const e=t.get(n,Pr),s=t.get(n,Cr),i=t.get(n,Mr),o=!a.has(n),r=s.state;if(i.enabled?e.pressed?s.state=Tr.Pressed:e.hovered?s.state=Tr.Hovered:s.state=Tr.Normal:s.state=Tr.Disabled,o&&a.add(n),(o||r!==s.state)&&s.transition&&t.has(n,Xe)){const o=t.get(n,Xe);o.color=Oo(s.transition,i.enabled,e.pressed,e.hovered),t.insert(n,Xe,o)}}},{name:"ButtonSystem"}))}}const Hr=new Or,jr=Ae("TextInput",{value:"",placeholder:"",placeholderColor:{r:.6,g:.6,b:.6,a:1},fontFamily:"Arial",fontSize:16,color:{r:1,g:1,b:1,a:1},backgroundColor:{r:.15,g:.15,b:.15,a:1},padding:6,maxLength:0,multiline:!1,password:!1,readOnly:!1,focused:!1,cursorPos:0,dirty:!0}),Vr=Ae("Focusable",{tabIndex:0,isFocused:!1});class Nr{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 Xr=pt(new Nr,"FocusManager");class Yr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(We("TextInput",jr),zr()&&!$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=d(he.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(Xr);if(!t||null===t.focusedEntity)return null;const s=t.focusedEntity;return n.valid(s)&&n.has(s,jr)?s:null}const g=()=>{l||null===m()||b()},y=()=>{l=!0},_=()=>{l=!1,b()},w=t=>{const s=m();if(null===s)return;if("Escape"===t.key)return void v();const i=n.get(s,jr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(Ar).emit(s,"submit"),void v()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const s=n.get(t,jr);s.focused=!1,s.dirty=!0;e.getResource(Xr).blur()}};function b(){const t=m();if(null===t)return;const s=n.get(t,jr);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(Ar).emit(t,"change")}s.cursorPos=p.selectionStart??i.length,s.dirty=!0,S()}function v(){const t=m();if(null!==t){const e=n.get(t,jr);e.focused=!1,e.dirty=!0}e.getResource(Xr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of s.values())e.releaseTexture(t);s.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,d){(i.width<u||i.height<d)&&(i.width=Vo(Math.max(i.width,u)),i.height=Vo(Math.max(i.height,d))),o.clearRect(0,0,i.width,i.height);const h=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,o.fillRect(0,0,u,d),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,d),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),y=l.padding;if(l.multiline){const e=jo(o,p,u-2*y);let t=y;for(const n of e)o.fillText(n,y,t),t+=g}else{const e=(d-l.fontSize)/2;o.fillText(p,y,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,n,s;if(l.multiline){const e=jo(o,l.value,u-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const n=e[t].length;if(i+n>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=n,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const c=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(c).width,n=y+r*g,s=g}else t=y+o.measureText(e).width,n=(d-l.fontSize)/2,s=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,n,2,s)}o.restore();const _=o.getImageData(0,0,u,d),w=new Uint8Array(_.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const b=s.get(e);void 0!==b&&x.releaseTexture(b);const v=x.createTexture(u,d,r,w.length,1,!0);s.set(e,v);const S=n.get(e,Xe);S.texture=v,S.size.x=u,S.size.y=d,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},n.insert(e,Xe,S)}e.addSystemToSchedule(sn.Update,an([mt(Xr)],e=>{const t=n.getEntitiesWithComponents([jr]);for(const e of t)Ko(n,e,Vr,{tabIndex:0,isFocused:!1}),Ko(n,e,Mr,{enabled:!0,blockRaycast:!0});const s=m();if(s!==M){if(null!==M&&n.valid(M)&&n.has(M,jr)){const e=n.get(M,jr);e.focused=!1,e.dirty=!0,p.blur()}null!==s&&function(e){const t=n.get(e,jr);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(sn.PreUpdate,an([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===h?0:(e-h)/1e3;h=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;n.get(o,jr).dirty=!0}const r=t.getResourceManager();for(const[e,t]of s)n.valid(e)&&n.has(e,jr)||(r.releaseTexture(t),s.delete(e));const a=n.getEntitiesWithComponents([jr,Fo]);for(const e of a){const t=n.get(e,jr);if(!t.dirty)continue;const s=n.get(e,Fo),i=Math.ceil(s.size.x),o=Math.ceil(s.size.y);i<=0||o<=0||(Uo(n,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const qr=new Yr,Gr={Simple:0,Sliced:1,Tiled:2,Filled:3},Kr={Horizontal:0,Vertical:1},Jr={Left:0,Right:1,Bottom:2,Top:3},Qr=Ae("Image",{texture:ye,color:{r:1,g:1,b:1,a:1},imageType:Gr.Simple,fillMethod:Kr.Horizontal,fillOrigin:Jr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Zr=Qo({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?Xo(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Yo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class ea{build(e){We("Image",Qr);const t=e.world,n=new Map;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{for(const e of n.keys())t.valid(e)&&t.has(e,Qr)||n.delete(e);const e=t.getEntitiesWithComponents([Qr]);for(const s of e){const e=t.get(s,Qr),i=t.has(s,Fo)?t.get(s,Fo):null,o={image:e,uiRect:i,entity:s},r=n.get(s);if(r&&!Zr.changed(r,o))continue;Uo(t,s);const a=t.get(s,Xe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=Xo(i,s),a.size.y=Yo(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===Kr.Horizontal?e.fillOrigin===Jr.Left?(a.uvScale.x=t,a.size.x=n*t):(a.uvOffset.x=1-t,a.uvScale.x=t,a.size.x=n*t):e.fillOrigin===Jr.Bottom?(a.uvScale.y=t,a.size.y=s*t):(a.uvOffset.y=1-t,a.uvScale.y=t,a.size.y=s*t)}else e.imageType===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,Xe,a),n.set(s,Zr.take(o))}else a.color.a=0,t.insert(s,Xe,a),n.set(s,Zr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const ta=new ea,na=Ae("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),sa=Ae("ToggleGroup",{allowSwitchOff:!1});class ia{build(e){We("Toggle",na),We("ToggleGroup",sa);const t=e.world,n=new Set;e.addSystemToSchedule(sn.Update,an([mt(Ar)],e=>{const s=t.getEntitiesWithComponents([na]);if(!zr()||$r()){const i=new Map;for(const e of s){if(n.has(e))continue;n.add(e);const s=t.get(e,na);s.isOn&&0!==s.group&&t.valid(s.group)&&(i.has(s.group)?(s.isOn=!1,t.insert(e,na,s)):i.set(s.group,e))}const o=new Map;for(const e of s){const n=t.get(e,na);if(0!==n.group&&t.valid(n.group)){let t=o.get(n.group);t||(t=[],o.set(n.group,t)),t.push(e)}}for(const n of s){if(Ko(t,n,Mr,{enabled:!0}),!t.has(n,Pr))continue;const s=t.get(n,Pr),i=t.get(n,na),r=t.get(n,Mr);if(s.justPressed&&r.enabled){const s=i.group,r=0!==s&&t.valid(s)&&t.has(s,sa);if(i.isOn&&r){if(!t.get(s,sa).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(n,na,i),i.isOn&&r){const i=o.get(s);if(i)for(const s of i){if(s===n)continue;const i=t.get(s,na);i.isOn&&(i.isOn=!1,t.insert(s,na,i),e.emit(s,"change"))}}e.emit(n,"change")}if(i.transition&&t.has(n,Xe)){const e=t.get(n,Xe);e.color=Oo(i.transition,r.enabled,s.pressed,s.hovered),t.insert(n,Xe,e)}}}for(const e of s){const n=t.get(e,na);if(n.graphicEntity&&t.valid(n.graphicEntity)&&t.has(n.graphicEntity,Xe)){const e=t.get(n.graphicEntity,Xe);e.enabled=n.isOn,t.insert(n.graphicEntity,Xe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const oa=new ia,ra=Io,aa=Ae("ProgressBar",{value:0,fillEntity:0,direction:Io.LeftToRight});function la(e,t,n,s){if(!e.has(t,Fo))return;const i=e.get(t,Fo),o=n/2,r=s/2,a={left:-o,bottom:-r,right:o,top:r},l=ko(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,Xe)){const n=e.get(t,Xe);n.size.x===l.width&&n.size.y===l.height||(n.size.x=l.width,n.size.y=l.height,e.insert(t,Xe,n))}if(e.has(t,je)){const n=e.get(t,je),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,je,n))}}class ca{build(e){We("ProgressBar",aa);const t=e.world;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e=t.getEntitiesWithComponents([aa,Fo]);for(const n of e){const e=t.get(n,aa);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const s=t.get(n,Fo),i=Math.max(0,Math.min(1,e.value));Lo(t,e.fillEntity,e.direction,i);const o=Xo(s,n),r=Yo(s,n);la(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const ua=new ca,da=Ae("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),ha=Ae("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}});class fa{build(e){We("Draggable",da),We("DragState",ha);const t=e.world,n=e.getResource(Ar);let s=null,i={x:0,y:0},o=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn)],(e,r)=>{if(zr()&&!$r())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([da,Pr]);let n=null,o=-1/0,r=-1;for(const s of e){if(!t.get(s,da).enabled)continue;if(t.get(s,Pr).hovered){let e=0;t.has(s,Xe)&&(e=t.get(s,Xe).layer);const i=No(t,s);(e>o||e===o&&i>=r)&&(o=e,r=i,n=s)}}if(null!==n){s=n,i={x:a.x,y:a.y},t.has(n,ha)||t.insert(n,ha);const e=t.get(n,ha),o=t.get(n,je);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==s&&!e.isMouseButtonDown(0)){if(t.valid(s)&&t.has(s,ha)){t.get(s,ha).isDragging=!1}s=null}if(null!==s&&null===o){if(!t.valid(s))return void(s=null);const e=a.x-i.x,l=a.y-i.y,c=Math.sqrt(e*e+l*l),u=t.get(s,da);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=s,s=null;t.get(o,ha).isDragging=!0,n.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,ha))return void(o=null);const s=t.get(o,ha),i=t.get(o,da),r=a.x-s.pointerStartWorld.x,l=a.y-s.pointerStartWorld.y;let c=s.startWorldPos.x+r,u=s.startWorldPos.y+l;const d=function(e,t,n,s){let i=e.lockX?t.startWorldPos.x:n,o=e.lockY?t.startWorldPos.y:s;return null!==e.constraintMin&&(i=Math.max(i,e.constraintMin.x),o=Math.max(o,e.constraintMin.y)),null!==e.constraintMax&&(i=Math.min(i,e.constraintMax.x),o=Math.min(o,e.constraintMax.y)),{x:i,y:o}}(i,s,c,u);c=d.x,u=d.y;const h=s.currentWorldPos.x,f=s.currentWorldPos.y;if(s.deltaWorld={x:c-h,y:u-f},s.currentWorldPos={x:c,y:u},s.totalDeltaWorld={x:c-s.startWorldPos.x,y:u-s.startWorldPos.y},t.has(o,je)){const e=function(e,t,n,s){if(!e.has(t,Ke))return{x:n,y:s};const i=e.get(t,Ke).entity;if(!e.valid(i)||!e.has(i,je))return{x:n,y:s};const o=e.get(i,je),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=yr(o.worldRotation.z,o.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l);return{x:(n*u-s*c)/r,y:(n*c+s*u)/a}}(t,o,s.deltaWorld.x,s.deltaWorld.y),n=t.get(o,je);n.position.x+=e.x,n.position.y+=e.y,t.insert(o,je,n)}n.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(s.isDragging=!1,n.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const pa=new fa,ma=Ae("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function ga(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 ya(e,t,n,s,i){const o=2/(s=Math.max(1e-4,s)),r=o*i,a=1/(1+r+.48*r*r+.235*r*r*r),l=e-t,c=(n+o*l)*i,u=t+(l+c)*a;return t-e>0==u>t?{value:t,velocity:0}:{value:u,velocity:(n-o*c)*a}}class _a{build(e){We("ScrollView",ma);const t=e.world,n=new Map,s={x:0,y:0};e.addSystemToSchedule(sn.PostUpdate,an([mt(pn),mt(yn),mt(wt)],(e,i,o)=>{const r=zr()&&!$r(),a=Math.min(o.delta,.05);for(const[e]of n)t.valid(e)||n.delete(e);i.valid&&(s.x=i.worldMouseX,s.y=i.worldMouseY);const l=t.getEntitiesWithComponents([ma,Fo]);for(const o of l){Ko(t,o,hr,{enabled:!0,mode:ur});const l=t.get(o,ma),c=t.get(o,Fo);let u=n.get(o);u||(u={isDragging:!1,lastWorldX:0,lastWorldY:0,velocityX:0,velocityY:0,contentBaseX:NaN,contentBaseY:NaN,lastAppliedX:NaN,lastAppliedY:NaN},n.set(o,u));const d=Xo(c,o),h=Yo(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,Je)){const e=t.get(l.contentEntity,Je).entities;let n=0,s=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,je))continue;const e=t.get(r,je);let a=0,l=0,c=.5,u=.5;if(t.has(r,Fo)){const e=t.get(r,Fo);a=Xo(e,r)||e.size.x,l=Yo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,Xe)){const e=t.get(r,Xe);a=e.size.x,l=e.size.y}const d=e.position.x-a*c,h=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);d<n&&(n=d),h>s&&(s=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=s-n),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){Ko(t,o,Mr,{enabled:!0,blockRaycast:!0});const n=t.has(o,Pr)?t.get(o,Pr):null;if(n?.justPressed&&(u.isDragging=!0,u.lastWorldX=s.x,u.lastWorldY=s.y,u.velocityX=0,u.velocityY=0),u.isDragging&&e.isMouseButtonDown(0)){const e=s.x-u.lastWorldX,t=s.y-u.lastWorldY,n=Math.min(1,10*a);if(l.horizontalEnabled){const t=ga(l.scrollX,0,m,d);if(l.scrollX-=e*t,0===e)u.velocityX=0;else{const s=a>0?-e*t/a:0;u.velocityX+=(s-u.velocityX)*n}}if(l.verticalEnabled){const e=ga(l.scrollY,0,g,h);if(l.scrollY+=t*e,0===t)u.velocityY=0;else{const s=a>0?t*e/a:0;u.velocityY+=(s-u.velocityY)*n}}u.lastWorldX=s.x,u.lastWorldY=s.y}if(u.isDragging&&e.isMouseButtonReleased(0)){u.isDragging=!1;const e=5*d,t=5*h;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(n?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=ga(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=ga(l.scrollX,0,m,d);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=ya(l.scrollX,e,u.velocityX,.1,a);l.scrollX=t.value,u.velocityX=t.velocity,Math.abs(l.scrollX-e)<.5&&Math.abs(u.velocityX)<Zo&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Zo?(u.velocityX*=Math.pow(l.decelerationRate,a),l.scrollX+=u.velocityX*a):u.velocityX=0);if(l.elastic&&t){const e=l.scrollY<0?0:g,t=ya(l.scrollY,e,u.velocityY,.1,a);l.scrollY=t.value,u.velocityY=t.velocity,Math.abs(l.scrollY-e)<.5&&Math.abs(u.velocityY)<Zo&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Zo?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*d,t=.5*h;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,je)){const e=t.get(l.contentEntity,je),n=e.position.x,s=e.position.y;(isNaN(u.lastAppliedX)||Math.abs(n-u.lastAppliedX)>.01)&&(u.contentBaseX=n),(isNaN(u.lastAppliedY)||Math.abs(s-u.lastAppliedY)>.01)&&(u.contentBaseY=s),e.position.x=u.contentBaseX-l.scrollX,e.position.y=u.contentBaseY+l.scrollY,u.lastAppliedX=e.position.x,u.lastAppliedY=e.position.y,t.insert(l.contentEntity,je,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const wa=new _a,xa=Io,ba=Ae("Slider",{value:0,minValue:0,maxValue:1,direction:Io.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function va(e,t,n,s,i,o){const r=Xo(s,i)*n.worldScale.x,a=Yo(s,i)*n.worldScale.y,l=yr(n.worldRotation.z,n.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-n.worldPosition.x,h=t-n.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-s.pivot.x*r,g=-s.pivot.y*a;switch(o){case Io.LeftToRight:return r>0?(f-m)/r:0;case Io.RightToLeft:return r>0?1-(f-m)/r:0;case Io.BottomToTop:return a>0?(p-g)/a:0;case Io.TopToBottom:return a>0?1-(p-g)/a:0}}function Sa(e,t,n){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case Io.LeftToRight:e.anchorMin.x=n,e.anchorMin.y=0,e.anchorMax.x=n,e.anchorMax.y=1;break;case Io.RightToLeft:e.anchorMin.x=1-n,e.anchorMin.y=0,e.anchorMax.x=1-n,e.anchorMax.y=1;break;case Io.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=n,e.anchorMax.x=1,e.anchorMax.y=n;break;case Io.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-n,e.anchorMax.x=1,e.anchorMax.y=1-n}}class Ma{build(e){We("Slider",ba);const t=e.world;let n=null;e.addSystemToSchedule(sn.PreUpdate,an([mt(pn),mt(yn),mt(Ar)],(e,s,i)=>{if(!s.valid)return;null===n||t.valid(n)||(n=null);const o=t.getEntitiesWithComponents([ba,Fo]);for(const r of o){const o=t.get(r,ba),a=t.get(r,Fo);if(!zr()||$r()){if(t.has(r,je)){Ko(t,r,Mr,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Ko(t,o.handleEntity,Mr,{enabled:!0,blockRaycast:!1});const l=t.get(r,je),c=t.has(r,Pr)?t.get(r,Pr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Pr)&&(u=t.get(o.handleEntity,Pr).justPressed),u&&(n=r),n===r&&e.isMouseButtonDown(0)){let e=va(s.worldMouseX,s.worldMouseY,l,a,r,o.direction);e=Math.max(0,Math.min(1,e));let n=o.minValue+e*(o.maxValue-o.minValue);o.wholeNumbers&&(n=Math.round(n));const c=o.value;o.value=Math.max(o.minValue,Math.min(o.maxValue,n)),t.insert(r,ba,o),o.value!==c&&i.emit(r,"change")}n===r&&e.isMouseButtonReleased(0)&&(n=null)}}const l=o.maxValue-o.minValue,c=l>0?(o.value-o.minValue)/l:0,u=Xo(a,r),d=Yo(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(Lo(t,o.fillEntity,o.direction,c),Jo(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Fo)){const e=t.get(o.handleEntity,Fo);Sa(e,o.direction,c),t.insert(o.handleEntity,Fo,e),Jo(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pa=new Ma;class Ta{build(e){We("Focusable",Vr);const t=e.world,n=new Nr;e.insertResource(Xr,n),e.addSystemToSchedule(sn.Update,an([mt(pn),mt(Ar)],(e,s)=>{if(zr()&&!$r())return;null===n.focusedEntity||t.valid(n.focusedEntity)||(n.focusedEntity=null);const i=t.getEntitiesWithComponents([Vr]);for(const e of i){if(!t.has(e,Pr))continue;t.get(e,Pr).justPressed&&o(e)}if(e.isKeyPressed("Tab")){const s=function(){const e=[];for(const n of i){if(!t.valid(n))continue;if(t.has(n,Mr)){if(!t.get(n,Mr).enabled)continue}const s=t.get(n,Vr);e.push({entity:n,tabIndex:s.tabIndex})}return e.sort((e,t)=>e.tabIndex-t.tabIndex),e.map(e=>e.entity)}();if(0===s.length)return;const r=null!==n.focusedEntity?s.findIndex(e=>e===n.focusedEntity):-1,a=e.isKeyDown("Shift");let l;l=-1===r?a?s.length-1:0:a?(r-1+s.length)%s.length:(r+1)%s.length,o(s[l])}function o(e){const i=n.focusedEntity;if(i===e)return;if(null!==i&&t.valid(i)&&t.has(i,Vr)){t.get(i,Vr).isFocused=!1,s.emit(i,"blur",i)}n.focus(e);t.get(e,Vr).isFocused=!0,s.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Ca=new Ta,Ea=Ae("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function Aa(){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")}}()}class Ra{build(e){We("SafeArea",Ea);const t=e.world;let n=Aa(),s=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{n=Aa(),s=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{n=Aa(),s=!0});e.addSystemToSchedule(sn.PreUpdate,an([mt(yn)],e=>{if(!e.valid||0===e.screenH)return;const a=e.worldTop-e.worldBottom;if(e.screenH===o&&a===r||(o=e.screenH,r=a,s=!0),!s)return;s=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([Ea,Fo]);for(const e of u){const s=t.get(e,Ea),i=t.get(e,Fo),o=s.applyTop?n.top*c:0,r=s.applyBottom?n.bottom*c:0,a=s.applyLeft?n.left*c:0,l=s.applyRight?n.right*c:0;let u=!1;i.offsetMin.x===a&&i.offsetMin.y===r||(i.offsetMin={x:a,y:r},u=!0),i.offsetMax.x===-l&&i.offsetMax.y===-o||(i.offsetMax={x:-l,y:-o},u=!0),u&&t.insert(e,Fo,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ia=new Ra,ka=Ae("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Fa=null;function Ba(e,t){if(!Fa)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const n=Fa.get(e);n?n.renderer=t:Fa.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class za{build(e){We("ListView",ka);const t=e.world,n=new Map;Fa=n,e.addSystemToSchedule(sn.PostUpdate,an([mt(pn)],e=>{const s=zr()&&!$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([ka,Fo]);for(const o of i){Ko(t,o,Mr,{enabled:!0,blockRaycast:!0}),Ko(t,o,hr,{enabled:!0,mode:ur});let i=n.get(o);i||(i={visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:null},n.set(o,i));const r=t.get(o,ka),a=t.get(o,Fo),l=Yo(a,o),c=Xo(a,o);if(!s){const n=t.has(o,Pr)?t.get(o,Pr):null;if(n?.hovered){const t=e.getScrollDelta();0!==t.y&&(r.scrollY+=.1*t.y)}}const u=Math.max(0,r.itemCount*r.itemHeight-l);r.scrollY=Math.max(0,Math.min(r.scrollY,u));const d=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),h=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,n]of i.itemEntities)(e<d||e>=h)&&(t.valid(n)&&t.despawn(n),i.itemEntities.delete(e));for(let e=d;e<h;e++){let n=i.itemEntities.get(e);if(n&&t.valid(n)||(n=t.spawn(),t.insert(n,it,{value:`ListItem_${e}`}),t.insert(n,Fo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y:r.itemHeight},pivot:{x:.5,y:1}}),t.setParent(n,o),i.itemEntities.set(e,n),i.renderer&&i.renderer(e,n)),t.has(n,je)){const s=t.get(n,je);s.position.y=-(e*r.itemHeight-r.scrollY),t.insert(n,je,s)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Ua=new za,Wa=Ae("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class $a{build(e){We("Dropdown",Wa);const t=e.world,n=new Map;function s(e){if(0===e||!t.valid(e))return;if(!t.has(e,je))return;const n=t.get(e,je);0===n.scale.x&&0===n.scale.y&&0===n.scale.z&&t.insert(e,je,{position:{x:n.position.x,y:n.position.y,z:n.position.z},rotation:{x:n.rotation.x,y:n.rotation.y,z:n.rotation.z,w:n.rotation.w},scale:{x:1,y:1,z:1}})}function i(e){if(t.has(e,Xe)){const n=t.get(e,Xe);1===n.color.r&&1===n.color.g&&1===n.color.b&&1===n.color.a&&t.insert(e,Xe,{texture:n.texture,color:{r:.9,g:.9,b:.9,a:1},size:{x:n.size.x,y:n.size.y},uvOffset:{x:n.uvOffset.x,y:n.uvOffset.y},uvScale:{x:n.uvScale.x,y:n.uvScale.y},layer:n.layer,flipX:n.flipX,flipY:n.flipY,material:n.material,enabled:n.enabled})}}function o(e,n,s){n.isOpen=!0,s.highlightIndex=n.selectedIndex;const i=n.listEntity;if(0===i||!t.valid(i))return;u(i,!0),c(s);const o=t.get(e,Xe),r=o.size.x,a=o.size.y;s.ddWidth=r;const l=n.options.length*er;t.insert(i,Fo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,je,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,Xe,{texture:ye,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<n.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*er;t.insert(o,it,{value:`Option_${e}`}),t.insert(o,Fo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*er},offsetMax:{x:0,y:0},size:{x:r,y:er},pivot:{x:.5,y:.5}}),t.insert(o,je,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,Xe,{texture:ye,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:er},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Mr,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),s.optionEntities.push(o);const c=t.spawn();t.insert(c,je,{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,or,{content:n.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:nr.Left,verticalAlign:sr.Middle,wordWrap:!1,overflow:ir.Clip,lineHeight:1.2}),t.insert(c,Fo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:er},pivot:{x:.5,y:.5}}),t.setParent(c,o),s.textEntities.push(c)}d(s)}function r(e,t,n){t.isOpen=!1,c(n),u(t.listEntity,!1)}function a(e,t,n,s,i){t.selectedIndex=s,r(0,t,n),i.emit(e,"change")}function l(e){const n=e.labelEntity;if(0===n||!t.valid(n))return;if(!t.has(n,or))return;const s=t.get(n,or);let i={r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},o=s.content,r=!1;if(1===i.r&&1===i.g&&1===i.b&&1===i.a&&(i={r:0,g:0,b:0,a:1},r=!0),e.selectedIndex>=0&&e.selectedIndex<e.options.length){const t=e.options[e.selectedIndex];o!==t&&(o=t,r=!0)}r&&t.insert(n,or,{content:o,fontSize:s.fontSize,fontFamily:s.fontFamily,color:i,align:s.align,verticalAlign:s.verticalAlign,wordWrap:s.wordWrap,overflow:s.overflow,lineHeight:s.lineHeight})}function c(e){for(const n of e.textEntities)t.valid(n)&&t.despawn(n);for(const n of e.optionEntities)t.valid(n)&&t.despawn(n);e.optionEntities=[],e.textEntities=[]}function u(e,n){if(0!==e&&t.valid(e)&&(t.has(e,Mr)&&t.insert(e,Mr,{enabled:n,blockRaycast:!0,raycastTarget:!0}),t.has(e,Xe))){const s=t.get(e,Xe);t.insert(e,Xe,{texture:s.texture,color:{r:s.color.r,g:s.color.g,b:s.color.b,a:s.color.a},size:{x:s.size.x,y:s.size.y},uvOffset:{x:s.uvOffset.x,y:s.uvOffset.y},uvScale:{x:s.uvScale.x,y:s.uvScale.y},layer:s.layer,flipX:s.flipX,flipY:s.flipY,material:s.material,enabled:n})}}function d(e){for(let n=0;n<e.optionEntities.length;n++){const s=e.optionEntities[n];if(!t.valid(s)||!t.has(s,Xe))continue;const i=n===e.highlightIndex?{...tr}:{r:.95,g:.95,b:.95,a:1};t.insert(s,Xe,{texture:ye,color:i,size:{x:e.ddWidth,y:er},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function h(e){for(const n of e.optionEntities){if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).hovered)return!0}return!1}e.addSystemToSchedule(sn.Update,an([mt(pn),mt(Ar)],(e,c)=>{for(const[e]of n)t.valid(e)||n.delete(e);const f=zr()&&!$r(),p=t.getEntitiesWithComponents([Wa]);for(const m of p){const p=t.get(m,Wa);let g=n.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},n.set(m,g)),s(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Ko(t,m,Mr,{enabled:!0,blockRaycast:!0});const y=t.has(m,Pr)?t.get(m,Pr):null;if(y?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const n=g.optionEntities[e];if(!t.valid(n)||!t.has(n,Pr))continue;if(t.get(n,Pr).justPressed){a(m,p,g,e,c);break}}let n=-1;for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,Pr))continue;if(t.get(s,Pr).hovered){n=e;break}}n>=0&&n!==g.highlightIndex&&(g.highlightIndex=n,d(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,d(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,d(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(y?.hovered||h(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Da=new $a,La=0,Oa=0,Ha=2,ja=Ae("LayoutGroup",{direction:La,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Oa,reverseOrder:!1});class Va{build(e){We("LayoutGroup",ja);const t=e.world;e.addSystemToSchedule(sn.PreUpdate,an([],()=>{const e=t.getEntitiesWithComponents([ja,Fo,Je]);for(const n of e){const e=t.get(n,ja),s=t.get(n,Fo),i=t.get(n,Je);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,Fo)&&t.has(e,je)&&o.push({entity:e,rect:t.get(e,Fo)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=Xo(s,n),a=Yo(s,n),l=s.pivot.x,c=s.pivot.y,u=e.padding,d=e.direction===La;let h=0;for(let n=0;n<o.length;n++){const s=o[n],i=Xo(s.rect,s.entity),f=Yo(s.rect,s.entity),p=s.rect.pivot.x,m=s.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===Oa?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ha?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,n<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===Oa?-l*r+u.left+p*i:e.childAlignment===Ha?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,y=(1-c)*a-u.top-h-(1-m)*f,h+=f,n<o.length-1&&(h+=e.spacing));const _=t.get(s.entity,je);_.position.x=g,_.position.y=y,t.insert(s.entity,je,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Na=new Va;class Xa{build(e){const t=e.world,n=e.wasmModule,s=t.getCppRegistry();e.addSystemToSchedule(sn.PostUpdate,an([],()=>{n.uiRenderOrder_update(s)},{name:"UIRenderOrderSystem"}))}}const Ya=new Xa;async function qa(e,t,n){const s=e.getResource(ho);await s.switchTo(t,{transition:n.type,duration:n.duration,color:n.color})}async function Ga(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 Ka=pt({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),Ja={r:.2,g:.4,b:1,a:.7},Qa={r:.2,g:1,b:.2,a:.7},Za={r:.2,g:1,b:1,a:.7},el={r:1,g:1,b:.2,a:.5},tl={r:1,g:.2,b:.2,a:.8},nl={r:1,g:.2,b:.2,a:1},sl=1.5,il=16;function ol(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function rl(e){switch(e){case ht.Static:return Ja;case ht.Kinematic:return Za;default:return Qa}}function al(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*r-n.y*a,y:t+n.x*a+n.y*r}));for(let e=0;e<4;e++)si.line(l[e],l[(e+1)%4],o,sl)}function ll(e,t,n,s,i,o){const r=Math.cos(i),a=Math.sin(i),l=(n,s)=>({x:e+n*r-s*a,y:t+n*a+s*r}),c=l(-n,s),u=l(n,s),d=l(-n,-s),h=l(n,-s);si.line(c,d,o,sl),si.line(u,h,o,sl);for(let e=0;e<il;e++){const t=e/il*Math.PI,i=(e+1)/il*Math.PI,r=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(i),s+n*Math.sin(i));si.line(r,a,o,sl)}for(let e=0;e<il;e++){const t=Math.PI+e/il*Math.PI,i=Math.PI+(e+1)/il*Math.PI,r=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(i),-s+n*Math.sin(i));si.line(r,a,o,sl)}}function cl(e,t,n,s){const i=e+.5*n,o=t+.5*s;si.line({x:e,y:t},{x:i,y:o},tl,sl);const r=Math.sqrt(n*n+s*s);if(r<1)return;const a=Math.PI/6,l=n/r,c=s/r,u=i-6*(l*Math.cos(a)-c*Math.sin(a)),d=o-6*(l*Math.sin(a)+c*Math.cos(a)),h=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));si.line({x:i,y:o},{x:u,y:d},tl,sl),si.line({x:i,y:o},{x:h,y:f},tl,sl)}function ul(e,t,n){const s=e.getResource(Ka);if(!s||!s.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([lt,je]);let r=null;s.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const n=e.world.get(t,lt);if(!n.enabled)continue;const o=e.world.get(t,je),a=o.worldPosition.x,l=o.worldPosition.y,c=ol(o.worldRotation);if(s.showColliders){if(e.world.has(t,ct)){const s=e.world.get(t,ct),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);al(a+r*d-u*h,l+r*h+u*d,s.halfExtents.x*i,s.halfExtents.y*i,c,o)}if(e.world.has(t,ut)){const s=e.world.get(t,ut),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c),f=a+r*d-u*h,p=l+r*h+u*d;si.circleOutline({x:f,y:p},s.radius*i,o,sl,32)}if(e.world.has(t,dt)){const s=e.world.get(t,dt),o=s.isSensor?el:rl(n.bodyType),r=s.offset.x*i,u=s.offset.y*i,d=Math.cos(c),h=Math.sin(c);ll(a+r*d-u*h,l+r*h+u*d,s.radius*i,s.halfHeight*i,c,o)}}if(s.showVelocity&&r&&n.bodyType===ht.Dynamic){const e=r.getLinearVelocity(t);cl(a,l,e.x*i,e.y*i)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)si.circle({x:e.contactX,y:e.contactY},3,nl,!0,32)}}const dl=pt({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),hl=pt(null,"PhysicsAPI");function fl(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function pl(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class ml{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,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(dl,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=Ga(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([qe]);for(const n of t){const t=e.world.get(n,qe);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/i,r=e.world;r.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(sn.PostUpdate,an([mt(wt)],a=>{if(zr()&&!$r())return;const l=r.getEntitiesWithComponents([lt,je]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,lt),l=r.get(i,je);if(t.has(i)){const e=n.get(i);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(i,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const r=fl(l.worldRotation);s._physics_createBody(i,a.bodyType,l.worldPosition.x*o,l.worldPosition.y*o,r,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),_l(e,s,i,this.config_.collisionLayerMasks),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===ht.Kinematic){const e=fl(l.worldRotation);s._physics_setBodyTransform(i,l.worldPosition.x*o,l.worldPosition.y*o,e)}}for(const e of t)c.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<s;i++){const s=o+4*i,r=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,c=t.HEAPF32[s+3];if(!e.world.valid(r))continue;const u=e.world.get(r,je);if(!u)continue;let d=a,h=l,f=c;if(e.world.has(r,Ke)){const t=e.world.get(r,Ke);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,je)){const n=e.world.get(t.entity,je),s=fl(n.worldRotation),i=a-n.worldPosition.x,o=l-n.worldPosition.y,r=Math.cos(-s),u=Math.sin(-s);d=(i*r-o*u)/(0!==n.worldScale.x?n.worldScale.x:1),h=(i*u+o*r)/(0!==n.worldScale.y?n.worldScale.y:1),f=c-s}}u.position.x=d,u.position.y=h;const p=pl(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,je,u)}}(e,s,i),function(e,t,n){t._physics_collectEvents();const s=[],i=t._physics_getCollisionEnterCount();if(i>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<i;o++){const i=e+6*o;s.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*n,contactY:t.HEAPF32[i+5]*n})}}const o=[],r=t._physics_getCollisionExitCount();if(r>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<r;n++){const s=e+2*n;o.push({entityA:t.HEAPU32[s],entityB:t.HEAPU32[s+1]})}}const a=[],l=t._physics_getSensorEnterCount();if(l>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let n=0;n<l;n++){const s=e+2*n;a.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}const c=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let n=0;n<u;n++){const s=e+2*n;c.push({sensorEntity:t.HEAPU32[s],visitorEntity:t.HEAPU32[s+1]})}}e.insertResource(dl,{collisionEnters:s,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,s,i)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(hl,wl._fromModule(s)),function(e,t,n){e.insertResource(Ka,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),li("physics-debug-draw",()=>{ul(e,t,n)})}(e,hl,dl),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}const gl=16;function yl(e,t,n){if(!n)return t;for(let t=0;t<gl;t++)if(e===1<<t)return n[t];return t}function _l(e,t,n,s){const i=e.world;if(i.has(n,ct)){const e=i.get(n,ct),o=e.categoryBits??1,r=yl(o,e.maskBits??65535,s);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,ut)){const e=i.get(n,ut),o=e.categoryBits??1,r=yl(o,e.maskBits??65535,s);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}if(i.has(n,dt)){const e=i.get(n,dt),o=e.categoryBits??1,r=yl(o,e.maskBits??65535,s);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,o,r)}}class wl{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(wl.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)}static setDebugDraw(e,t){const n=e.getResource(Ka);n&&(n.enabled=t,e.insertResource(Ka,n))}static setDebugDrawConfig(e,t){const n=e.getResource(Ka);n&&e.insertResource(Ka,{...n,...t})}}const xl={nearest:0,linear:1},bl={repeat:0,clamp:1,mirror:2};function vl(e,t,n=!0,s){const i=e.getResourceManager(),o=e._malloc(t.pixels.length);let r;if(e.HEAPU8.set(t.pixels,o),s&&(s.filterMode||s.wrapMode)&&i.createTextureEx){const e=xl[s.filterMode??"linear"]??1,a=bl[s.wrapMode??"clamp"]??1;r=i.createTextureEx(t.width,t.height,o,t.pixels.length,1,n,e,a)}else r=i.createTexture(t.width,t.height,o,t.pixels.length,1,n);return e._free(o),r}function Sl(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 Ml(e,t,n,s){const i=e.worldScale.x*t*(n?-1:1),o=e.worldScale.y*t*(s?-1:1),r=e.worldScale.z,a=e.worldRotation.x,l=e.worldRotation.y,c=e.worldRotation.z,u=e.worldRotation.w,d=a+a,h=l+l,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,w=c*f,x=u*d,b=u*h,v=u*f;return new Float32Array([(1-(y+w))*i,(m+v)*i,(g-b)*i,0,(m-v)*o,(1-(p+w))*o,(_+x)*o,0,(g+b)*r,(_-x)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function Pl(e){const{app:t,module:n,sceneData:s,provider:i,spineModule:o,physicsModule:r,physicsConfig:a,manifest:l,sceneName:c}=e,u=await async function(e,t,n){const s={},i=t.textureImporterSettings;for(const o of t.entities)for(const t of o.components){const o=xs(t.type);for(const r of o){if("texture"!==r.type)continue;const o=t.data[r.field];if("string"==typeof o&&o&&void 0===s[o])try{const t=i?.[o];s[o]=vl(e,await n.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),s[o]=0}}}return s}(n,s,i);!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)}}}}(n,s,u);let d={},h=null;if(o&&(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"])}}(o),d=await async function(e,t,n,s,i){const o={};for(const r of s.entities)for(const s of r.components){const r=bs(s.type);if(!r||!s.data)continue;const a=s.data[r.skeletonField],l=s.data[r.atlasField];if(!a||!l)continue;const c=i.resolvePath(a),u=i.resolvePath(l);try{const s=await i.readText(l),r="binary"===T(c)?.contentType;let d,h;if(r){const e=await i.readBinary(a);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await i.readText(a),n=(new TextEncoder).encode(e);h=n.length,d=t._malloc(h+1),t.HEAPU8.set(n,d),t.HEAPU8[d+h]=0}const f=n.loadSkeleton(d,h,s,s.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=Sl(s),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const s=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(s):await i.loadPixels(s),r=vl(e,o,!1),a=e.getResourceManager().getTextureGLId(r);n.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,o,h,s,i)),r){const e={gravity:a?.gravity??{...ce},fixedTimestep:a?.fixedTimestep??ue,subStepCount:a?.subStepCount??4};new ml("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,n){const s={};for(const i of t.entities)for(const t of i.components){const i=xs(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===s[o])try{let t,i;const r=T(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await n.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){s[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await n.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await n.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){s[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=n.loadPixelsRaw?await n.loadPixelsRaw(l):await n.loadPixels(l),u=vl(e,c,!1),d=e.getResourceManager();s[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{s[o]=0}}return s}(n,s,i),p=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=xs(e.type).find(e=>"material"===e.type);if(!i)continue;const o=e.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{const e=JSON.parse(await t.readText(o));if(!e.vertexSource||!e.fragmentSource){n[o]=0;continue}const i=e.vertexSource+e.fragmentSource;let r=s[i];r||(r=Cn.createShader(e.vertexSource,e.fragmentSource),s[i]=r),n[o]=Cn.createFromAsset(e,r)}catch{n[o]=0}}return n}(s,i);await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=xs(t.type);for(const o of i){if("anim-clip"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=JSON.parse(t),o=$n(s),r=new Map;for(const t of o)try{const s=await n.loadPixels(t);r.set(t,vl(e,s))}catch{r.set(t,0)}On(Dn(i,s,r))}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,s,i),await async function(e,t,n){const s=new Set;for(const i of t.entities)for(const t of i.components){const i=xs(t.type);for(const o of i){if("tilemap"!==o.type)continue;const i=t.data[o.field];if("string"==typeof i&&i&&!s.has(i)){s.add(i);try{const t=await n.readText(i),s=ds(JSON.parse(t));if(!s)continue;const o=[];for(const t of s.tilesets){const s=hs(i,t.image);let r=0;try{const t=await n.loadPixels(s);r=vl(e,t),Kn(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}Zn(i,{tileWidth:s.tileWidth,tileHeight:s.tileHeight,layers:s.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:o})}catch(e){console.warn(`[loadTilemaps] Failed to load tilemap: ${i}`,e)}}}}}(n,s,i),await async function(e,t){const n=[],s=new Set;for(const t of e.entities)for(const e of t.components){const t=xs(e.type);for(const i of t){if("audio"!==i.type)continue;const t=e.data[i.field];"string"==typeof t&&t&&!s.has(t)&&(s.add(t),n.push(t))}}0!==n.length&&(t?await Promise.all(n.map(async e=>{try{const n=await t.readBinary(e);await Yn.preloadFromData(e,n.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await Yn.preloadAll(n).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(s,i),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=xs(e.type);if(0===t.length)continue;const n=e.data;for(const e of t){const t=i[e.type];t&&"string"==typeof n[e.field]&&(n[e.field]=t[n[e.field]]||0)}}}(s,u,f,p);const m=Cs(t.world,s);if(c&&t.hasResource(ho))for(const e of m.values())t.world.insert(e,ot,{scene:c,persistent:!1});if(o&&h){const e=function(e,t,n,s){const i={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){const r=bs(t.type);if(!r||!t.data)continue;const a=n[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=s.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(h,s,d,m);!function(e,t,n,s,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>.5)&&(l=le);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,Ze)?c.get(o,Ze):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&s.update(r,l*d);let h=0;if(c.has(o,je)){const e=Ml(c.get(o,je),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=s.getMeshBatchCount(r);for(let e=0;e<f;e++){const i=s.getMeshBatchVertexCount(r,e),o=s.getMeshBatchIndexCount(r,e);if(!i||!o)continue;const a=8*i*4,l=2*o,c=n._malloc(a),u=n._malloc(l),d=n._malloc(4),f=n._malloc(4);s.getMeshBatchData(r,e,c,u,d,f);const p=n.HEAPU32[d>>2],m=n.HEAPU32[f>>2],g=new Float32Array(n.HEAPF32.buffer,c,8*i),y=new Uint16Array(n.HEAPU8.buffer,u,o),_=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,_>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(y),t.renderer_submitTriangles(_,i,w,o,p,m,h),t._free(_),t._free(w),n._free(c),n._free(u),n._free(d),n._free(f)}h&&t._free(h)}})}(t,n,o,h,e)}if(l){const e=t.getResource(Bs);e&&e.setAddressableManifest(l)}}function Tl(e,t,n){return{name:e,async setup(){await Pl({...n,sceneData:t,sceneName:e})}}}async function Cl(e){const{app:t,firstScene:n,aspectRatio:s}=e;yo(t);const i={app:e.app,module:e.module,provider:e.provider,spineModule:e.spineModule,physicsModule:e.physicsModule,physicsConfig:e.physicsConfig,manifest:e.manifest},o=t.getResource(ho);for(const t of e.scenes)o.register(Tl(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Is(t.world,s)}class El{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=bs(e.type);if(i){const s=e.data[i.skeletonField],o=e.data[i.atlasField];s&&("binary"===T(s)?.contentType?n.add(s):t.add(s)),o&&t.add(o)}const o=xs(e.type);for(const i of o){const o=e.data[i.field];"string"==typeof o&&o&&("font"===i.type?(s.add(o),t.add(o)):"material"===i.type||"anim-clip"===i.type||"tilemap"===i.type?t.add(o):"audio"===i.type&&n.add(o))}}const i=[];for(const e of t)i.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of n)i.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(i);const o=[];for(const e of s){const t=T(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const n=this.textCache_.get(e);if(n)try{const t=JSON.parse(n),s="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(s){const t=e.substring(0,e.lastIndexOf("/")),n=t?`${t}/${s}`:s;this.textCache_.has(n)||o.push(fetch(this.resolveUrl(n)).then(e=>e.text()).then(e=>{this.textCache_.set(n,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${n}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),n=await fetch(t),s=await n.blob(),i=await createImageBitmap(s),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Al="__preview__";class Rl{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(ho);t.register({name:Al,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Al),this.loadPromise_=t.load(Al).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await r(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new El(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Pl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Al})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const n=e.getEntitiesWithComponents([Ye]);for(const s of n){if(e.get(s,Ye).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,n=1.7777777777777777;const s=e.getEntitiesWithComponents([qe]);for(const i of s){const s=e.get(i,qe);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(ho).getScene(Al),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,je,r);const a={isActive:!0,projectionType:Le.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:n,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:Oe.ColorAndDepth};e.insert(o,Ye,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ho);await e.switchTo(Al),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 Il={create(e){const t=e.depth??!0,n="linear"===e.filter,s=(t?1:0)|(n?2:0),i=to.createRenderTarget(e.width,e.height,s);return{_handle:i,textureId:to.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:n?"linear":"nearest"}},release(e){to.releaseRenderTarget(e._handle)},resize:(e,t,n)=>(to.releaseRenderTarget(e._handle),Il.create({width:t,height:n,depth:e._depth,filter:e._filter})),begin(e,t){to.begin(t,e._handle)},end(){to.end()},getDepthTexture:e=>to.getTargetDepthTexture(e._handle)};var kl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(kl||(kl={}));class Fl{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${kl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case kl.Debug:console.debug(t,n);break;case kl.Info:console.log(t,n);break;case kl.Warn:console.warn(t,n);break;case kl.Error:console.error(t,n)}}}class Bl{constructor(){this.handlers_=[],this.minLevel_=kl.Info,this.addHandler(new Fl)}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(kl.Debug,e,t,n)}info(e,t,n){this.log(kl.Info,e,t,n)}warn(e,t,n){this.log(kl.Warn,e,t,n)}error(e,t,n){this.log(kl.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 zl=new Bl;function Ul(){return zl}function Wl(e){zl.setMinLevel(e)}function $l(e,t,n){zl.debug(e,t,n)}function Dl(e,t,n){zl.info(e,t,n)}function Ll(e,t,n){zl.warn(e,t,n)}function Ol(e,t,n){zl.error(e,t,n)}const Hl={Linear:0,EaseInQuad:1,EaseOutQuad:2,EaseInOutQuad:3,EaseInCubic:4,EaseOutCubic:5,EaseInOutCubic:6,EaseInBack:7,EaseOutBack:8,EaseInOutBack:9,EaseInElastic:10,EaseOutElastic:11,EaseInOutElastic:12,EaseOutBounce:13,CubicBezier:14,Step:15},jl={Running:0,Paused:1,Completed:2,Cancelled:3},Vl={None:0,Restart:1,PingPong:2};const Nl=1.70158,Xl=2.70158,Yl=2.5949095;const ql=2*Math.PI/3,Gl=2*Math.PI/4.5;const Kl=7.5625,Jl=2.75;const Ql=1e-6;function Zl(e,t,n){switch(e){case Hl.Linear:return t;case Hl.EaseInQuad:return function(e){return e*e}(t);case Hl.EaseOutQuad:return function(e){return e*(2-e)}(t);case Hl.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Hl.EaseInCubic:return function(e){return e*e*e}(t);case Hl.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Hl.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Hl.EaseInBack:return function(e){return Xl*e*e*e-Nl*e*e}(t);case Hl.EaseOutBack:return function(e){const t=e-1;return 1+Xl*t*t*t+Nl*t*t}(t);case Hl.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Yl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Yl)+2)/2}(t);case Hl.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*ql)}(t);case Hl.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*ql)+1}(t);case Hl.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Gl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Gl)/2+1}(t);case Hl.EaseOutBounce:return function(e){return e<1/Jl?Kl*e*e:e<2/Jl?Kl*(e-=1.5/Jl)*e+.75:e<2.5/Jl?Kl*(e-=2.25/Jl)*e+.9375:Kl*(e-=2.625/Jl)*e+.984375}(t);case Hl.CubicBezier:return n?function(e,t,n,s,i){let o=e;for(let n=0;n<8;n++){const n=1-o,i=3*t*n*n*o+3*s*n*o*o+o*o*o-e;if(Math.abs(i)<Ql)break;const r=3*t*(1-2*o)*(1-o)+6*s*o*(1-o)-3*s*o*o+3*o*o;if(Math.abs(r)<Ql)break;o-=i/r}const r=1-o;return 3*n*r*r*o+3*i*r*o*o+o*o*o}(t,n.p1x,n.p1y,n.p2x,n.p2y):t;case Hl.Step:return function(e){return e<1?0:1}(t);default:return t}}const ec=new class{constructor(){this.entries_=new Map,this.nextId_=1,this.cppSequences_=new Map,this.module_=null,this.registry_=null}init(e,t){this.module_=e,this.registry_=t}create(e,t,n,s,i){const o=this.nextId_++;return this.entries_.set(o,{id:o,from:e,to:t,duration:n,elapsed:0,delay:i?.delay??0,easing:i?.easing??Hl.Linear,bezierPoints:null,state:jl.Running,loop:i?.loop??Vl.None,loopCount:i?.loopCount??0,loopsRemaining:i?.loopCount??0,callback:s,sequenceNext:null,sequenceNextExternal:null}),o}update(e){if(this.module_&&this.registry_)for(const[e,t]of this.cppSequences_){this.module_._anim_getTweenState(this.registry_,e)===jl.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==jl.Running)continue;if(t.delay>0){if(t.delay-=e,t.delay>0)continue;e=-t.delay,t.delay=0}t.elapsed+=e;const n=Math.min(t.elapsed/t.duration,1),s=Zl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Vl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Vl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=jl.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===jl.Running&&(t.state=jl.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===jl.Paused&&(t.state=jl.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=jl.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:jl.Cancelled}setBezier(e,t,n,s,i){const o=this.entries_.get(e);o&&(o.bezierPoints={p1x:t,p1y:n,p2x:s,p2y:i})}setSequenceNext(e,t){const n=this.entries_.get(e);n&&(n.sequenceNext=t,this.pause(t))}setSequenceNextExternal(e,t){const n=this.entries_.get(e);n&&(n.sequenceNextExternal=t,t.pause())}registerCppSequence(e,t){this.cppSequences_.set(e,t),this.pause(t)}shutdown(){this.entries_.clear(),this.cppSequences_.clear(),this.module_=null,this.registry_=null,this.nextId_=1}};class tc{constructor(e){this.id=e}get state(){return ec.getState(this.id)}bezier(e,t,n,s){return ec.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof tc?ec.setSequenceNext(this.id,e.id):ec.setSequenceNextExternal(this.id,e),this}pause(){ec.pause(this.id)}resume(){ec.resume(this.id)}cancel(){ec.cancel(this.id)}}const nc={PositionX:0,PositionY:1,PositionZ:2,ScaleX:3,ScaleY:4,RotationZ:5,ColorR:6,ColorG:7,ColorB:8,ColorA:9,SizeX:10,SizeY:11,CameraOrthoSize:12};class sc{constructor(e,t,n){this.module_=e,this.registry_=t,this.entity=n}get state(){return this.module_._anim_getTweenState(this.registry_,this.entity)}bezier(e,t,n,s){return this.module_._anim_setTweenBezier(this.registry_,this.entity,e,t,n,s),this}then(e){return e instanceof tc?(ec.registerCppSequence(this.entity,e.id),this):(this.module_._anim_setSequenceNext(this.registry_,this.entity,e.entity),this)}pause(){this.module_._anim_pauseTween(this.registry_,this.entity)}resume(){this.module_._anim_resumeTween(this.registry_,this.entity)}cancel(){this.module_._anim_cancelTween(this.registry_,this.entity)}}let ic=null,oc=null;function rc(e,t){ic=e,oc=t,ec.init(e,t)}function ac(){ec.shutdown(),ic=null,oc=null}function lc(){if(!ic)throw new Error("Tween API not initialized");return ic}function cc(){if(!oc)throw new Error("Tween API not initialized");return oc}const uc={to(e,t,n,s,i,o){const r=lc(),a=cc(),l=o?.easing??Hl.Linear,c=o?.delay??0,u=o?.loop??Vl.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new sc(r,a,h)},value(e,t,n,s,i){const o=ec.create(e,t,n,s,i);return new tc(o)},cancel(e){lc()._anim_cancelTween(cc(),e.entity)},cancelAll(e){lc()._anim_cancelAllTweens(cc(),e)},update(e){lc()._anim_updateTweens(cc(),e),ec.update(e)}};class dc{constructor(){this.name="AnimationPlugin"}build(e){rc(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{uc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Xn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ac()}}const hc=new dc;var fc;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(fc||(fc={}));const pc={model:fc.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function mc(e,t=pc){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case fc.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case fc.Inverse:a=s/Math.max(r,s);break;case fc.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function gc(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const yc=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:fc.Inverse,rolloff:1,priority:0,enabled:!0}),_c=Ae("AudioListener",{enabled:!0});class wc{constructor(e={}){this.name="AudioPlugin",this.activeSourceHandles_=null,this.playedEntities_=null,this.config_=e}build(e){const n=t().createAudioBackend(),s=this.config_;n.initialize({initialPoolSize:s.initialPoolSize}).catch(e=>{console.warn("[AudioPlugin] backend initialization failed:",e)});const i=n.mixer;Yn.init(n,i),i&&(void 0!==s.masterVolume&&(i.master.volume=s.masterVolume),void 0!==s.musicVolume&&(i.music.volume=s.musicVolume),void 0!==s.sfxVolume&&(i.sfx.volume=s.sfxVolume));const o=new Map;this.activeSourceHandles_=o;const r=new Set;this.playedEntities_=r;const a=new Set;let l=!1,c=!1;e.addSystemToSchedule(sn.PreUpdate,an([mt(wt)],t=>{if(!(!zr()||$r()))return void(c&&(l=!1,c=!1));c=!0;const s=e.world;let i=0,u=0,d=!1;const h=s.getEntitiesWithComponents([_c,Ne]);for(const e of h){if(s.get(e,_c).enabled){const t=s.get(e,Ne);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([yc]);a.clear();for(const e of f){const t=s.get(e,yc);if(!t.enabled||!t.clip)continue;const c=e;if(a.add(c),t.playOnAwake&&!r.has(c)&&!o.has(c)&&n.isReady){const e=Yn.getBufferHandle(t.clip);if(e){const s=n.play(e,{bus:t.bus,volume:t.volume,loop:t.loop,playbackRate:t.pitch});o.set(c,s),r.add(c)}else console.warn(`[AudioPlugin] playOnAwake: clip "${t.clip}" not preloaded`)}if(t.spatial&&o.has(c)){const n=o.get(c);if(!n.isPlaying){o.delete(c);continue}d||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=s.tryGet?.(e,Ne),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=mc(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=gc(a,0,i,0,t.maxDistance);n.setVolume(t.volume*m),n.setPan(g)}}for(const[e,t]of o)a.has(e)&&t.isPlaying||o.delete(e)},{name:"AudioUpdateSystem"}))}stopAllSources(){if(this.activeSourceHandles_){for(const e of this.activeSourceHandles_.values())e.stop();this.activeSourceHandles_.clear()}this.playedEntities_?.clear()}cleanup(){this.stopAllSources(),Yn.dispose()}}const xc=new wc;let bc=null,vc=null;function Sc(e,t){bc=e,vc=t}function Mc(){bc=null,vc=null}const Pc={update(e){bc&&vc&&bc.particle_update?.(vc,e)},play(e){bc&&vc&&bc.particle_play?.(vc,e)},stop(e){bc&&vc&&bc.particle_stop?.(vc,e)},reset(e){bc&&vc&&bc.particle_reset?.(vc,e)},getAliveCount:e=>bc?bc.particle_getAliveCount?.(e)??0:0};class Tc{constructor(){this.name="ParticlePlugin"}build(e){Sc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Pc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Mc()}}const Cc=new Tc,Ec=1e6;class Ac{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){ss(e.wasmModule);const t=e.world,n=this.initializedLayers_,s=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(yn),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:Ec,l=i?.valid?i.worldTop:Ec,c=t.getEntitiesWithComponents([as,je]);for(const e of c){const s=t.tryGet(e,as),i=t.tryGet(e,je);if(!s||!i)continue;if(!s.visible)continue;const c=s.texture;if(!c)continue;const u=Jn(c);if(!u)continue;if(!n.has(e)){if(os.initLayer(e,s.width,s.height,s.tileWidth,s.tileHeight),s.tiles.length>0){const t=new Uint16Array(s.tiles.length);for(let e=0;e<s.tiles.length;e++)t[e]=s.tiles[e];os.setTiles(e,t)}n.add(e)}const d=s.tileWidth/u.width,h=s.tileHeight/u.height,f=s.tint,p=s.parallaxFactor;os.submitLayer(e,c,s.layer,0,s.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,s.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([rs,je]);for(const e of u){if(t.tryGet(e,as))continue;const i=t.tryGet(e,rs),c=t.tryGet(e,je);if(!i?.source||!c)continue;const u=es(i.source);if(!u)continue;if(!s.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];os.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&os.setTiles(i,o.tiles),t.push(i),n.add(i)}s.set(e,t)}const d=s.get(e);for(let e=0;e<u.layers.length&&e<d.length;e++){const t=d[e],n=u.tilesets[0];if(!n)continue;const s=Jn(n.textureHandle);if(!s)continue;const i=u.tileWidth/s.width,h=u.tileHeight/s.height;os.submitLayer(t,n.textureHandle,e,0,n.columns,i,h,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)os.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),Qn(),is()}}const Rc=new Ac;function Ic(e,t){return e.toFixed(t)}function kc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Fc{constructor(e,t="bottom-left"){this.visible_=!0,this.disposed_=!1,this.el_=document.createElement("div"),this.el_.style.cssText="\nposition: fixed;\nz-index: 99999;\npointer-events: none;\nbackground: rgba(30, 30, 30, 0.85);\nborder: 1px solid rgba(60, 60, 60, 0.8);\nborder-radius: 4px;\npadding: 6px 10px;\nfont: 11px monospace;\ncolor: #cccccc;\nline-height: 1.6;\nmin-width: 200px;\nwhite-space: pre;\n"+function(e){switch(e){case"top-left":return"top: 12px; left: 12px;";case"top-right":return"top: 12px; right: 12px;";case"bottom-left":return"bottom: 12px; left: 12px;";case"bottom-right":return"bottom: 12px; right: 12px;"}}(t),e.appendChild(this.el_)}update(e){if(!this.visible_||this.disposed_)return;const t=[];if(t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px">Performance</div><div>FPS: <span style="color:#d19a66">${Ic(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ic(e.frameTimeMs,1)}ms</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Rendering</div><div>DC: <span style="color:#d19a66">${e.drawCalls}</span> Tri: <span style="color:#d19a66">${e.triangles}</span></div><div>Sprites: <span style="color:#d19a66">${e.sprites}</span> Culled: <span style="color:#d19a66">${e.culled}</span></div>`),t.push(`<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">World</div><div>Entities: <span style="color:#d19a66">${e.entityCount}</span></div>`),e.systemTimings.size>0){const n=[...e.systemTimings.entries()].sort((e,t)=>t[1]-e[1]).slice(0,5);let s='<div style="color:#8c8c8c;border-bottom:1px solid rgba(60,60,60,0.8);padding-bottom:3px;margin-bottom:3px;margin-top:4px">Systems (top 5)</div>';for(const[e,t]of n){s+=`<div>${kc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ic(t,1)}ms</span></div>`}t.push(s)}this.el_.innerHTML=t.join("")}show(){this.visible_=!0,this.el_.style.display=""}hide(){this.visible_=!1,this.el_.style.display="none"}dispose(){this.disposed_=!0,this.el_.parentElement?.removeChild(this.el_)}}function Bc(){return{fps:0,frameTimeMs:0,entityCount:0,systemTimings:new Map,phaseTimings:new Map,drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}}const zc=pt(Bc(),"Stats");class Uc{constructor(e=300){this.buffer_=[],this.cursor_=0,this.count_=0,this.capacity_=e}get count(){return this.count_}push(e,t,n){const s={frameTimeMs:e,phaseTimings:new Map(t),systemTimings:n?new Map(n):new Map};this.count_<this.capacity_?(this.buffer_.push(s),this.count_++):this.buffer_[this.cursor_]=s,this.cursor_=(this.cursor_+1)%this.capacity_}getLatest(){if(0===this.count_)return null;const e=(this.cursor_-1+this.capacity_)%this.capacity_;return this.buffer_[e]}getAll(){return 0===this.count_?[]:this.count_<this.capacity_?this.buffer_.slice():[...this.buffer_.slice(this.cursor_),...this.buffer_.slice(0,this.cursor_)]}reset(){this.buffer_.length=0,this.cursor_=0,this.count_=0}}const Wc="StatsCollect";class $c{constructor(){this.deltas_=[],this.cursor_=0,this.count_=0,this.sum_=0}pushFrame(e){!Number.isFinite(e)||e<0||(this.count_<60?(this.deltas_.push(e),this.sum_+=e,this.count_++):(this.sum_-=this.deltas_[this.cursor_],this.deltas_[this.cursor_]=e,this.sum_+=e,this.cursor_=(this.cursor_+1)%60))}getFps(){return 0===this.count_||this.sum_<=0?0:this.count_/this.sum_}getFrameTimeMs(){return 0===this.count_||this.sum_<=0?0:this.sum_/this.count_*1e3}reset(){this.deltas_.length=0,this.cursor_=0,this.count_=0,this.sum_=0}}class Dc{constructor(e){this.name="Stats",this.collector_=new $c,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(zc,Bc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Fc(e,this.options_.position)}const t=this.collector_,n=this.overlay_,s=an([mt(wt),{_type:"get_world"}],(s,i)=>{t.pushFrame(s.delta);const o=e.getResource(zc);o.fps=t.getFps(),o.frameTimeMs=t.getFrameTimeMs(),o.entityCount=i.entityCount();const r=e.getSystemTimings();if(r){const e=new Map(r);e.delete(Wc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=to.getStats();o.drawCalls=l.drawCalls,o.triangles=l.triangles,o.sprites=l.sprites,o.text=l.text,o.spine=l.spine,o.meshes=l.meshes,o.culled=l.culled,n?.update(o)},{name:Wc});e.addSystemToSchedule(sn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Lc=new Dc;class Oc{constructor(e){this.assets_=e}async loadPixels(e){return function(e){return new Promise((t,n)=>{const s=new Image;s.onload=()=>{const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const n=e.getContext("2d");n.drawImage(s,0,0);const i=n.getImageData(0,0,s.width,s.height);t({width:s.width,height:s.height,pixels:new Uint8Array(i.data.buffer)})},s.onerror=n,s.src=e})}(this.getAsset(e))}readText(e){return function(e){return atob(e.split(",")[1])}(this.getAsset(e))}readBinary(e){return function(e){const t=atob(e.split(",")[1]),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(this.getAsset(e))}resolvePath(e){return e}getAsset(e){const t=this.assets_[e];if(!t)throw new Error(`Asset not found: ${e}`);return t}}async function Hc(e,t){try{const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(t);return await e({instantiateWasm:(e,t)=>(WebAssembly.instantiate(n.buffer,e).then(e=>{t(e.instance,e.module)}),{})})}catch(e){return null}}async function jc(e){const{app:t,module:n,assets:s,scenes:i,firstScene:o}=e,r=t.getResource(Bs);r&&(r.registerEmbeddedAssets(s),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Hc(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,l=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Hc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Oc(s);await Cl({app:t,module:n,provider:c,scenes:i,firstScene:o,spineModule:a,physicsModule:l,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Vc=[cr,Sr,Ir,ta,ua,Hr,pa,wa,Pa,oa,qr,Ca,Ia,Ua,Da,Na,Ya],Nc=[...Vc,hc,xc,Cc,Rc,Gi];function Xc(e,t){return function(e,t){const n=go.new(),s=new e.Registry;n.connectCpp(s,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Zs(e),Mn(e),gi(e),Ei(e),Zi(e),so(e);const i=new ro;n.setPipeline(i);let o=h();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=vo(e,s,t,i));const r=n.getResource(yn);if(o.length>0){const e=o[0],n=e.viewportRect;r.viewProjection.set(e.viewProjection),r.vpX=Math.round(n.x*t),r.vpY=Math.round((1-n.y-n.h)*i),r.vpW=Math.round(n.w*t),r.vpH=Math.round(n.h*i),r.screenW=t,r.screenH=i,r.worldLeft=e.cameraX-e.halfW,r.worldRight=e.cameraX+e.halfW,r.worldBottom=e.cameraY-e.halfH,r.worldTop=e.cameraY+e.halfH,r.valid=!0}else r.valid=!1}n.insertResource(yn,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=r();a(e,t)}},c={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=r();if(0===t||0===l)return;const c=e.registry_getCanvasEntity(s);if(c>=0){const e=s.getCanvas(c).backgroundColor;to.setClearColor(e.x,e.y,e.z,e.w)}const u=(h()-o)/1e3;let d;if(to.resize(t,l),n.hasResource(ho)){const e=n.getResource(ho).getActiveScenes();e.length>0&&(d=new Set(e))}i.setActiveScenes(d??null);const f=vo(e,s,t,l,n.world,d);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:s},viewProjection:_o,width:t,height:l,elapsed:u});else{i.beginScreenCapture();for(const e of f){const n=e.viewportRect,o=Math.round(n.x*t),r=Math.round((1-n.y-n.h)*l),a=Math.round(n.w*t),c=Math.round(n.h*l);i.renderCamera({registry:{_cpp:s},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),to.setViewport(0,0,t,l)}}};if(n.addSystemToSchedule(sn.First,l),n.addSystemToSchedule(sn.Last,c),n.addPlugin(Us),n.addPlugin(Ys),n.addPlugin(gn),n.addPlugin(mo),t?.plugins)for(const e of t.plugins)n.addPlugin(e);return n}(e,{plugins:Nc,...t})}class Yc{constructor(e){this.resolvePath_=e}async loadPixels(e){return async function(e){return t().loadImagePixels(e)}(this.resolvePath_(e))}async readText(e){return l(this.resolvePath_(e))}async readBinary(e){const t=await a(this.resolvePath_(e));return new Uint8Array(t)}resolvePath(e){return this.resolvePath_(e)}}function qc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Gc(e,t){try{return await e({instantiateWasm:qc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function Kc(e){const t=await l("asset-manifest.json"),n=JSON.parse(t),s=function(e){const t={},n={};for(const s in e.groups){const i=e.groups[s];for(const e in i.assets){const s=i.assets[e];t[e]=s,n[s.path]=s}}return{assetIndex:t,pathIndex:n}}(n),i=function(e){const{assetIndex:t,pathIndex:n}=e;return e=>{const s=W(e),i=t[e]||t[s]||n[s]||n[e];return i?i.path:s}}(s),o=wx.createCanvas(),r=wx.getSystemInfoSync();o.width=r.windowWidth*r.pixelRatio,o.height=r.windowHeight*r.pixelRatio;const a=await e.engineFactory({canvas:o,instantiateWasm:qc("esengine.wasm")}),c=o.getContext("webgl2")||o.getContext("webgl");if(!c)return void console.error("[ESEngine] Failed to create WebGL context");const u=a.GL.registerContext(c,{majorVersion:0===c.getParameter(c.VERSION).indexOf("WebGL 2")?2:1,minorVersion:0,enableExtensionsByDefault:!0}),d=Xc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await Gc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Gc(e.physicsFactory,"physics.wasm"));const p=new Yc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Cl({app:d,module:a,provider:p,scenes:m,firstScene:e.firstScene,spineModule:h,physicsModule:f,physicsConfig:e.physicsConfig,manifest:n,aspectRatio:o.width/o.height}),d.run()}J||(J=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const n="string"==typeof e?e:e.toString(),s={method:t?.method??"GET",headers:t?.headers,body:t?.body},i=await w(n,s);return{ok:i.ok,status:i.status,statusText:i.statusText,headers:new Headers(i.headers),json:()=>i.json(),text:()=>i.text(),arrayBuffer:()=>i.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:n}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return x(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),n=new Uint8Array(t);let s=0;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i<128?n[s++]=i:i<2048?(n[s++]=192|i>>6,n[s++]=128|63&i):i>=55296&&i<=56319?(i=e.charCodeAt(++t)-56320+(i-55296<<10)+65536,n[s++]=240|i>>18,n[s++]=128|i>>12&63,n[s++]=128|i>>6&63,n[s++]=128|63&i):(n[s++]=224|i>>12,n[s++]=128|i>>6&63,n[s++]=128|63&i)}return n.subarray(0,s)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let n="";for(let e=0;e<t.length;){const s=t[e];if(s<128)n+=String.fromCharCode(s),e++;else if(192==(224&s))n+=String.fromCharCode((31&s)<<6|63&t[e+1]),e+=2;else if(224==(240&s))n+=String.fromCharCode((15&s)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const i=((7&s)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;n+=String.fromCharCode(55296+(i>>10),56320+(1023&i)),e+=4}}return n}})}(),console.log("[ESEngine] WeChat platform initialized")),e=Q;export{Wt as Added,dc as AnimationPlugin,go as App,zs as AssetPlugin,Ws as AssetRefCounter,Fs as AssetServer,Bs as Assets,Un as AsyncCache,fc as AttenuationModel,Yn as Audio,p as AudioBus,_c as AudioListener,m as AudioMixer,wc as AudioPlugin,g as AudioPool,yc as AudioSource,Qe as BitmapText,_n as BlendMode,ht as BodyType,ct as BoxCollider,Cr as Button,Tr as ButtonState,Ye as Camera,qe as Canvas,dt as CapsuleCollider,$t as Changed,Je as Children,ut as CircleCollider,Oe as ClearFlags,Yt as Commands,Gt as CommandsInstance,ee as DEFAULT_DESIGN_HEIGHT,Z as DEFAULT_DESIGN_WIDTH,le as DEFAULT_FALLBACK_DT,ue as DEFAULT_FIXED_TIMESTEP,ie as DEFAULT_FONT_FAMILY,oe as DEFAULT_FONT_SIZE,ce as DEFAULT_GRAVITY,re as DEFAULT_LINE_HEIGHT,ae as DEFAULT_MAX_DELTA_TIME,te as DEFAULT_PIXELS_PER_UNIT,de as DEFAULT_SPINE_SKIN,se as DEFAULT_SPRITE_SIZE,ne as DEFAULT_TEXT_CANVAS_SIZE,di as DataType,fa as DragPlugin,ha as DragState,da as Draggable,si as Draw,Wa as Dropdown,$a as DropdownPlugin,Hl as EasingType,et as EmitterShape,qt as EntityCommands,en as EventReader,nn as EventReaderInstance,Qt as EventRegistry,Zt as EventWriter,tn as EventWriterInstance,Io as FillDirection,Kr as FillMethod,Jr as FillOrigin,Xr as FocusManager,Nr as FocusManagerState,Ta as FocusPlugin,Vr as Focusable,Uc as FrameHistory,oo as GLDebug,wi as Geometry,on as GetWorld,ge as INVALID_ENTITY,_e as INVALID_FONT,we as INVALID_MATERIAL,ye as INVALID_TEXTURE,Qr as Image,ea as ImagePlugin,Gr as ImageType,pn as Input,mn as InputPlugin,fn as InputState,Mr as Interactable,Va as LayoutGroupPlugin,ka as ListView,za as ListViewPlugin,Ve as LocalTransform,kl as LogLevel,Bl as Logger,Vl as LoopMode,Cn as Material,Wn as MaterialLoader,zt as Mut,it as Name,Ke as Parent,Pc as Particle,nt as ParticleEasing,st as ParticleEmitter,Tc as ParticlePlugin,wl as Physics,dl as PhysicsEvents,ml as PhysicsPlugin,Ii as PostProcess,qi as PostProcessPlugin,Pi as PostProcessStack,rt as PostProcessVolume,Vs as PrefabServer,Ns as Prefabs,Xs as PrefabsPlugin,Rl as PreviewPlugin,aa as ProgressBar,ra as ProgressBarDirection,ca as ProgressBarPlugin,Le as ProjectionType,jt as Query,Vt as QueryInstance,Nt as Removed,Xt as RemovedQueryInstance,ro as RenderPipeline,Ki as RenderStage,Il as RenderTexture,to as Renderer,mt as Res,gt as ResMut,lt as RigidBody,he as RuntimeConfig,Ea as SafeArea,Ra as SafeAreaPlugin,He as ScaleMode,ho as SceneManager,uo as SceneManagerState,ot as SceneOwner,sn as Schedule,ma as ScrollView,_a as ScrollViewPlugin,zn as ShaderSources,tt as SimulationSpace,ba as Slider,xa as SliderDirection,Ma as SliderPlugin,Ze as SpineAnimation,Xe as Sprite,Nn as SpriteAnimator,zc as Stats,$c as StatsCollector,Fc as StatsOverlay,Dc as StatsPlugin,bt as Storage,hn as SystemRunner,or as Text,nr as TextAlign,jr as TextInput,Yr as TextInputPlugin,ir as TextOverflow,lr as TextPlugin,rr as TextRenderer,sr as TextVerticalAlign,rs as Tilemap,os as TilemapAPI,as as TilemapLayer,Ac as TilemapPlugin,wt as Time,na as Toggle,ia as TogglePlugin,je as Transform,uc as Tween,sc as TweenHandle,jl as TweenState,nc as TweenTarget,yn as UICameraInfo,Er as UIEventQueue,Ar as UIEvents,Pr as UIInteraction,Or as UIInteractionPlugin,Rr as UILayoutPlugin,hr as UIMask,vr as UIMaskPlugin,Fo as UIRect,Xa as UIRenderOrderPlugin,Ge as Velocity,Yc as WeChatAssetProvider,El as WebAssetProvider,Bt as World,Ne as WorldTransform,un as addStartupSystem,cn as addSystem,dn as addSystemToSchedule,hc as animationPlugin,me as applyBuildRuntimeConfig,Lo as applyDirectionalFill,fe as applyRuntimeConfig,Us as assetPlugin,xc as audioPlugin,mc as calculateAttenuation,gc as calculatePanning,Oi as cleanupAllPostProcessVolumes,Li as cleanupPostProcessVolume,Vn as clearAnimClips,ui as clearDrawCallbacks,Qn as clearTextureDimensionsCache,ts as clearTilemapSourceCache,ke as clearUserComponents,Se as color,Wo as computeFillAnchors,Do as computeFillSize,$o as computeHandleAnchors,ko as computeUIRectLayout,br as createMaskProcessor,Tl as createRuntimeSceneConfig,Xc as createWebApp,$l as debug,Bc as defaultFrameStats,Ae as defineComponent,Kt as defineEvent,pt as defineResource,an as defineSystem,Re as defineTag,pa as dragPlugin,Da as dropdownPlugin,Ol as error,$n as extractAnimClipTexturePaths,ks as findEntityByName,yo as flushPendingSystems,Ca as focusPlugin,E as getAddressableType,A as getAddressableTypeByEditorType,I as getAllAssetExtensions,Ui as getAllEffectDefs,jn as getAnimClip,D as getAssetBuildTransform,z as getAssetMimeType,T as getAssetTypeEntry,$e as getComponent,xs as getComponentAssetFieldDescriptors,ws as getComponentAssetFields,at as getComponentDefaults,Ms as getComponentEntityFields,bs as getComponentSpineFieldDescriptor,F as getCustomExtensions,C as getEditorType,Bi as getEffectDef,zi as getEffectTypes,Ul as getLogger,t as getPlatform,s as getPlatformType,Jn as getTextureDimensions,es as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,ta as imagePlugin,Dl as info,Zs as initDrawAPI,so as initGLDebugAPI,gi as initGeometryAPI,Mn as initMaterialAPI,Sc as initParticleAPI,jc as initPlayableRuntime,Ei as initPostProcessAPI,Zi as initRendererAPI,Cl as initRuntime,ss as initTilemapAPI,rc as initTweenAPI,Kc as initWeChatRuntime,gn as inputPlugin,Ds as instantiatePrefab,fr as intersectRects,pr as invertMatrix4,ze as isBuiltinComponent,U as isCustomExtension,zr as isEditor,R as isKnownAssetExtension,n as isPlatformInitialized,$r as isPlayMode,Ur as isRuntime,wn as isTextureRef,i as isWeChat,o as isWeb,Na as layoutGroupPlugin,Ua as listViewPlugin,Rs as loadComponent,Ga as loadPhysicsModule,Pl as loadRuntimeScene,Cs as loadSceneData,Es as loadSceneWithAssets,gs as loadTiledMap,k as looksLikeAssetPath,Dn as parseAnimClipData,fs as parseTiledMap,ds as parseTmjJson,Cc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,wr as pointInOBB,gr as pointInWorldRect,Gi as postProcessPlugin,Ys as prefabsPlugin,ua as progressBarPlugin,Me as quat,On as registerAnimClip,$ as registerAssetBuildTransform,We as registerComponent,_s as registerComponentAssetFields,Ss as registerComponentEntityFields,li as registerDrawCallback,$s as registerEmbeddedAssets,Bn as registerMaterialCallback,Kn as registerTextureDimensions,Zn as registerTilemapSource,Ps as remapEntityFields,hs as resolveRelativePath,Ia as safeAreaPlugin,mo as sceneManagerPlugin,mr as screenToWorld,wa as scrollViewPlugin,Br as setEditorMode,Ba as setListViewRenderer,Wl as setLogLevel,Wr as setPlayMode,Tt as setWasmErrorHandler,ei as shutdownDrawAPI,io as shutdownGLDebugAPI,yi as shutdownGeometryAPI,Pn as shutdownMaterialAPI,Mc as shutdownParticleAPI,Ai as shutdownPostProcessAPI,eo as shutdownRendererAPI,is as shutdownTilemapAPI,ac as shutdownTweenAPI,Pa as sliderPlugin,Xn as spriteAnimatorSystemUpdate,Lc as statsPlugin,qo as syncFillSpriteSize,Di as syncPostProcessVolume,qr as textInputPlugin,cr as textPlugin,Rc as tilemapPlugin,W as toBuildPath,oa as togglePlugin,qa as transitionTo,Hr as uiInteractionPlugin,Ir as uiLayoutPlugin,Sr as uiMaskPlugin,Vc as uiPlugins,Ya as uiRenderOrderPlugin,Hn as unregisterAnimClip,Fe as unregisterComponent,ci as unregisterDrawCallback,Is as updateCameraAspectRatio,xe as vec2,be as vec3,ve as vec4,Ll as warn,fo as wrapSceneSystem,N as wxFileExists,X as wxFileExistsSync,G as wxGetImagePixels,q as wxLoadImage,K as wxLoadImagePixels,j as wxReadFile,V as wxReadTextFile,Y as wxWriteFile};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/shared/index.js b/desktop/public/sdk/esm/shared/index.js
index 9fe140c23..e5791db89 100644
--- a/desktop/public/sdk/esm/shared/index.js
+++ b/desktop/public/sdk/esm/shared/index.js
@@ -1,2 +1,2 @@
-import{M as e,aC as t,j as s,d as n,e as i,T as r,f as o,C as a,_ as c,B as l,J as u,S as y,i as h,n as d,o as _,x as p}from"./material.js";let f=null,m=0,g=0,b=0;const w=new Float32Array(256);function x(e){f=e,m=f._malloc(64),g=f._malloc(64),b=f._malloc(1024)}function E(){f&&(m&&(f._free(m),m=0),g&&(f._free(g),g=0),b&&(f._free(b),b=0)),f=null}function P(){if(!f)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return f}const M={r:1,g:1,b:1,a:1},C={begin(e){const t=P();try{t.HEAPF32.set(e,m/4),t.draw_begin(m)}catch(e){s(e,"Draw.begin")}},end(){try{P().draw_end()}catch(e){s(e,"Draw.end")}},line(e,t,n,i=1){try{P().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,i)}catch(e){s(e,"Draw.line")}},rect(e,t,n,i=!0){try{P().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,i)}catch(e){s(e,"Draw.rect")}},rectOutline(e,t,n,i=1){try{P().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,i)}catch(e){s(e,"Draw.rectOutline")}},circle(e,t,n,i=!0,r=32){try{P().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,i,r)}catch(e){s(e,"Draw.circle")}},circleOutline(e,t,n,i=1,r=32){try{P().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,i,r)}catch(e){s(e,"Draw.circleOutline")}},texture(e,t,n,i=M){try{P().draw_texture(e.x,e.y,t.x,t.y,n,i.r,i.g,i.b,i.a)}catch(e){s(e,"Draw.texture")}},textureRotated(e,t,n,i,r=M){try{P().draw_textureRotated(e.x,e.y,t.x,t.y,n,i,r.r,r.g,r.b,r.a)}catch(e){s(e,"Draw.textureRotated")}},setLayer(e){P().draw_setLayer(e)},setDepth(e){P().draw_setDepth(e)},getDrawCallCount:()=>f?f.draw_getDrawCallCount():0,getPrimitiveCount:()=>f?f.draw_getPrimitiveCount():0,setBlendMode(e){P().draw_setBlendMode(e)},setDepthTest(e){P().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=P();s.HEAPF32.set(n,g/4),s.draw_mesh(e,t,g)}catch(n){s(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(n,i,r){try{const s=P(),o=e.get(i);if(!o)return;if(C.setBlendMode(o.blendMode),C.setDepthTest(o.depthTest),0===o.uniforms.size)return void C.drawMesh(n,o.shader,r);let a;if(s.HEAPF32.set(r,g/4),!o.dirty_&&o.cachedBuffer_)a=o.cachedIdx_;else{a=0;let e=0;for(const[s,n]of o.uniforms){const i=D(s);if(!(i<0)){if(t(n))w[a++]=10,w[a++]=i,w[a++]=n.slot??e++,w[a++]=n.textureId;else if("number"==typeof n)w[a++]=1,w[a++]=i,w[a++]=n;else if(Array.isArray(n)){w[a++]=n.length,w[a++]=i;for(let e=0;e<n.length;e++)w[a++]=n[e]}else"w"in n?(w[a++]=4,w[a++]=i,w[a++]=n.x,w[a++]=n.y,w[a++]=n.z,w[a++]=n.w):"z"in n?(w[a++]=3,w[a++]=i,w[a++]=n.x,w[a++]=n.y,w[a++]=n.z):(w[a++]=2,w[a++]=i,w[a++]=n.x,w[a++]=n.y);if(a>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!o.cachedBuffer_||o.cachedBuffer_.length<a)&&(o.cachedBuffer_=new Float32Array(a)),o.cachedBuffer_.set(w.subarray(0,a)),o.cachedIdx_=a,o.dirty_=!1}if(0===a)return void s.draw_mesh(n,o.shader,g);s.HEAPF32.set(o.cachedBuffer_.subarray(0,a),b/4),s.draw_meshWithUniforms(n,o.shader,g,b,a)}catch(e){s(e,`Draw.drawMeshWithMaterial(geometry=${n}, material=${i})`)}}},A={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},B=new Set;function D(e){const t=A[e];return void 0!==t?t:(B.has(e)||(B.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(A).join(", ")}`)),-1)}const S=new Map;function v(e,t,s){S.set(e,{fn:t,scene:s??""})}function T(e){S.delete(e)}function H(){S.clear()}function R(){return S}let U=!1,F=!1;function I(e){U=e}function V(){return U}function L(){return!U}function z(e){F=e}function k(){return F}async function O(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function G(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const s=t.cwrap.bind(t);return{_physics_init:s("physics_init",null,["number","number","number","number"]),_physics_shutdown:s("physics_shutdown",null,[]),_physics_createBody:s("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:s("physics_destroyBody",null,["number"]),_physics_hasBody:s("physics_hasBody","number",["number"]),_physics_addBoxShape:s("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:s("physics_addCircleShape",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:s("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number","number","number"]),_physics_step:s("physics_step",null,["number"]),_physics_setBodyTransform:s("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:s("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:s("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:s("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:s("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:s("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:s("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:s("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:s("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:s("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:s("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:s("physics_getSensorExitBuffer","number",[]),_physics_applyForce:s("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:s("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:s("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:s("physics_getLinearVelocity","number",["number"]),_physics_setGravity:s("physics_setGravity",null,["number","number"]),_physics_getGravity:s("physics_getGravity","number",[]),_physics_setAngularVelocity:s("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:s("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:s("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:s("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:s("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const W=n({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),j={r:.2,g:.4,b:1,a:.7},q={r:.2,g:1,b:.2,a:.7},$={r:.2,g:1,b:1,a:.7},X={r:1,g:1,b:.2,a:.5},Y={r:1,g:.2,b:.2,a:.8},K={r:1,g:.2,b:.2,a:1},J=1.5,N=16;function Q(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Z(e){switch(e){case l.Static:return j;case l.Kinematic:return $;case l.Dynamic:default:return q}}function ee(e,t,s,n,i,r){const o=Math.cos(i),a=Math.sin(i),c=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*o-s.y*a,y:t+s.x*a+s.y*o}));for(let e=0;e<4;e++)C.line(c[e],c[(e+1)%4],r,J)}function te(e,t,s,n,i,r){const o=Math.cos(i),a=Math.sin(i),c=(s,n)=>({x:e+s*o-n*a,y:t+s*a+n*o}),l=c(-s,n),u=c(s,n),y=c(-s,-n),h=c(s,-n);C.line(l,y,r,J),C.line(u,h,r,J);for(let e=0;e<N;e++){const t=e/N*Math.PI,i=(e+1)/N*Math.PI,o=c(-s*Math.cos(t),n+s*Math.sin(t)),a=c(-s*Math.cos(i),n+s*Math.sin(i));C.line(o,a,r,J)}for(let e=0;e<N;e++){const t=Math.PI+e/N*Math.PI,i=Math.PI+(e+1)/N*Math.PI,o=c(-s*Math.cos(t),-n+s*Math.sin(t)),a=c(-s*Math.cos(i),-n+s*Math.sin(i));C.line(o,a,r,J)}}function se(e,t,s,n){const i=e+.5*s,r=t+.5*n;C.line({x:e,y:t},{x:i,y:r},Y,J);const o=Math.sqrt(s*s+n*n);if(o<1)return;const a=Math.PI/6,c=s/o,l=n/o,u=i-6*(c*Math.cos(a)-l*Math.sin(a)),y=r-6*(c*Math.sin(a)+l*Math.cos(a)),h=i-6*(c*Math.cos(a)+l*Math.sin(a)),d=r-6*(-c*Math.sin(a)+l*Math.cos(a));C.line({x:i,y:r},{x:u,y:y},Y,J),C.line({x:i,y:r},{x:h,y:d},Y,J)}function ne(e,t,s){if(V()&&!k())return;const n=e.getResource(W);if(!n||!n.enabled)return;const y=function(e){const t=e.world.getEntitiesWithComponents([u]);for(const s of t){const t=e.world.get(s,u);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),h=e.world.getEntitiesWithComponents([i,r]);let d=null;n.showVelocity&&e.hasResource(t)&&(d=e.getResource(t));for(const t of h){const s=e.world.get(t,i);if(!s.enabled)continue;const u=e.world.get(t,r),h=u.worldPosition.x,_=u.worldPosition.y,p=Q(u.worldRotation);if(n.showColliders){if(e.world.has(t,o)){const n=e.world.get(t,o),i=n.isSensor?X:Z(s.bodyType),r=n.offset.x*y,a=n.offset.y*y,c=Math.cos(p),l=Math.sin(p);ee(h+r*c-a*l,_+r*l+a*c,n.halfExtents.x*y,n.halfExtents.y*y,p,i)}if(e.world.has(t,a)){const n=e.world.get(t,a),i=n.isSensor?X:Z(s.bodyType),r=n.offset.x*y,o=n.offset.y*y,c=Math.cos(p),l=Math.sin(p),u=h+r*c-o*l,d=_+r*l+o*c;C.circleOutline({x:u,y:d},n.radius*y,i,J,32)}if(e.world.has(t,c)){const n=e.world.get(t,c),i=n.isSensor?X:Z(s.bodyType),r=n.offset.x*y,o=n.offset.y*y,a=Math.cos(p),l=Math.sin(p);te(h+r*a-o*l,_+r*l+o*a,n.radius*y,n.halfHeight*y,p,i)}}if(n.showVelocity&&d&&s.bodyType===l.Dynamic){const e=d.getLinearVelocity(t);se(h,_,e.x*y,e.y*y)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)C.circle({x:e.contactX,y:e.contactY},3,K,!0,32)}}function ie(e,t,s){e.insertResource(W,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),v("physics-debug-draw",()=>{ne(e,t,s)})}const re=n({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),oe=n(null,"PhysicsAPI");function ae(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ce(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class le{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,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(re,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=O(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const o=function(e){const t=e.world.getEntitiesWithComponents([u]);for(const s of t){const t=e.world.get(s,u);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),a=1/o,c=e.world;c.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(y.PostUpdate,h([d(_)],u=>{if(V()&&!k())return;const y=c.getEntitiesWithComponents([i,r]),h=new Set;for(const o of y){h.add(o);const u=c.get(o,i),y=c.get(o,r);if(t.has(o)){const e=s.get(o);!e||e.bodyType===u.bodyType&&e.gravityScale===u.gravityScale&&e.linearDamping===u.linearDamping&&e.angularDamping===u.angularDamping&&e.fixedRotation===u.fixedRotation&&e.bullet===u.bullet||(n._physics_updateBodyProperties(o,u.bodyType,u.gravityScale,u.linearDamping,u.angularDamping,u.fixedRotation?1:0,u.bullet?1:0),e.bodyType=u.bodyType,e.gravityScale=u.gravityScale,e.linearDamping=u.linearDamping,e.angularDamping=u.angularDamping,e.fixedRotation=u.fixedRotation,e.bullet=u.bullet)}else{if(!u.enabled)continue;const i=ae(y.worldRotation);n._physics_createBody(o,u.bodyType,y.worldPosition.x*a,y.worldPosition.y*a,i,u.gravityScale,u.linearDamping,u.angularDamping,u.fixedRotation?1:0,u.bullet?1:0),he(e,n,o,this.config_.collisionLayerMasks),t.add(o),s.set(o,{bodyType:u.bodyType,gravityScale:u.gravityScale,linearDamping:u.linearDamping,angularDamping:u.angularDamping,fixedRotation:u.fixedRotation,bullet:u.bullet})}if(u.bodyType===l.Kinematic){const e=ae(y.worldRotation);n._physics_setBodyTransform(o,y.worldPosition.x*a,y.worldPosition.y*a,e)}}for(const e of t)h.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(u.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,a=t.HEAPU32[n],c=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,u=t.HEAPF32[n+3];if(!e.world.valid(a))continue;const y=e.world.get(a,r);if(!y)continue;let h=c,d=l,_=u;if(e.world.has(a,p)){const t=e.world.get(a,p);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,r)){const s=e.world.get(t.entity,r),n=ae(s.worldRotation),i=c-s.worldPosition.x,o=l-s.worldPosition.y,a=Math.cos(-n),y=Math.sin(-n);h=(i*a-o*y)/(0!==s.worldScale.x?s.worldScale.x:1),d=(i*y+o*a)/(0!==s.worldScale.y?s.worldScale.y:1),_=u-n}}y.position.x=h,y.position.y=d;const f=ce(_);y.rotation.w=f.w,y.rotation.x=f.x,y.rotation.y=f.y,y.rotation.z=f.z,e.world.insert(a,r,y)}}(e,n,o),function(e,t,s){t._physics_collectEvents();const n=[],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;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+5]*s})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;r.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(re,{collisionEnters:n,collisionExits:r,sensorEnters:a,sensorExits:l})}(e,n,o)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(oe,de._fromModule(n)),ie(e,oe,re),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}const ue=16;function ye(e,t,s){if(!s)return t;for(let t=0;t<ue;t++)if(e===1<<t)return s[t];return t}function he(e,t,s,n){const i=e.world;if(i.has(s,o)){const e=i.get(s,o),r=e.categoryBits??1,a=ye(r,e.maskBits??65535,n);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,r,a)}if(i.has(s,a)){const e=i.get(s,a),r=e.categoryBits??1,o=ye(r,e.maskBits??65535,n);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,r,o)}if(i.has(s,c)){const e=i.get(s,c),r=e.categoryBits??1,o=ye(r,e.maskBits??65535,n);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,r,o)}}class de{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(de.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)}static setDebugDraw(e,t){const s=e.getResource(W);s&&(s.enabled=t,e.insertResource(W,s))}static setDebugDrawConfig(e,t){const s=e.getResource(W);s&&e.insertResource(W,{...s,...t})}}export{C as D,le as P,V as a,k as b,H as c,de as d,re as e,L as f,R as g,I as h,x as i,z as j,oe as k,O as l,W as m,ne as n,G as o,ie as p,v as r,E as s,T as u};
+import{M as e,aC as t,j as s,d as n,e as i,T as r,f as o,C as a,_ as c,B as l,J as u,S as y,i as h,n as d,o as _,x as p}from"./material.js";let f=null,m=0,g=0,b=0;const w=new Float32Array(256);function x(e){f=e,m=f._malloc(64),g=f._malloc(64),b=f._malloc(1024)}function E(){f&&(m&&(f._free(m),m=0),g&&(f._free(g),g=0),b&&(f._free(b),b=0)),f=null}function P(){if(!f)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return f}const M={r:1,g:1,b:1,a:1},C={begin(e){const t=P();try{t.HEAPF32.set(e,m/4),t.draw_begin(m)}catch(e){s(e,"Draw.begin")}},end(){try{P().draw_end()}catch(e){s(e,"Draw.end")}},line(e,t,n,i=1){try{P().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,i)}catch(e){s(e,"Draw.line")}},rect(e,t,n,i=!0){try{P().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,i)}catch(e){s(e,"Draw.rect")}},rectOutline(e,t,n,i=1){try{P().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,i)}catch(e){s(e,"Draw.rectOutline")}},circle(e,t,n,i=!0,r=32){try{P().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,i,r)}catch(e){s(e,"Draw.circle")}},circleOutline(e,t,n,i=1,r=32){try{P().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,i,r)}catch(e){s(e,"Draw.circleOutline")}},texture(e,t,n,i=M){try{P().draw_texture(e.x,e.y,t.x,t.y,n,i.r,i.g,i.b,i.a)}catch(e){s(e,"Draw.texture")}},textureRotated(e,t,n,i,r=M){try{P().draw_textureRotated(e.x,e.y,t.x,t.y,n,i,r.r,r.g,r.b,r.a)}catch(e){s(e,"Draw.textureRotated")}},setLayer(e){P().draw_setLayer(e)},setDepth(e){P().draw_setDepth(e)},getDrawCallCount:()=>f?f.draw_getDrawCallCount():0,getPrimitiveCount:()=>f?f.draw_getPrimitiveCount():0,setBlendMode(e){P().draw_setBlendMode(e)},setDepthTest(e){P().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=P();s.HEAPF32.set(n,g/4),s.draw_mesh(e,t,g)}catch(n){s(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(n,i,r){try{const s=P(),o=e.get(i);if(!o)return;if(C.setBlendMode(o.blendMode),C.setDepthTest(o.depthTest),0===o.uniforms.size)return void C.drawMesh(n,o.shader,r);let a;if(s.HEAPF32.set(r,g/4),!o.dirty_&&o.cachedBuffer_)a=o.cachedIdx_;else{a=0;let e=0;for(const[s,n]of o.uniforms){const i=D(s);if(!(i<0)){if(t(n))w[a++]=10,w[a++]=i,w[a++]=n.slot??e++,w[a++]=n.textureId;else if("number"==typeof n)w[a++]=1,w[a++]=i,w[a++]=n;else if(Array.isArray(n)){w[a++]=n.length,w[a++]=i;for(let e=0;e<n.length;e++)w[a++]=n[e]}else"w"in n?(w[a++]=4,w[a++]=i,w[a++]=n.x,w[a++]=n.y,w[a++]=n.z,w[a++]=n.w):"z"in n?(w[a++]=3,w[a++]=i,w[a++]=n.x,w[a++]=n.y,w[a++]=n.z):(w[a++]=2,w[a++]=i,w[a++]=n.x,w[a++]=n.y);if(a>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!o.cachedBuffer_||o.cachedBuffer_.length<a)&&(o.cachedBuffer_=new Float32Array(a)),o.cachedBuffer_.set(w.subarray(0,a)),o.cachedIdx_=a,o.dirty_=!1}if(0===a)return void s.draw_mesh(n,o.shader,g);s.HEAPF32.set(o.cachedBuffer_.subarray(0,a),b/4),s.draw_meshWithUniforms(n,o.shader,g,b,a)}catch(e){s(e,`Draw.drawMeshWithMaterial(geometry=${n}, material=${i})`)}}},A={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},B=new Set;function D(e){const t=A[e];return void 0!==t?t:(B.has(e)||(B.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(A).join(", ")}`)),-1)}const S=new Map;function v(e,t,s){S.set(e,{fn:t,scene:s??""})}function T(e){S.delete(e)}function H(){S.clear()}function R(){return S}let U=!1,F=!1;function I(e){U=e}function V(){return U}function L(){return!U}function z(e){F=e}function k(){return F}async function O(e,t){if(!t)throw new Error("PhysicsModuleLoader: factory parameter is required. Pass the Physics WASM factory function explicitly via loadPhysicsModule(url, factory).");return t()}async function G(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const s=t.cwrap.bind(t);return{_physics_init:s("physics_init",null,["number","number","number","number"]),_physics_shutdown:s("physics_shutdown",null,[]),_physics_createBody:s("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:s("physics_destroyBody",null,["number"]),_physics_hasBody:s("physics_hasBody","number",["number"]),_physics_addBoxShape:s("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:s("physics_addCircleShape",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:s("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number","number","number"]),_physics_step:s("physics_step",null,["number"]),_physics_setBodyTransform:s("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:s("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:s("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:s("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:s("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:s("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:s("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:s("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:s("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:s("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:s("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:s("physics_getSensorExitBuffer","number",[]),_physics_applyForce:s("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:s("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:s("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:s("physics_getLinearVelocity","number",["number"]),_physics_setGravity:s("physics_setGravity",null,["number","number"]),_physics_getGravity:s("physics_getGravity","number",[]),_physics_setAngularVelocity:s("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:s("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:s("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:s("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:s("physics_updateBodyProperties",null,["number","number","number","number","number","number","number"]),get HEAPF32(){return t.HEAPF32},get HEAPU8(){return t.HEAPU8},get HEAPU32(){return t.HEAPU32},_malloc:t._malloc.bind(t),_free:t._free.bind(t)}}const W=n({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),j={r:.2,g:.4,b:1,a:.7},q={r:.2,g:1,b:.2,a:.7},$={r:.2,g:1,b:1,a:.7},X={r:1,g:1,b:.2,a:.5},Y={r:1,g:.2,b:.2,a:.8},K={r:1,g:.2,b:.2,a:1},J=1.5,N=16;function Q(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Z(e){switch(e){case l.Static:return j;case l.Kinematic:return $;case l.Dynamic:default:return q}}function ee(e,t,s,n,i,r){const o=Math.cos(i),a=Math.sin(i),c=[{x:-s,y:-n},{x:s,y:-n},{x:s,y:n},{x:-s,y:n}].map(s=>({x:e+s.x*o-s.y*a,y:t+s.x*a+s.y*o}));for(let e=0;e<4;e++)C.line(c[e],c[(e+1)%4],r,J)}function te(e,t,s,n,i,r){const o=Math.cos(i),a=Math.sin(i),c=(s,n)=>({x:e+s*o-n*a,y:t+s*a+n*o}),l=c(-s,n),u=c(s,n),y=c(-s,-n),h=c(s,-n);C.line(l,y,r,J),C.line(u,h,r,J);for(let e=0;e<N;e++){const t=e/N*Math.PI,i=(e+1)/N*Math.PI,o=c(-s*Math.cos(t),n+s*Math.sin(t)),a=c(-s*Math.cos(i),n+s*Math.sin(i));C.line(o,a,r,J)}for(let e=0;e<N;e++){const t=Math.PI+e/N*Math.PI,i=Math.PI+(e+1)/N*Math.PI,o=c(-s*Math.cos(t),-n+s*Math.sin(t)),a=c(-s*Math.cos(i),-n+s*Math.sin(i));C.line(o,a,r,J)}}function se(e,t,s,n){const i=e+.5*s,r=t+.5*n;C.line({x:e,y:t},{x:i,y:r},Y,J);const o=Math.sqrt(s*s+n*n);if(o<1)return;const a=Math.PI/6,c=s/o,l=n/o,u=i-6*(c*Math.cos(a)-l*Math.sin(a)),y=r-6*(c*Math.sin(a)+l*Math.cos(a)),h=i-6*(c*Math.cos(a)+l*Math.sin(a)),d=r-6*(-c*Math.sin(a)+l*Math.cos(a));C.line({x:i,y:r},{x:u,y:y},Y,J),C.line({x:i,y:r},{x:h,y:d},Y,J)}function ne(e,t,s){const n=e.getResource(W);if(!n||!n.enabled)return;const y=function(e){const t=e.world.getEntitiesWithComponents([u]);for(const s of t){const t=e.world.get(s,u);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),h=e.world.getEntitiesWithComponents([i,r]);let d=null;n.showVelocity&&e.hasResource(t)&&(d=e.getResource(t));for(const t of h){const s=e.world.get(t,i);if(!s.enabled)continue;const u=e.world.get(t,r),h=u.worldPosition.x,_=u.worldPosition.y,p=Q(u.worldRotation);if(n.showColliders){if(e.world.has(t,o)){const n=e.world.get(t,o),i=n.isSensor?X:Z(s.bodyType),r=n.offset.x*y,a=n.offset.y*y,c=Math.cos(p),l=Math.sin(p);ee(h+r*c-a*l,_+r*l+a*c,n.halfExtents.x*y,n.halfExtents.y*y,p,i)}if(e.world.has(t,a)){const n=e.world.get(t,a),i=n.isSensor?X:Z(s.bodyType),r=n.offset.x*y,o=n.offset.y*y,c=Math.cos(p),l=Math.sin(p),u=h+r*c-o*l,d=_+r*l+o*c;C.circleOutline({x:u,y:d},n.radius*y,i,J,32)}if(e.world.has(t,c)){const n=e.world.get(t,c),i=n.isSensor?X:Z(s.bodyType),r=n.offset.x*y,o=n.offset.y*y,a=Math.cos(p),l=Math.sin(p);te(h+r*a-o*l,_+r*l+o*a,n.radius*y,n.halfHeight*y,p,i)}}if(n.showVelocity&&d&&s.bodyType===l.Dynamic){const e=d.getLinearVelocity(t);se(h,_,e.x*y,e.y*y)}}if(n.showContacts&&e.hasResource(s)){const t=e.getResource(s);for(const e of t.collisionEnters)C.circle({x:e.contactX,y:e.contactY},3,K,!0,32)}}function ie(e,t,s){e.insertResource(W,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),v("physics-debug-draw",()=>{ne(e,t,s)})}const re=n({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),oe=n(null,"PhysicsAPI");function ae(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ce(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class le{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,collisionLayerMasks:t.collisionLayerMasks}}build(e){e.insertResource(re,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=O(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const o=function(e){const t=e.world.getEntitiesWithComponents([u]);for(const s of t){const t=e.world.get(s,u);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),a=1/o,c=e.world;c.onDespawn(e=>{t.has(e)&&(n._physics_destroyBody(e),t.delete(e),s.delete(e))}),e.addSystemToSchedule(y.PostUpdate,h([d(_)],u=>{if(V()&&!k())return;const y=c.getEntitiesWithComponents([i,r]),h=new Set;for(const o of y){h.add(o);const u=c.get(o,i),y=c.get(o,r);if(t.has(o)){const e=s.get(o);!e||e.bodyType===u.bodyType&&e.gravityScale===u.gravityScale&&e.linearDamping===u.linearDamping&&e.angularDamping===u.angularDamping&&e.fixedRotation===u.fixedRotation&&e.bullet===u.bullet||(n._physics_updateBodyProperties(o,u.bodyType,u.gravityScale,u.linearDamping,u.angularDamping,u.fixedRotation?1:0,u.bullet?1:0),e.bodyType=u.bodyType,e.gravityScale=u.gravityScale,e.linearDamping=u.linearDamping,e.angularDamping=u.angularDamping,e.fixedRotation=u.fixedRotation,e.bullet=u.bullet)}else{if(!u.enabled)continue;const i=ae(y.worldRotation);n._physics_createBody(o,u.bodyType,y.worldPosition.x*a,y.worldPosition.y*a,i,u.gravityScale,u.linearDamping,u.angularDamping,u.fixedRotation?1:0,u.bullet?1:0),he(e,n,o,this.config_.collisionLayerMasks),t.add(o),s.set(o,{bodyType:u.bodyType,gravityScale:u.gravityScale,linearDamping:u.linearDamping,angularDamping:u.angularDamping,fixedRotation:u.fixedRotation,bullet:u.bullet})}if(u.bodyType===l.Kinematic){const e=ae(y.worldRotation);n._physics_setBodyTransform(o,y.worldPosition.x*a,y.worldPosition.y*a,e)}}for(const e of t)h.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(u.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const i=t._physics_getDynamicBodyTransforms(),o=i>>2;for(let i=0;i<n;i++){const n=o+4*i,a=t.HEAPU32[n],c=t.HEAPF32[n+1]*s,l=t.HEAPF32[n+2]*s,u=t.HEAPF32[n+3];if(!e.world.valid(a))continue;const y=e.world.get(a,r);if(!y)continue;let h=c,d=l,_=u;if(e.world.has(a,p)){const t=e.world.get(a,p);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,r)){const s=e.world.get(t.entity,r),n=ae(s.worldRotation),i=c-s.worldPosition.x,o=l-s.worldPosition.y,a=Math.cos(-n),y=Math.sin(-n);h=(i*a-o*y)/(0!==s.worldScale.x?s.worldScale.x:1),d=(i*y+o*a)/(0!==s.worldScale.y?s.worldScale.y:1),_=u-n}}y.position.x=h,y.position.y=d;const f=ce(_);y.rotation.w=f.w,y.rotation.x=f.x,y.rotation.y=f.y,y.rotation.z=f.z,e.world.insert(a,r,y)}}(e,n,o),function(e,t,s){t._physics_collectEvents();const n=[],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;n.push({entityA:t.HEAPU32[i],entityB:t.HEAPU32[i+1],normalX:t.HEAPF32[i+2],normalY:t.HEAPF32[i+3],contactX:t.HEAPF32[i+4]*s,contactY:t.HEAPF32[i+5]*s})}}const r=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<o;s++){const n=e+2*s;r.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],c=t._physics_getSensorEnterCount();if(c>0){const e=t._physics_getSensorEnterBuffer()>>2;for(let s=0;s<c;s++){const n=e+2*s;a.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}const l=[],u=t._physics_getSensorExitCount();if(u>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<u;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(re,{collisionEnters:n,collisionExits:r,sensorEnters:a,sensorExits:l})}(e,n,o)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(oe,de._fromModule(n)),ie(e,oe,re),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}const ue=16;function ye(e,t,s){if(!s)return t;for(let t=0;t<ue;t++)if(e===1<<t)return s[t];return t}function he(e,t,s,n){const i=e.world;if(i.has(s,o)){const e=i.get(s,o),r=e.categoryBits??1,a=ye(r,e.maskBits??65535,n);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,r,a)}if(i.has(s,a)){const e=i.get(s,a),r=e.categoryBits??1,o=ye(r,e.maskBits??65535,n);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,r,o)}if(i.has(s,c)){const e=i.get(s,c),r=e.categoryBits??1,o=ye(r,e.maskBits??65535,n);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0,r,o)}}class de{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(de.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)}static setDebugDraw(e,t){const s=e.getResource(W);s&&(s.enabled=t,e.insertResource(W,s))}static setDebugDrawConfig(e,t){const s=e.getResource(W);s&&e.insertResource(W,{...s,...t})}}export{C as D,le as P,V as a,k as b,H as c,de as d,re as e,L as f,R as g,I as h,x as i,z as j,oe as k,O as l,W as m,ne as n,G as o,ie as p,v as r,E as s,T as u};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/shared/index.js.map b/desktop/public/sdk/esm/shared/index.js.map
index 25132ca04..570e4d656 100644
--- a/desktop/public/sdk/esm/shared/index.js.map
+++ b/desktop/public/sdk/esm/shared/index.js.map
@@ -1 +1 @@
-{"version":3,"file":"index.js","sources":["../../src/draw.ts","../../src/customDraw.ts","../../src/env.ts","../../src/physics/PhysicsModuleLoader.ts","../../src/physics/PhysicsDebugDraw.ts","../../src/physics/PhysicsPlugin.ts"],"sourcesContent":[null,null,null,null,null,null],"names":["module","viewProjectionPtr","transformPtr","uniformsPtr","uniformBuffer","Float32Array","initDrawAPI","wasmModule","_malloc","UNIFORMS_BUFFER_SIZE","shutdownDrawAPI","_free","getModule","Error","WHITE","r","g","b","a","Draw","begin","viewProjection","m","HEAPF32","set","draw_begin","e","handleWasmError","end","draw_end","line","from","to","color","thickness","draw_line","x","y","rect","position","size","filled","draw_rect","rectOutline","draw_rectOutline","circle","center","radius","segments","draw_circle","circleOutline","draw_circleOutline","texture","textureHandle","tint","draw_texture","textureRotated","rotation","draw_textureRotated","setLayer","layer","draw_setLayer","setDepth","depth","draw_setDepth","getDrawCallCount","draw_getDrawCallCount","getPrimitiveCount","draw_getPrimitiveCount","setBlendMode","mode","draw_setBlendMode","setDepthTest","enabled","draw_setDepthTest","drawMesh","geometry","shader","transform","draw_mesh","drawMeshWithMaterial","material","matData","Material","get","blendMode","depthTest","uniforms","idx","dirty_","cachedBuffer_","cachedIdx_","autoTextureSlot","name","value","nameId","getUniformNameId","isTextureRef","slot","textureId","Array","isArray","length","i","z","w","console","warn","subarray","draw_meshWithUniforms","UNIFORM_NAME_MAP","u_time","u_color","u_intensity","u_scale","u_offset","u_param0","u_param1","u_param2","u_param3","u_param4","u_vec0","u_vec1","u_vec2","u_vec3","u_texture0","u_texture1","u_texture2","u_texture3","warnedUniforms","Set","id","undefined","has","add","Object","keys","join","callbacks","Map","registerDrawCallback","fn","scene","unregisterDrawCallback","delete","clearDrawCallbacks","clear","getDrawCallbacks","editorMode","playMode","setEditorMode","active","isEditor","isRuntime","setPlayMode","isPlayMode","async","loadPhysicsModule","wasmUrl","factory","loadPhysicsSideModule","wasmBinary","mainModule","loadDynamicLibrary","Uint8Array","loadAsync","allowUndefined","cwrap","bind","_physics_init","_physics_shutdown","_physics_createBody","_physics_destroyBody","_physics_hasBody","_physics_addBoxShape","_physics_addCircleShape","_physics_addCapsuleShape","_physics_step","_physics_setBodyTransform","_physics_getDynamicBodyCount","_physics_getDynamicBodyTransforms","_physics_collectEvents","_physics_getCollisionEnterCount","_physics_getCollisionEnterBuffer","_physics_getCollisionExitCount","_physics_getCollisionExitBuffer","_physics_getSensorEnterCount","_physics_getSensorEnterBuffer","_physics_getSensorExitCount","_physics_getSensorExitBuffer","_physics_applyForce","_physics_applyImpulse","_physics_setLinearVelocity","_physics_getLinearVelocity","_physics_setGravity","_physics_getGravity","_physics_setAngularVelocity","_physics_getAngularVelocity","_physics_applyTorque","_physics_applyAngularImpulse","_physics_updateBodyProperties","HEAPU8","HEAPU32","PhysicsDebugDraw","defineResource","showColliders","showVelocity","showContacts","STATIC_COLOR","DYNAMIC_COLOR","KINEMATIC_COLOR","SENSOR_COLOR","VELOCITY_COLOR","CONTACT_COLOR","DEBUG_LINE_THICKNESS","CAPSULE_ARC_SEGMENTS","quatToAngleZ","q","Math","atan2","bodyTypeColor","bodyType","BodyType","Static","Kinematic","Dynamic","drawRotatedBox","cx","cy","halfW","halfH","angle","cos","sin","pts","map","c","drawCapsule","halfHeight","toWorld","lx","ly","topLeft","topRight","bottomLeft","bottomRight","a0","PI","a1","p0","p1","drawVelocityArrow","vx","vy","endX","endY","len","sqrt","ARROWHEAD_ANGLE","dirX","dirY","leftX","leftY","rightX","rightY","drawPhysicsDebug","app","physicsApiRes","physicsEventsRes","config","getResource","ppu","entities","world","getEntitiesWithComponents","Canvas","entity","canvas","pixelsPerUnit","readPixelsPerUnit","RigidBody","Transform","physics","hasResource","rb","wt","wx","worldPosition","wy","worldRotation","BoxCollider","box","baseColor","isSensor","offsetX","offset","offsetY","cosA","sinA","halfExtents","CircleCollider","CapsuleCollider","capsule","vel","getLinearVelocity","events","collision","collisionEnters","contactX","contactY","setupPhysicsDebugDraw","insertResource","PhysicsEvents","collisionExits","sensorEnters","sensorExits","PhysicsAPI","angleZToQuat","half","PhysicsPlugin","constructor","this","wasmUrl_","factory_","config_","gravity","fixedTimestep","subStepCount","collisionLayerMasks","build","trackedEntities","cachedProps","initPromise","then","invPpu","onDespawn","addSystemToSchedule","Schedule","PostUpdate","defineSystem","Res","Time","time","currentEntities","prev","gravityScale","linearDamping","angularDamping","fixedRotation","bullet","addShapeForEntity","delta","count","ptr","baseU32","entityId","worldX","worldY","worldAngle","valid","localX","localY","localAngle","Parent","parentData","pwt","parentAngle","dx","dy","worldScale","insert","syncDynamicTransforms","enterCount","enterPtr","base","push","entityA","entityB","normalX","normalY","exitCount","exitPtr","sensorEnterCount","sensorEnterPtr","sensorEntity","visitorEntity","sensorExitCount","sensorExitPtr","collectEvents","physicsModule","Physics","_fromModule","setFixedTimestep","catch","error","physicsInitPromise","MAX_COLLISION_LAYERS","resolveCollisionMask","categoryBits","maskBits","layerMasks","category","mask","density","friction","restitution","module_","instance","create","prototype","applyForce","force","applyImpulse","impulse","setLinearVelocity","velocity","setGravity","getGravity","setAngularVelocity","omega","getAngularVelocity","applyTorque","torque","applyAngularImpulse","setDebugDraw","setDebugDrawConfig","current"],"mappings":"4IAqBA,IAAIA,EAAgC,KAChCC,EAA4B,EAC5BC,EAAuB,EACvBC,EAAsB,EAE1B,MACMC,EAAgB,IAAIC,aADG,KAOvB,SAAUC,EAAYC,GACxBP,EAASO,EACTN,EAAoBD,EAAOQ,QAAQ,IACnCN,EAAeF,EAAOQ,QAAQ,IAC9BL,EAAcH,EAAOQ,QAAQC,KACjC,UAEgBC,IACRV,IACIC,IACAD,EAAOW,MAAMV,GACbA,EAAoB,GAEpBC,IACAF,EAAOW,MAAMT,GACbA,EAAe,GAEfC,IACAH,EAAOW,MAAMR,GACbA,EAAc,IAGtBH,EAAS,IACb,CA4IA,SAASY,IACL,IAAKZ,EACD,MAAM,IAAIa,MAAM,uDAEpB,OAAOb,CACX,CAEA,MAAMc,EAAe,CAAEC,EAAG,EAAGC,EAAG,EAAGC,EAAG,EAAGC,EAAG,GAE/BC,EAAgB,CACzB,KAAAC,CAAMC,GACF,MAAMC,EAAIV,IACV,IACIU,EAAEC,QAAQC,IAAIH,EAAgBpB,EAAoB,GAClDqB,EAAEG,WAAWxB,EACjB,CAAE,MAAOyB,GACLC,EAAgBD,EAAG,aACvB,CACJ,EAEA,GAAAE,GACI,IACIhB,IAAYiB,UAChB,CAAE,MAAOH,GACLC,EAAgBD,EAAG,WACvB,CACJ,EAEA,IAAAI,CAAKC,EAAYC,EAAUC,EAAcC,EAAY,GACjD,IACItB,IAAYuB,UACRJ,EAAKK,EAAGL,EAAKM,EACbL,EAAGI,EAAGJ,EAAGK,EACTJ,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCgB,EAER,CAAE,MAAOR,GACLC,EAAgBD,EAAG,YACvB,CACJ,EAEA,IAAAY,CAAKC,EAAgBC,EAAYP,EAAcQ,GAAS,GACpD,IACI7B,IAAY8B,UACRH,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACbJ,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCuB,EAER,CAAE,MAAOf,GACLC,EAAgBD,EAAG,YACvB,CACJ,EAEA,WAAAiB,CAAYJ,EAAgBC,EAAYP,EAAcC,EAAY,GAC9D,IACItB,IAAYgC,iBACRL,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACbJ,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCgB,EAER,CAAE,MAAOR,GACLC,EAAgBD,EAAG,mBACvB,CACJ,EAEA,MAAAmB,CAAOC,EAAcC,EAAgBd,EAAcQ,GAAS,EAAMO,EAAW,IACzE,IACIpC,IAAYqC,YACRH,EAAOV,EAAGU,EAAOT,EACjBU,EACAd,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCuB,EACAO,EAER,CAAE,MAAOtB,GACLC,EAAgBD,EAAG,cACvB,CACJ,EAEA,aAAAwB,CAAcJ,EAAcC,EAAgBd,EAAcC,EAAY,EAAGc,EAAW,IAChF,IACIpC,IAAYuC,mBACRL,EAAOV,EAAGU,EAAOT,EACjBU,EACAd,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCgB,EACAc,EAER,CAAE,MAAOtB,GACLC,EAAgBD,EAAG,qBACvB,CACJ,EAEA,OAAA0B,CAAQb,EAAgBC,EAAYa,EAAuBC,EAAcxC,GACrE,IACIF,IAAY2C,aACRhB,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACbgB,EACAC,EAAKvC,EAAGuC,EAAKtC,EAAGsC,EAAKrC,EAAGqC,EAAKpC,EAErC,CAAE,MAAOQ,GACLC,EAAgBD,EAAG,eACvB,CACJ,EAEA,cAAA8B,CAAejB,EAAgBC,EAAYiB,EAAkBJ,EAAuBC,EAAcxC,GAC9F,IACIF,IAAY8C,oBACRnB,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACboB,EACAJ,EACAC,EAAKvC,EAAGuC,EAAKtC,EAAGsC,EAAKrC,EAAGqC,EAAKpC,EAErC,CAAE,MAAOQ,GACLC,EAAgBD,EAAG,sBACvB,CACJ,EAEA,QAAAiC,CAASC,GACLhD,IAAYiD,cAAcD,EAC9B,EAEA,QAAAE,CAASC,GACLnD,IAAYoD,cAAcD,EAC9B,EAEAE,iBAAgB,IACPjE,EACEA,EAAOkE,wBADM,EAIxBC,kBAAiB,IACRnE,EACEA,EAAOoE,yBADM,EAIxB,YAAAC,CAAaC,GACT1D,IAAY2D,kBAAkBD,EAClC,EAEA,YAAAE,CAAaC,GACT7D,IAAY8D,kBAAkBD,EAClC,EAEA,QAAAE,CAASC,EAA0BC,EAAsBC,GACrD,IACI,MAAMxD,EAAIV,IACVU,EAAEC,QAAQC,IAAIsD,EAAW5E,EAAe,GACxCoB,EAAEyD,UAAUH,EAAUC,EAAQ3E,EAClC,CAAE,MAAOwB,GACLC,EAAgBD,EAAG,0BAA0BkD,aAAoBC,KACrE,CACJ,EAEA,oBAAAG,CAAqBJ,EAA0BK,EAA0BH,GACrE,IACI,MAAMxD,EAAIV,IACJsE,EAAUC,EAASC,IAAIH,GAC7B,IAAKC,EAAS,OAKd,GAHA/D,EAAKkD,aAAaa,EAAQG,WAC1BlE,EAAKqD,aAAaU,EAAQI,WAEI,IAA1BJ,EAAQK,SAAS/C,KAEjB,YADArB,EAAKwD,SAASC,EAAUM,EAAQL,OAAQC,GAM5C,IAAIU,EACJ,GAHAlE,EAAEC,QAAQC,IAAIsD,EAAW5E,EAAe,IAGnCgF,EAAQO,QAAUP,EAAQQ,cAC3BF,EAAMN,EAAQS,eACX,CACHH,EAAM,EACN,IAAII,EAAkB,EACtB,IAAK,MAAOC,EAAMC,KAAUZ,EAAQK,SAAU,CAC1C,MAAMQ,EAASC,EAAiBH,GAChC,KAAIE,EAAS,GAAb,CAEA,GAAIE,EAAaH,GACb1F,EAAcoF,KAAS,GACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAMI,MAAQN,IACrCxF,EAAcoF,KAASM,EAAMK,eAC1B,GAAqB,iBAAVL,EACd1F,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,OACpB,GAAIM,MAAMC,QAAQP,GAAQ,CAC7B1F,EAAcoF,KAASM,EAAMQ,OAC7BlG,EAAcoF,KAASO,EACvB,IAAK,IAAIQ,EAAI,EAAGA,EAAIT,EAAMQ,OAAQC,IAC9BnG,EAAcoF,KAASM,EAAMS,EAErC,KAAW,MAAOT,GACd1F,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAM1D,EAC7BhC,EAAcoF,KAASM,EAAMzD,EAC7BjC,EAAcoF,KAASM,EAAMU,EAC7BpG,EAAcoF,KAASM,EAAMW,GACtB,MAAOX,GACd1F,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAM1D,EAC7BhC,EAAcoF,KAASM,EAAMzD,EAC7BjC,EAAcoF,KAASM,EAAMU,IAE7BpG,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAM1D,EAC7BhC,EAAcoF,KAASM,EAAMzD,GAGjC,GAAImD,EAAM/E,IAA0B,CAChCiG,QAAQC,KAAK,0DACb,KACJ,CAxCgB,CAyCpB,GAEKzB,EAAQQ,eAAiBR,EAAQQ,cAAcY,OAASd,KACzDN,EAAQQ,cAAgB,IAAIrF,aAAamF,IAE7CN,EAAQQ,cAAclE,IAAIpB,EAAcwG,SAAS,EAAGpB,IACpDN,EAAQS,WAAaH,EACrBN,EAAQO,QAAS,CACrB,CAEA,GAAY,IAARD,EAEA,YADAlE,EAAEyD,UAAUH,EAAUM,EAAQL,OAAQ3E,GAI1CoB,EAAEC,QAAQC,IAAI0D,EAAQQ,cAAekB,SAAS,EAAGpB,GAAMrF,EAAc,GACrEmB,EAAEuF,sBAAsBjC,EAAUM,EAAQL,OAAQ3E,EAAcC,EAAaqF,EACjF,CAAE,MAAO9D,GACLC,EAAgBD,EAAG,sCAAsCkD,eAAsBK,KACnF,CACJ,GAGE6B,EAA2C,CAC7CC,OAAU,EACVC,QAAW,EACXC,YAAe,EACfC,QAAW,EACXC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,OAAU,GACVC,OAAU,GACVC,OAAU,GACVC,OAAU,GACVC,WAAc,GACdC,WAAc,GACdC,WAAc,GACdC,WAAc,IAGZC,EAAiB,IAAIC,IAE3B,SAASlC,EAAiBH,GACtB,MAAMsC,EAAKrB,EAAiBjB,GAC5B,YAAWuC,IAAPD,EAAyBA,GACxBF,EAAeI,IAAIxC,KACpBoC,EAAeK,IAAIzC,GACnBa,QAAQC,KACJ,oCAAoCd,yBAChB0C,OAAOC,KAAK1B,GAAkB2B,KAAK,WAGxD,EACX,CCrdA,MAAMC,EAAY,IAAIC,aAENC,EAAqBT,EAAYU,EAAkBC,GAC/DJ,EAAUlH,IAAI2G,EAAI,CAAEU,KAAIC,MAAOA,GAAS,IAC5C,CAEM,SAAUC,EAAuBZ,GACnCO,EAAUM,OAAOb,EACrB,UAEgBc,IACZP,EAAUQ,OACd,UAUgBC,IACZ,OAAOT,CACX,CC/BA,IAAIU,GAAa,EACbC,GAAW,EAET,SAAUC,EAAcC,GAC1BH,EAAaG,CACjB,UAEgBC,IACZ,OAAOJ,CACX,UAEgBK,IACZ,OAAQL,CACZ,CAEM,SAAUM,EAAYH,GACxBF,EAAWE,CACf,UAEgBI,IACZ,OAAON,CACX,CCiDOO,eAAeC,EAClBC,EACAC,GAEA,IAAKA,EACD,MAAM,IAAIlJ,MACN,8IAIR,OAAOkJ,GACX,CAYOH,eAAeI,EAClBC,EACAC,SAEMA,EAAWC,mBACb,IAAIC,WAAWH,GACf,CAAEI,WAAW,EAAMC,gBAAgB,IAGvC,MAAMC,EAAQL,EAAWK,MAAMC,KAAKN,GAEpC,MAAO,CACHO,cAAeF,EAAM,eAAgB,KAAM,CAAC,SAAU,SAAU,SAAU,WAC1EG,kBAAmBH,EAAM,mBAAoB,KAAM,IAEnDI,oBAAqBJ,EAAM,qBAAsB,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAClJK,qBAAsBL,EAAM,sBAAuB,KAAM,CAAC,WAC1DM,iBAAkBN,EAAM,kBAAmB,SAAU,CAAC,WAEtDO,qBAAsBP,EAAM,sBAAuB,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAC9JQ,wBAAyBR,EAAM,yBAA0B,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAC1JS,yBAA0BT,EAAM,0BAA2B,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAEtKU,cAAeV,EAAM,eAAgB,KAAM,CAAC,WAE5CW,0BAA2BX,EAAM,2BAA4B,KAAM,CAAC,SAAU,SAAU,SAAU,WAClGY,6BAA8BZ,EAAM,8BAA+B,SAAU,IAC7Ea,kCAAmCb,EAAM,mCAAoC,SAAU,IAEvFc,uBAAwBd,EAAM,wBAAyB,KAAM,IAC7De,gCAAiCf,EAAM,iCAAkC,SAAU,IACnFgB,iCAAkChB,EAAM,kCAAmC,SAAU,IACrFiB,+BAAgCjB,EAAM,gCAAiC,SAAU,IACjFkB,gCAAiClB,EAAM,iCAAkC,SAAU,IACnFmB,6BAA8BnB,EAAM,8BAA+B,SAAU,IAC7EoB,8BAA+BpB,EAAM,+BAAgC,SAAU,IAC/EqB,4BAA6BrB,EAAM,6BAA8B,SAAU,IAC3EsB,6BAA8BtB,EAAM,8BAA+B,SAAU,IAE7EuB,oBAAqBvB,EAAM,qBAAsB,KAAM,CAAC,SAAU,SAAU,WAC5EwB,sBAAuBxB,EAAM,uBAAwB,KAAM,CAAC,SAAU,SAAU,WAChFyB,2BAA4BzB,EAAM,4BAA6B,KAAM,CAAC,SAAU,SAAU,WAC1F0B,2BAA4B1B,EAAM,4BAA6B,SAAU,CAAC,WAE1E2B,oBAAqB3B,EAAM,qBAAsB,KAAM,CAAC,SAAU,WAClE4B,oBAAqB5B,EAAM,qBAAsB,SAAU,IAE3D6B,4BAA6B7B,EAAM,6BAA8B,KAAM,CAAC,SAAU,WAClF8B,4BAA6B9B,EAAM,6BAA8B,SAAU,CAAC,WAC5E+B,qBAAsB/B,EAAM,sBAAuB,KAAM,CAAC,SAAU,WACpEgC,6BAA8BhC,EAAM,8BAA+B,KAAM,CAAC,SAAU,WAEpFiC,8BAA+BjC,EAAM,+BAAgC,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAExI,WAAIhJ,GAAY,OAAO2I,EAAW3I,OAAS,EAC3C,UAAIkL,GAAW,OAAOvC,EAAWuC,MAAQ,EACzC,WAAIC,GAAY,OAAOxC,EAAWwC,OAAS,EAC3ClM,QAAS0J,EAAW1J,QAAQgK,KAAKN,GACjCvJ,MAAOuJ,EAAWvJ,MAAM6J,KAAKN,GAErC,CCrIO,MAAMyC,EAAmBC,EAAuC,CACnEnI,SAAS,EACToI,eAAe,EACfC,cAAc,EACdC,cAAc,GACf,oBAMGC,EAAsB,CAAEjM,EAAG,GAAKC,EAAG,GAAKC,EAAG,EAAKC,EAAG,IACnD+L,EAAuB,CAAElM,EAAG,GAAKC,EAAG,EAAKC,EAAG,GAAKC,EAAG,IACpDgM,EAAyB,CAAEnM,EAAG,GAAKC,EAAG,EAAKC,EAAG,EAAKC,EAAG,IACtDiM,EAAsB,CAAEpM,EAAG,EAAKC,EAAG,EAAKC,EAAG,GAAKC,EAAG,IACnDkM,EAAwB,CAAErM,EAAG,EAAKC,EAAG,GAAKC,EAAG,GAAKC,EAAG,IACrDmM,EAAuB,CAAEtM,EAAG,EAAKC,EAAG,GAAKC,EAAG,GAAKC,EAAG,GACpDoM,EAAuB,IAIvBC,EAAuB,GAE7B,SAASC,EAAaC,GAClB,OAAOC,KAAKC,MAAM,GAAKF,EAAEhH,EAAIgH,EAAEjH,EAAIiH,EAAErL,EAAIqL,EAAEpL,GAAI,EAAI,GAAKoL,EAAEpL,EAAIoL,EAAEpL,EAAIoL,EAAEjH,EAAIiH,EAAEjH,GAChF,CAEA,SAASoH,EAAcC,GACnB,OAAQA,GACJ,KAAKC,EAASC,OAAQ,OAAOf,EAC7B,KAAKc,EAASE,UAAW,OAAOd,EAChC,KAAKY,EAASG,QACd,QAAS,OAAOhB,EAExB,CAaA,SAASiB,GACLC,EAAYC,EACZC,EAAeC,EACfC,EAAetM,GAEf,MAAMuM,EAAMd,KAAKc,IAAID,GACfE,EAAMf,KAAKe,IAAIF,GAOfG,EANU,CACZ,CAAEtM,GAAIiM,EAAOhM,GAAIiM,GACjB,CAAElM,EAAIiM,EAAOhM,GAAIiM,GACjB,CAAElM,EAAIiM,EAAOhM,EAAIiM,GACjB,CAAElM,GAAIiM,EAAOhM,EAAIiM,IAEDK,IAAIC,IAAC,CACrBxM,EAAG+L,EAAKS,EAAExM,EAAIoM,EAAMI,EAAEvM,EAAIoM,EAC1BpM,EAAG+L,EAAKQ,EAAExM,EAAIqM,EAAMG,EAAEvM,EAAImM,KAE9B,IAAK,IAAIjI,EAAI,EAAGA,EAAI,EAAGA,IACnBpF,EAAKW,KAAK4M,EAAInI,GAAImI,GAAKnI,EAAI,GAAK,GAAItE,EAAOqL,EAEnD,CAEA,SAASuB,GACLV,EAAYC,EACZrL,EAAgB+L,EAChBP,EAAetM,GAEf,MAAMuM,EAAMd,KAAKc,IAAID,GACfE,EAAMf,KAAKe,IAAIF,GAEfQ,EAAU,CAACC,EAAYC,KAAU,CACnC7M,EAAG+L,EAAKa,EAAKR,EAAMS,EAAKR,EACxBpM,EAAG+L,EAAKY,EAAKP,EAAMQ,EAAKT,IAGtBU,EAAUH,GAAShM,EAAQ+L,GAC3BK,EAAWJ,EAAQhM,EAAQ+L,GAC3BM,EAAaL,GAAShM,GAAS+L,GAC/BO,EAAcN,EAAQhM,GAAS+L,GAErC3N,EAAKW,KAAKoN,EAASE,EAAYnN,EAAOqL,GACtCnM,EAAKW,KAAKqN,EAAUE,EAAapN,EAAOqL,GAExC,IAAK,IAAI/G,EAAI,EAAGA,EAAIgH,EAAsBhH,IAAK,CAC3C,MAAM+I,EAAM/I,EAAIgH,EAAwBG,KAAK6B,GACvCC,GAAOjJ,EAAI,GAAKgH,EAAwBG,KAAK6B,GAC7CE,EAAKV,GACNhM,EAAS2K,KAAKc,IAAIc,GACnBR,EAAa/L,EAAS2K,KAAKe,IAAIa,IAE7BI,EAAKX,GACNhM,EAAS2K,KAAKc,IAAIgB,GACnBV,EAAa/L,EAAS2K,KAAKe,IAAIe,IAEnCrO,EAAKW,KAAK2N,EAAIC,EAAIzN,EAAOqL,EAC7B,CAEA,IAAK,IAAI/G,EAAI,EAAGA,EAAIgH,EAAsBhH,IAAK,CAC3C,MAAM+I,EAAK5B,KAAK6B,GAAMhJ,EAAIgH,EAAwBG,KAAK6B,GACjDC,EAAK9B,KAAK6B,IAAOhJ,EAAI,GAAKgH,EAAwBG,KAAK6B,GACvDE,EAAKV,GACNhM,EAAS2K,KAAKc,IAAIc,IAClBR,EAAa/L,EAAS2K,KAAKe,IAAIa,IAE9BI,EAAKX,GACNhM,EAAS2K,KAAKc,IAAIgB,IAClBV,EAAa/L,EAAS2K,KAAKe,IAAIe,IAEpCrO,EAAKW,KAAK2N,EAAIC,EAAIzN,EAAOqL,EAC7B,CACJ,CAEA,SAASqC,GACLvN,EAAWC,EACXuN,EAAYC,GAEZ,MAAMC,EAAO1N,EAxGM,GAwGFwN,EACXG,EAAO1N,EAzGM,GAyGFwN,EACjB1O,EAAKW,KAAK,CAAEM,IAAGC,KAAK,CAAED,EAAG0N,EAAMzN,EAAG0N,GAAQ3C,EAAgBE,GAE1D,MAAM0C,EAAMtC,KAAKuC,KAAKL,EAAKA,EAAKC,EAAKA,GACrC,GAAIG,EAAM,EAAG,OAEb,MACME,EAAkBxC,KAAK6B,GAAK,EAC5BY,EAAOP,EAAKI,EACZI,EAAOP,EAAKG,EAEZK,EAAQP,EALW,GAKgBK,EAAOzC,KAAKc,IAAI0B,GAAmBE,EAAO1C,KAAKe,IAAIyB,IACtFI,EAAQP,EANW,GAMgBI,EAAOzC,KAAKe,IAAIyB,GAAmBE,EAAO1C,KAAKc,IAAI0B,IACtFK,EAAST,EAPU,GAOiBK,EAAOzC,KAAKc,IAAI0B,GAAmBE,EAAO1C,KAAKe,IAAIyB,IACvFM,EAAST,EARU,IAQkBI,EAAOzC,KAAKe,IAAIyB,GAAmBE,EAAO1C,KAAKc,IAAI0B,IAE9F/O,EAAKW,KAAK,CAAEM,EAAG0N,EAAMzN,EAAG0N,GAAQ,CAAE3N,EAAGiO,EAAOhO,EAAGiO,GAASlD,EAAgBE,GACxEnM,EAAKW,KAAK,CAAEM,EAAG0N,EAAMzN,EAAG0N,GAAQ,CAAE3N,EAAGmO,EAAQlO,EAAGmO,GAAUpD,EAAgBE,EAC9E,UAEgBmD,GACZC,EACAC,EACAC,GAEA,GAAIpH,MAAeG,IAAc,OAEjC,MAAMkH,EAASH,EAAII,YAAoCnE,GACvD,IAAKkE,IAAWA,EAAOpM,QAAS,OAEhC,MAAMsM,EAtHV,SAA2BL,GACvB,MAAMM,EAAWN,EAAIO,MAAMC,0BAA0B,CAACC,IACtD,IAAK,MAAMC,KAAUJ,EAAU,CAC3B,MAAMK,EAASX,EAAIO,MAAM7L,IAAIgM,EAAQD,GACrC,GAAIE,GAAUA,EAAOC,cACjB,OAAOD,EAAOC,aAEtB,CACA,OAAO,GACX,CA6GgBC,CAAkBb,GACxBM,EAAWN,EAAIO,MAAMC,0BAA0B,CAACM,EAAWC,IAEjE,IAAIC,EAAmC,KACnCb,EAAO/D,cAAgB4D,EAAIiB,YAAYhB,KACvCe,EAAUhB,EAAII,YAA8BH,IAGhD,IAAK,MAAMS,KAAUJ,EAAU,CAC3B,MAAMY,EAAKlB,EAAIO,MAAM7L,IAAIgM,EAAQI,GACjC,IAAKI,EAAGnN,QAAS,SAEjB,MAAMoN,EAAKnB,EAAIO,MAAM7L,IAAIgM,EAAQK,GAC3BK,EAAKD,EAAGE,cAAc3P,EACtB4P,EAAKH,EAAGE,cAAc1P,EACtBkM,EAAQf,EAAaqE,EAAGI,eAE9B,GAAIpB,EAAOhE,cAAe,CACtB,GAAI6D,EAAIO,MAAM5I,IAAI+I,EAAQc,GAAc,CACpC,MAAMC,EAAMzB,EAAIO,MAAM7L,IAAIgM,EAAQc,GAC5BE,EAAYD,EAAIE,SAAWlF,EAAeS,EAAcgE,EAAG/D,UAC3DyE,EAAUH,EAAII,OAAOnQ,EAAI2O,EACzByB,EAAUL,EAAII,OAAOlQ,EAAI0O,EACzB0B,EAAO/E,KAAKc,IAAID,GAChBmE,EAAOhF,KAAKe,IAAIF,GAGtBL,GAFW4D,EAAKQ,EAAUG,EAAOD,EAAUE,EAChCV,EAAKM,EAAUI,EAAOF,EAAUC,EACpBN,EAAIQ,YAAYvQ,EAAI2O,EAAKoB,EAAIQ,YAAYtQ,EAAI0O,EAAKxC,EAAO6D,EACpF,CAEA,GAAI1B,EAAIO,MAAM5I,IAAI+I,EAAQwB,GAAiB,CACvC,MAAM/P,EAAS6N,EAAIO,MAAM7L,IAAIgM,EAAQwB,GAC/BR,EAAYvP,EAAOwP,SAAWlF,EAAeS,EAAcgE,EAAG/D,UAC9DyE,EAAUzP,EAAO0P,OAAOnQ,EAAI2O,EAC5ByB,EAAU3P,EAAO0P,OAAOlQ,EAAI0O,EAC5B0B,EAAO/E,KAAKc,IAAID,GAChBmE,EAAOhF,KAAKe,IAAIF,GAChBJ,EAAK2D,EAAKQ,EAAUG,EAAOD,EAAUE,EACrCtE,EAAK4D,EAAKM,EAAUI,EAAOF,EAAUC,EAC3CtR,EAAK+B,cACD,CAAEd,EAAG+L,EAAI9L,EAAG+L,GACZvL,EAAOE,OAASgO,EAChBqB,EACA9E,EAjLI,GAoLZ,CAEA,GAAIoD,EAAIO,MAAM5I,IAAI+I,EAAQyB,GAAkB,CACxC,MAAMC,EAAUpC,EAAIO,MAAM7L,IAAIgM,EAAQyB,GAChCT,EAAYU,EAAQT,SAAWlF,EAAeS,EAAcgE,EAAG/D,UAC/DyE,EAAUQ,EAAQP,OAAOnQ,EAAI2O,EAC7ByB,EAAUM,EAAQP,OAAOlQ,EAAI0O,EAC7B0B,EAAO/E,KAAKc,IAAID,GAChBmE,EAAOhF,KAAKe,IAAIF,GAGtBM,GAFWiD,EAAKQ,EAAUG,EAAOD,EAAUE,EAChCV,EAAKM,EAAUI,EAAOF,EAAUC,EACvBK,EAAQ/P,OAASgO,EAAK+B,EAAQhE,WAAaiC,EAAKxC,EAAO6D,EAC/E,CACJ,CAEA,GAAIvB,EAAO/D,cAAgB4E,GAAWE,EAAG/D,WAAaC,EAASG,QAAS,CACpE,MAAM8E,EAAMrB,EAAQsB,kBAAkB5B,GACtCzB,GAAkBmC,EAAIE,EAAIe,EAAI3Q,EAAI2O,EAAKgC,EAAI1Q,EAAI0O,EACnD,CACJ,CAEA,GAAIF,EAAO9D,cAAgB2D,EAAIiB,YAAYf,GAAmB,CAC1D,MAAMqC,EAASvC,EAAII,YAA+BF,GAClD,IAAK,MAAMsC,KAAaD,EAAOE,gBAC3BhS,EAAK0B,OACD,CAAET,EAAG8Q,EAAUE,SAAU/Q,EAAG6Q,EAAUG,UA/MzB,EAiNbhG,GACA,EAhNQ,GAoNpB,CACJ,UAEgBiG,GACZ5C,EACAC,EACAC,GAEAF,EAAI6C,eAAe5G,EAAkB,CACjClI,SAAS,EACToI,eAAe,EACfC,cAAc,EACdC,cAAc,IAGlBnE,EAAqB,qBAAsB,KACvC6H,GAAiBC,EAAKC,EAAeC,IAE7C,CCtNO,MAAM4C,GAAgB5G,EAAkC,CAC3DuG,gBAAiB,GACjBM,eAAgB,GAChBC,aAAc,GACdC,YAAa,IACd,iBAEUC,GAAahH,EAAwB,KAAO,cAMzD,SAASY,GAAaC,GAClB,OAAOC,KAAKC,MAAM,GAAKF,EAAEhH,EAAIgH,EAAEjH,EAAIiH,EAAErL,EAAIqL,EAAEpL,GAAI,EAAI,GAAKoL,EAAEpL,EAAIoL,EAAEpL,EAAIoL,EAAEjH,EAAIiH,EAAEjH,GAChF,CAEA,SAASqN,GAAatF,GAClB,MAAMuF,EAAe,GAARvF,EACb,MAAO,CAAE9H,EAAGiH,KAAKc,IAAIsF,GAAO1R,EAAG,EAAGC,EAAG,EAAGmE,EAAGkH,KAAKe,IAAIqF,GACxD,OAiBaC,GAKT,WAAAC,CAAYlK,EAAiB+G,EAA8B,CAAA,EAAI9G,GAC3DkK,KAAKC,SAAWpK,EAChBmK,KAAKE,SAAWpK,EAChBkK,KAAKG,QAAU,CACXC,QAASxD,EAAOwD,SAAW,CAAEjS,EAAG,EAAGC,SACnCiS,cAAezD,EAAOyD,eAAiB,EAAI,GAC3CC,aAAc1D,EAAO0D,cAAgB,EACrCC,oBAAqB3D,EAAO2D,oBAEpC,CAEA,KAAAC,CAAM/D,GACFA,EAAI6C,eAAeC,GAAe,CAC9BL,gBAAiB,GACjBM,eAAgB,GAChBC,aAAc,GACdC,YAAa,KAGjB,MAAMe,EAAkB,IAAIxM,IACtByM,EAAc,IAAIhM,IAElBiM,EAAc/K,EAAkBoK,KAAKC,SAAUD,KAAKE,UAAUU,KAC/D7U,IACGA,EAAOyK,cACHwJ,KAAKG,QAAQC,QAAQjS,EACrB6R,KAAKG,QAAQC,QAAQhS,EACrB4R,KAAKG,QAAQE,cACbL,KAAKG,QAAQG,cAGjB,MAAMxD,EA/CtB,SAA2BL,GACvB,MAAMM,EAAWN,EAAIO,MAAMC,0BAA0B,CAACC,IACtD,IAAK,MAAMC,KAAUJ,EAAU,CAC3B,MAAMK,EAASX,EAAIO,MAAM7L,IAAIgM,EAAQD,GACrC,GAAIE,GAAUA,EAAOC,cACjB,OAAOD,EAAOC,aAEtB,CACA,OAAO,GACX,CAsC4BC,CAAkBb,GACxBoE,EAAS,EAAI/D,EAEbE,EAAQP,EAAIO,MAElBA,EAAM8D,UAAW3D,IACTsD,EAAgBrM,IAAI+I,KACpBpR,EAAO4K,qBAAqBwG,GAC5BsD,EAAgB1L,OAAOoI,GACvBuD,EAAY3L,OAAOoI,MAI3BV,EAAIsE,oBACAC,EAASC,WACTC,EACI,CAACC,EAAIC,IACJC,IACG,GAAI9L,MAAeG,IAAc,OAEjC,MAAMqH,EAAWC,EAAMC,0BAA0B,CAACM,EAAWC,IACvD8D,EAAkB,IAAIrN,IAE5B,IAAK,MAAMkJ,KAAUJ,EAAU,CAC3BuE,EAAgBjN,IAAI8I,GACpB,MAAMQ,EAAKX,EAAM7L,IAAIgM,EAAQI,GACvBK,EAAKZ,EAAM7L,IAAIgM,EAAQK,GAE7B,GAAKiD,EAAgBrM,IAAI+I,GAsBlB,CACH,MAAMoE,EAAOb,EAAYvP,IAAIgM,IACzBoE,GACCA,EAAK3H,WAAa+D,EAAG/D,UACrB2H,EAAKC,eAAiB7D,EAAG6D,cACzBD,EAAKE,gBAAkB9D,EAAG8D,eAC1BF,EAAKG,iBAAmB/D,EAAG+D,gBAC3BH,EAAKI,gBAAkBhE,EAAGgE,eAC1BJ,EAAKK,SAAWjE,EAAGiE,SACpB7V,EAAOwM,8BACH4E,EAAQQ,EAAG/D,SACX+D,EAAG6D,aAAc7D,EAAG8D,cAAe9D,EAAG+D,eACtC/D,EAAGgE,cAAgB,EAAI,EAAGhE,EAAGiE,OAAS,EAAI,GAE9CL,EAAK3H,SAAW+D,EAAG/D,SACnB2H,EAAKC,aAAe7D,EAAG6D,aACvBD,EAAKE,cAAgB9D,EAAG8D,cACxBF,EAAKG,eAAiB/D,EAAG+D,eACzBH,EAAKI,cAAgBhE,EAAGgE,cACxBJ,EAAKK,OAASjE,EAAGiE,OAEzB,KA3CkC,CAC9B,IAAKjE,EAAGnN,QAAS,SAEjB,MAAM8J,EAAQf,GAAaqE,EAAGI,eAE9BjS,EAAO2K,oBACHyG,EAAQQ,EAAG/D,SACXgE,EAAGE,cAAc3P,EAAI0S,EAAQjD,EAAGE,cAAc1P,EAAIyS,EAAQvG,EAC1DqD,EAAG6D,aAAc7D,EAAG8D,cAAe9D,EAAG+D,eACtC/D,EAAGgE,cAAgB,EAAI,EAAGhE,EAAGiE,OAAS,EAAI,GAG9CC,GAAkBpF,EAAK1Q,EAAQoR,EAAQ6C,KAAKG,QAAQI,qBACpDE,EAAgBpM,IAAI8I,GACpBuD,EAAYnT,IAAI4P,EAAQ,CACpBvD,SAAU+D,EAAG/D,SACb4H,aAAc7D,EAAG6D,aACjBC,cAAe9D,EAAG8D,cAClBC,eAAgB/D,EAAG+D,eACnBC,cAAehE,EAAGgE,cAClBC,OAAQjE,EAAGiE,QAEnB,CAuBA,GAAIjE,EAAG/D,WAAaC,EAASE,UAAW,CACpC,MAAMO,EAAQf,GAAaqE,EAAGI,eAC9BjS,EAAOkL,0BACHkG,EACAS,EAAGE,cAAc3P,EAAI0S,EAAQjD,EAAGE,cAAc1P,EAAIyS,EAClDvG,EAER,CACJ,CAEA,IAAK,MAAM6C,KAAUsD,EACZa,EAAgBlN,IAAI+I,KACrBpR,EAAO4K,qBAAqBwG,GAC5BsD,EAAgB1L,OAAOoI,GACvBuD,EAAY3L,OAAOoI,IAI3BpR,EAAOiL,cAAcqK,EAAKS,OA+EtD,SAA+BrF,EAAU1Q,EAA2B+Q,GAChE,MAAMiF,EAAQhW,EAAOmL,+BACrB,GAAc,IAAV6K,EAAa,OAEjB,MAAMC,EAAMjW,EAAOoL,oCACb8K,EAAUD,GAAO,EAEvB,IAAK,IAAI1P,EAAI,EAAGA,EAAIyP,EAAOzP,IAAK,CAC5B,MAAMgM,EAAS2D,EAAc,EAAJ3P,EACnB4P,EAAWnW,EAAO0M,QAAQ6F,GAC1B6D,EAASpW,EAAOuB,QAAQgR,EAAS,GAAKxB,EACtCsF,EAASrW,EAAOuB,QAAQgR,EAAS,GAAKxB,EACtCuF,EAAatW,EAAOuB,QAAQgR,EAAS,GAE3C,IAAK7B,EAAIO,MAAMsF,MAAMJ,GAAW,SAEhC,MAAMrR,EAAY4L,EAAIO,MAAM7L,IAAI+Q,EAAU1E,GAC1C,IAAK3M,EAAW,SAEhB,IAAI0R,EAASJ,EACTK,EAASJ,EACTK,EAAaJ,EAEjB,GAAI5F,EAAIO,MAAM5I,IAAI8N,EAAUQ,GAAS,CACjC,MAAMC,EAAalG,EAAIO,MAAM7L,IAAI+Q,EAAUQ,GAC3C,GAAIC,GAAclG,EAAIO,MAAMsF,MAAMK,EAAWxF,SAAWV,EAAIO,MAAM5I,IAAIuO,EAAWxF,OAAQK,GAAY,CACjG,MAAMoF,EAAMnG,EAAIO,MAAM7L,IAAIwR,EAAWxF,OAAQK,GACvCqF,EAActJ,GAAaqJ,EAAI5E,eAC/B8E,EAAKX,EAASS,EAAI9E,cAAc3P,EAChC4U,EAAKX,EAASQ,EAAI9E,cAAc1P,EAChCmM,EAAMd,KAAKc,KAAKsI,GAChBrI,EAAMf,KAAKe,KAAKqI,GAGtBN,GAAUO,EAAKvI,EAAMwI,EAAKvI,IAFM,IAArBoI,EAAII,WAAW7U,EAAUyU,EAAII,WAAW7U,EAAI,GAGvDqU,GAAUM,EAAKtI,EAAMuI,EAAKxI,IAFM,IAArBqI,EAAII,WAAW5U,EAAUwU,EAAII,WAAW5U,EAAI,GAGvDqU,EAAaJ,EAAaQ,CAC9B,CACJ,CAEAhS,EAAUvC,SAASH,EAAIoU,EACvB1R,EAAUvC,SAASF,EAAIoU,EACvB,MAAMhJ,EAAIoG,GAAa6C,GACvB5R,EAAUrB,SAASgD,EAAIgH,EAAEhH,EACzB3B,EAAUrB,SAASrB,EAAIqL,EAAErL,EACzB0C,EAAUrB,SAASpB,EAAIoL,EAAEpL,EACzByC,EAAUrB,SAAS+C,EAAIiH,EAAEjH,EAEzBkK,EAAIO,MAAMiG,OAAOf,EAAU1E,EAAW3M,EAC1C,CACJ,CA/H4BqS,CAAsBzG,EAAK1Q,EAAQ+Q,GAiI/D,SAAuBL,EAAU1Q,EAA2B+Q,GACxD/Q,EAAOqL,yBAEP,MAAM8H,EAAyC,GACzCiE,EAAapX,EAAOsL,kCAC1B,GAAI8L,EAAa,EAAG,CAChB,MAAMC,EAAWrX,EAAOuL,oCAAsC,EAC9D,IAAK,IAAIhF,EAAI,EAAGA,EAAI6Q,EAAY7Q,IAAK,CACjC,MAAM+Q,EAAOD,EAAe,EAAJ9Q,EACxB4M,EAAgBoE,KAAK,CACjBC,QAASxX,EAAO0M,QAAQ4K,GACxBG,QAASzX,EAAO0M,QAAQ4K,EAAO,GAC/BI,QAAS1X,EAAOuB,QAAQ+V,EAAO,GAC/BK,QAAS3X,EAAOuB,QAAQ+V,EAAO,GAC/BlE,SAAUpT,EAAOuB,QAAQ+V,EAAO,GAAKvG,EACrCsC,SAAUrT,EAAOuB,QAAQ+V,EAAO,GAAKvG,GAE7C,CACJ,CAEA,MAAM0C,EAA8D,GAC9DmE,EAAY5X,EAAOwL,iCACzB,GAAIoM,EAAY,EAAG,CACf,MAAMC,EAAU7X,EAAOyL,mCAAqC,EAC5D,IAAK,IAAIlF,EAAI,EAAGA,EAAIqR,EAAWrR,IAAK,CAChC,MAAM+Q,EAAOO,EAAc,EAAJtR,EACvBkN,EAAe8D,KAAK,CAChBC,QAASxX,EAAO0M,QAAQ4K,GACxBG,QAASzX,EAAO0M,QAAQ4K,EAAO,IAEvC,CACJ,CAEA,MAAM5D,EAA8B,GAC9BoE,EAAmB9X,EAAO0L,+BAChC,GAAIoM,EAAmB,EAAG,CACtB,MAAMC,EAAiB/X,EAAO2L,iCAAmC,EACjE,IAAK,IAAIpF,EAAI,EAAGA,EAAIuR,EAAkBvR,IAAK,CACvC,MAAM+Q,EAAOS,EAAqB,EAAJxR,EAC9BmN,EAAa6D,KAAK,CACdS,aAAchY,EAAO0M,QAAQ4K,GAC7BW,cAAejY,EAAO0M,QAAQ4K,EAAO,IAE7C,CACJ,CAEA,MAAM3D,EAA6B,GAC7BuE,EAAkBlY,EAAO4L,8BAC/B,GAAIsM,EAAkB,EAAG,CACrB,MAAMC,EAAgBnY,EAAO6L,gCAAkC,EAC/D,IAAK,IAAItF,EAAI,EAAGA,EAAI2R,EAAiB3R,IAAK,CACtC,MAAM+Q,EAAOa,EAAoB,EAAJ5R,EAC7BoN,EAAY4D,KAAK,CACbS,aAAchY,EAAO0M,QAAQ4K,GAC7BW,cAAejY,EAAO0M,QAAQ4K,EAAO,IAE7C,CACJ,CAEA5G,EAAI6C,eAAeC,GAAe,CAC9BL,kBACAM,iBACAC,eACAC,eAER,CAjM4ByE,CAAc1H,EAAK1Q,EAAQ+Q,IAE/B,CAAElL,KAAM,mBAIhB6K,EAAI2H,cAAgBrY,EACpB0Q,EAAI6C,eAAeK,GAAY0E,GAAQC,YAAYvY,IACnDsT,GAAsB5C,EAAKkD,GAAYJ,IACvC9C,EAAI8H,iBAAiBvE,KAAKG,QAAQE,iBAI1CM,EAAY6D,MAAO/W,IACfgF,QAAQgS,MAAM,4CAA6ChX,KAE/DgP,EAAIiI,mBAAqB/D,CAC7B,EAOJ,MAAMgE,GAAuB,GAE7B,SAASC,GAAqBC,EAAsBC,EAAkBC,GAClE,IAAKA,EAAY,OAAOD,EACxB,IAAK,IAAIxS,EAAI,EAAGA,EAAIqS,GAAsBrS,IACtC,GAAIuS,IAAkB,GAAKvS,EAAI,OAAOyS,EAAWzS,GAErD,OAAOwS,CACX,CAEA,SAASjD,GAAkBpF,EAAU1Q,EAA2BoR,EAAgB4H,GAC5E,MAAM/H,EAAQP,EAAIO,MAElB,GAAIA,EAAM5I,IAAI+I,EAAQc,GAAc,CAChC,MAAMC,EAAMlB,EAAM7L,IAAIgM,EAAQc,GACxB+G,EAAW9G,EAAI2G,cAAgB,EAC/BI,EAAOL,GAAqBI,EAAU9G,EAAI4G,UAAY,MAAQC,GAOpE,YANAhZ,EAAO8K,qBACHsG,EAAQe,EAAIQ,YAAYvQ,EAAG+P,EAAIQ,YAAYtQ,EAC3C8P,EAAII,OAAOnQ,EAAG+P,EAAII,OAAOlQ,EACzB8P,EAAIgH,QAAShH,EAAIiH,SAAUjH,EAAIkH,YAAalH,EAAIE,SAAW,EAAI,EAC/D4G,EAAUC,EAGlB,CAEA,GAAIjI,EAAM5I,IAAI+I,EAAQwB,GAAiB,CACnC,MAAM/P,EAASoO,EAAM7L,IAAIgM,EAAQwB,GAC3BqG,EAAWpW,EAAOiW,cAAgB,EAClCI,EAAOL,GAAqBI,EAAUpW,EAAOkW,UAAY,MAAQC,GAOvE,YANAhZ,EAAO+K,wBACHqG,EAAQvO,EAAOE,OACfF,EAAO0P,OAAOnQ,EAAGS,EAAO0P,OAAOlQ,EAC/BQ,EAAOsW,QAAStW,EAAOuW,SAAUvW,EAAOwW,YAAaxW,EAAOwP,SAAW,EAAI,EAC3E4G,EAAUC,EAGlB,CAEA,GAAIjI,EAAM5I,IAAI+I,EAAQyB,GAAkB,CACpC,MAAMC,EAAU7B,EAAM7L,IAAIgM,EAAQyB,GAC5BoG,EAAWnG,EAAQgG,cAAgB,EACnCI,EAAOL,GAAqBI,EAAUnG,EAAQiG,UAAY,MAAQC,GACxEhZ,EAAOgL,yBACHoG,EAAQ0B,EAAQ/P,OAAQ+P,EAAQhE,WAChCgE,EAAQP,OAAOnQ,EAAG0Q,EAAQP,OAAOlQ,EACjCyQ,EAAQqG,QAASrG,EAAQsG,SAAUtG,EAAQuG,YAAavG,EAAQT,SAAW,EAAI,EAC/E4G,EAAUC,EAElB,CACJ,OA6HaZ,GAGT,WAAAtE,CAAYtD,GAER,GADAuD,KAAKqF,QAAU5I,EAAI2H,eACdpE,KAAKqF,QACN,MAAM,IAAIzY,MAAM,oEAExB,CAGA,kBAAO0X,CAAYvY,GACf,MAAMuZ,EAAWhR,OAAOiR,OAAOlB,GAAQmB,WAEvC,OADAF,EAASD,QAAUtZ,EACZuZ,CACX,CAEA,UAAAG,CAAWtI,EAAgBuI,GACvB1F,KAAKqF,QAAQxN,oBAAoBsF,EAAQuI,EAAMvX,EAAGuX,EAAMtX,EAC5D,CAEA,YAAAuX,CAAaxI,EAAgByI,GACzB5F,KAAKqF,QAAQvN,sBAAsBqF,EAAQyI,EAAQzX,EAAGyX,EAAQxX,EAClE,CAEA,iBAAAyX,CAAkB1I,EAAgB2I,GAC9B9F,KAAKqF,QAAQtN,2BAA2BoF,EAAQ2I,EAAS3X,EAAG2X,EAAS1X,EACzE,CAEA,iBAAA2Q,CAAkB5B,GACd,MACMkG,EADMrD,KAAKqF,QAAQrN,2BAA2BmF,IAChC,EACpB,MAAO,CAAEhP,EAAG6R,KAAKqF,QAAQ/X,QAAQ+V,GAAOjV,EAAG4R,KAAKqF,QAAQ/X,QAAQ+V,EAAO,GAC3E,CAEA,UAAA0C,CAAW3F,GACPJ,KAAKqF,QAAQpN,oBAAoBmI,EAAQjS,EAAGiS,EAAQhS,EACxD,CAEA,UAAA4X,GACI,MACM3C,EADMrD,KAAKqF,QAAQnN,uBACL,EACpB,MAAO,CAAE/J,EAAG6R,KAAKqF,QAAQ/X,QAAQ+V,GAAOjV,EAAG4R,KAAKqF,QAAQ/X,QAAQ+V,EAAO,GAC3E,CAEA,kBAAA4C,CAAmB9I,EAAgB+I,GAC/BlG,KAAKqF,QAAQlN,4BAA4BgF,EAAQ+I,EACrD,CAEA,kBAAAC,CAAmBhJ,GACf,OAAO6C,KAAKqF,QAAQjN,4BAA4B+E,EACpD,CAEA,WAAAiJ,CAAYjJ,EAAgBkJ,GACxBrG,KAAKqF,QAAQhN,qBAAqB8E,EAAQkJ,EAC9C,CAEA,mBAAAC,CAAoBnJ,EAAgByI,GAChC5F,KAAKqF,QAAQ/M,6BAA6B6E,EAAQyI,EACtD,CAEA,mBAAOW,CAAa9J,EAAUjM,GAC1B,MAAMoM,EAASH,EAAII,YAAoCnE,GACnDkE,IACAA,EAAOpM,QAAUA,EACjBiM,EAAI6C,eAAe5G,EAAkBkE,GAE7C,CAEA,yBAAO4J,CAAmB/J,EAAUG,GAChC,MAAM6J,EAAUhK,EAAII,YAAoCnE,GACpD+N,GACAhK,EAAI6C,eAAe5G,EAAkB,IAAK+N,KAAY7J,GAE9D"}
\ No newline at end of file
+{"version":3,"file":"index.js","sources":["../../src/draw.ts","../../src/customDraw.ts","../../src/env.ts","../../src/physics/PhysicsModuleLoader.ts","../../src/physics/PhysicsDebugDraw.ts","../../src/physics/PhysicsPlugin.ts"],"sourcesContent":[null,null,null,null,null,null],"names":["module","viewProjectionPtr","transformPtr","uniformsPtr","uniformBuffer","Float32Array","initDrawAPI","wasmModule","_malloc","UNIFORMS_BUFFER_SIZE","shutdownDrawAPI","_free","getModule","Error","WHITE","r","g","b","a","Draw","begin","viewProjection","m","HEAPF32","set","draw_begin","e","handleWasmError","end","draw_end","line","from","to","color","thickness","draw_line","x","y","rect","position","size","filled","draw_rect","rectOutline","draw_rectOutline","circle","center","radius","segments","draw_circle","circleOutline","draw_circleOutline","texture","textureHandle","tint","draw_texture","textureRotated","rotation","draw_textureRotated","setLayer","layer","draw_setLayer","setDepth","depth","draw_setDepth","getDrawCallCount","draw_getDrawCallCount","getPrimitiveCount","draw_getPrimitiveCount","setBlendMode","mode","draw_setBlendMode","setDepthTest","enabled","draw_setDepthTest","drawMesh","geometry","shader","transform","draw_mesh","drawMeshWithMaterial","material","matData","Material","get","blendMode","depthTest","uniforms","idx","dirty_","cachedBuffer_","cachedIdx_","autoTextureSlot","name","value","nameId","getUniformNameId","isTextureRef","slot","textureId","Array","isArray","length","i","z","w","console","warn","subarray","draw_meshWithUniforms","UNIFORM_NAME_MAP","u_time","u_color","u_intensity","u_scale","u_offset","u_param0","u_param1","u_param2","u_param3","u_param4","u_vec0","u_vec1","u_vec2","u_vec3","u_texture0","u_texture1","u_texture2","u_texture3","warnedUniforms","Set","id","undefined","has","add","Object","keys","join","callbacks","Map","registerDrawCallback","fn","scene","unregisterDrawCallback","delete","clearDrawCallbacks","clear","getDrawCallbacks","editorMode","playMode","setEditorMode","active","isEditor","isRuntime","setPlayMode","isPlayMode","async","loadPhysicsModule","wasmUrl","factory","loadPhysicsSideModule","wasmBinary","mainModule","loadDynamicLibrary","Uint8Array","loadAsync","allowUndefined","cwrap","bind","_physics_init","_physics_shutdown","_physics_createBody","_physics_destroyBody","_physics_hasBody","_physics_addBoxShape","_physics_addCircleShape","_physics_addCapsuleShape","_physics_step","_physics_setBodyTransform","_physics_getDynamicBodyCount","_physics_getDynamicBodyTransforms","_physics_collectEvents","_physics_getCollisionEnterCount","_physics_getCollisionEnterBuffer","_physics_getCollisionExitCount","_physics_getCollisionExitBuffer","_physics_getSensorEnterCount","_physics_getSensorEnterBuffer","_physics_getSensorExitCount","_physics_getSensorExitBuffer","_physics_applyForce","_physics_applyImpulse","_physics_setLinearVelocity","_physics_getLinearVelocity","_physics_setGravity","_physics_getGravity","_physics_setAngularVelocity","_physics_getAngularVelocity","_physics_applyTorque","_physics_applyAngularImpulse","_physics_updateBodyProperties","HEAPU8","HEAPU32","PhysicsDebugDraw","defineResource","showColliders","showVelocity","showContacts","STATIC_COLOR","DYNAMIC_COLOR","KINEMATIC_COLOR","SENSOR_COLOR","VELOCITY_COLOR","CONTACT_COLOR","DEBUG_LINE_THICKNESS","CAPSULE_ARC_SEGMENTS","quatToAngleZ","q","Math","atan2","bodyTypeColor","bodyType","BodyType","Static","Kinematic","Dynamic","drawRotatedBox","cx","cy","halfW","halfH","angle","cos","sin","pts","map","c","drawCapsule","halfHeight","toWorld","lx","ly","topLeft","topRight","bottomLeft","bottomRight","a0","PI","a1","p0","p1","drawVelocityArrow","vx","vy","endX","endY","len","sqrt","ARROWHEAD_ANGLE","dirX","dirY","leftX","leftY","rightX","rightY","drawPhysicsDebug","app","physicsApiRes","physicsEventsRes","config","getResource","ppu","entities","world","getEntitiesWithComponents","Canvas","entity","canvas","pixelsPerUnit","readPixelsPerUnit","RigidBody","Transform","physics","hasResource","rb","wt","wx","worldPosition","wy","worldRotation","BoxCollider","box","baseColor","isSensor","offsetX","offset","offsetY","cosA","sinA","halfExtents","CircleCollider","CapsuleCollider","capsule","vel","getLinearVelocity","events","collision","collisionEnters","contactX","contactY","setupPhysicsDebugDraw","insertResource","PhysicsEvents","collisionExits","sensorEnters","sensorExits","PhysicsAPI","angleZToQuat","half","PhysicsPlugin","constructor","this","wasmUrl_","factory_","config_","gravity","fixedTimestep","subStepCount","collisionLayerMasks","build","trackedEntities","cachedProps","initPromise","then","invPpu","onDespawn","addSystemToSchedule","Schedule","PostUpdate","defineSystem","Res","Time","time","currentEntities","prev","gravityScale","linearDamping","angularDamping","fixedRotation","bullet","addShapeForEntity","delta","count","ptr","baseU32","entityId","worldX","worldY","worldAngle","valid","localX","localY","localAngle","Parent","parentData","pwt","parentAngle","dx","dy","worldScale","insert","syncDynamicTransforms","enterCount","enterPtr","base","push","entityA","entityB","normalX","normalY","exitCount","exitPtr","sensorEnterCount","sensorEnterPtr","sensorEntity","visitorEntity","sensorExitCount","sensorExitPtr","collectEvents","physicsModule","Physics","_fromModule","setFixedTimestep","catch","error","physicsInitPromise","MAX_COLLISION_LAYERS","resolveCollisionMask","categoryBits","maskBits","layerMasks","category","mask","density","friction","restitution","module_","instance","create","prototype","applyForce","force","applyImpulse","impulse","setLinearVelocity","velocity","setGravity","getGravity","setAngularVelocity","omega","getAngularVelocity","applyTorque","torque","applyAngularImpulse","setDebugDraw","setDebugDrawConfig","current"],"mappings":"4IAqBA,IAAIA,EAAgC,KAChCC,EAA4B,EAC5BC,EAAuB,EACvBC,EAAsB,EAE1B,MACMC,EAAgB,IAAIC,aADG,KAOvB,SAAUC,EAAYC,GACxBP,EAASO,EACTN,EAAoBD,EAAOQ,QAAQ,IACnCN,EAAeF,EAAOQ,QAAQ,IAC9BL,EAAcH,EAAOQ,QAAQC,KACjC,UAEgBC,IACRV,IACIC,IACAD,EAAOW,MAAMV,GACbA,EAAoB,GAEpBC,IACAF,EAAOW,MAAMT,GACbA,EAAe,GAEfC,IACAH,EAAOW,MAAMR,GACbA,EAAc,IAGtBH,EAAS,IACb,CA4IA,SAASY,IACL,IAAKZ,EACD,MAAM,IAAIa,MAAM,uDAEpB,OAAOb,CACX,CAEA,MAAMc,EAAe,CAAEC,EAAG,EAAGC,EAAG,EAAGC,EAAG,EAAGC,EAAG,GAE/BC,EAAgB,CACzB,KAAAC,CAAMC,GACF,MAAMC,EAAIV,IACV,IACIU,EAAEC,QAAQC,IAAIH,EAAgBpB,EAAoB,GAClDqB,EAAEG,WAAWxB,EACjB,CAAE,MAAOyB,GACLC,EAAgBD,EAAG,aACvB,CACJ,EAEA,GAAAE,GACI,IACIhB,IAAYiB,UAChB,CAAE,MAAOH,GACLC,EAAgBD,EAAG,WACvB,CACJ,EAEA,IAAAI,CAAKC,EAAYC,EAAUC,EAAcC,EAAY,GACjD,IACItB,IAAYuB,UACRJ,EAAKK,EAAGL,EAAKM,EACbL,EAAGI,EAAGJ,EAAGK,EACTJ,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCgB,EAER,CAAE,MAAOR,GACLC,EAAgBD,EAAG,YACvB,CACJ,EAEA,IAAAY,CAAKC,EAAgBC,EAAYP,EAAcQ,GAAS,GACpD,IACI7B,IAAY8B,UACRH,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACbJ,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCuB,EAER,CAAE,MAAOf,GACLC,EAAgBD,EAAG,YACvB,CACJ,EAEA,WAAAiB,CAAYJ,EAAgBC,EAAYP,EAAcC,EAAY,GAC9D,IACItB,IAAYgC,iBACRL,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACbJ,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCgB,EAER,CAAE,MAAOR,GACLC,EAAgBD,EAAG,mBACvB,CACJ,EAEA,MAAAmB,CAAOC,EAAcC,EAAgBd,EAAcQ,GAAS,EAAMO,EAAW,IACzE,IACIpC,IAAYqC,YACRH,EAAOV,EAAGU,EAAOT,EACjBU,EACAd,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCuB,EACAO,EAER,CAAE,MAAOtB,GACLC,EAAgBD,EAAG,cACvB,CACJ,EAEA,aAAAwB,CAAcJ,EAAcC,EAAgBd,EAAcC,EAAY,EAAGc,EAAW,IAChF,IACIpC,IAAYuC,mBACRL,EAAOV,EAAGU,EAAOT,EACjBU,EACAd,EAAMlB,EAAGkB,EAAMjB,EAAGiB,EAAMhB,EAAGgB,EAAMf,EACjCgB,EACAc,EAER,CAAE,MAAOtB,GACLC,EAAgBD,EAAG,qBACvB,CACJ,EAEA,OAAA0B,CAAQb,EAAgBC,EAAYa,EAAuBC,EAAcxC,GACrE,IACIF,IAAY2C,aACRhB,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACbgB,EACAC,EAAKvC,EAAGuC,EAAKtC,EAAGsC,EAAKrC,EAAGqC,EAAKpC,EAErC,CAAE,MAAOQ,GACLC,EAAgBD,EAAG,eACvB,CACJ,EAEA,cAAA8B,CAAejB,EAAgBC,EAAYiB,EAAkBJ,EAAuBC,EAAcxC,GAC9F,IACIF,IAAY8C,oBACRnB,EAASH,EAAGG,EAASF,EACrBG,EAAKJ,EAAGI,EAAKH,EACboB,EACAJ,EACAC,EAAKvC,EAAGuC,EAAKtC,EAAGsC,EAAKrC,EAAGqC,EAAKpC,EAErC,CAAE,MAAOQ,GACLC,EAAgBD,EAAG,sBACvB,CACJ,EAEA,QAAAiC,CAASC,GACLhD,IAAYiD,cAAcD,EAC9B,EAEA,QAAAE,CAASC,GACLnD,IAAYoD,cAAcD,EAC9B,EAEAE,iBAAgB,IACPjE,EACEA,EAAOkE,wBADM,EAIxBC,kBAAiB,IACRnE,EACEA,EAAOoE,yBADM,EAIxB,YAAAC,CAAaC,GACT1D,IAAY2D,kBAAkBD,EAClC,EAEA,YAAAE,CAAaC,GACT7D,IAAY8D,kBAAkBD,EAClC,EAEA,QAAAE,CAASC,EAA0BC,EAAsBC,GACrD,IACI,MAAMxD,EAAIV,IACVU,EAAEC,QAAQC,IAAIsD,EAAW5E,EAAe,GACxCoB,EAAEyD,UAAUH,EAAUC,EAAQ3E,EAClC,CAAE,MAAOwB,GACLC,EAAgBD,EAAG,0BAA0BkD,aAAoBC,KACrE,CACJ,EAEA,oBAAAG,CAAqBJ,EAA0BK,EAA0BH,GACrE,IACI,MAAMxD,EAAIV,IACJsE,EAAUC,EAASC,IAAIH,GAC7B,IAAKC,EAAS,OAKd,GAHA/D,EAAKkD,aAAaa,EAAQG,WAC1BlE,EAAKqD,aAAaU,EAAQI,WAEI,IAA1BJ,EAAQK,SAAS/C,KAEjB,YADArB,EAAKwD,SAASC,EAAUM,EAAQL,OAAQC,GAM5C,IAAIU,EACJ,GAHAlE,EAAEC,QAAQC,IAAIsD,EAAW5E,EAAe,IAGnCgF,EAAQO,QAAUP,EAAQQ,cAC3BF,EAAMN,EAAQS,eACX,CACHH,EAAM,EACN,IAAII,EAAkB,EACtB,IAAK,MAAOC,EAAMC,KAAUZ,EAAQK,SAAU,CAC1C,MAAMQ,EAASC,EAAiBH,GAChC,KAAIE,EAAS,GAAb,CAEA,GAAIE,EAAaH,GACb1F,EAAcoF,KAAS,GACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAMI,MAAQN,IACrCxF,EAAcoF,KAASM,EAAMK,eAC1B,GAAqB,iBAAVL,EACd1F,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,OACpB,GAAIM,MAAMC,QAAQP,GAAQ,CAC7B1F,EAAcoF,KAASM,EAAMQ,OAC7BlG,EAAcoF,KAASO,EACvB,IAAK,IAAIQ,EAAI,EAAGA,EAAIT,EAAMQ,OAAQC,IAC9BnG,EAAcoF,KAASM,EAAMS,EAErC,KAAW,MAAOT,GACd1F,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAM1D,EAC7BhC,EAAcoF,KAASM,EAAMzD,EAC7BjC,EAAcoF,KAASM,EAAMU,EAC7BpG,EAAcoF,KAASM,EAAMW,GACtB,MAAOX,GACd1F,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAM1D,EAC7BhC,EAAcoF,KAASM,EAAMzD,EAC7BjC,EAAcoF,KAASM,EAAMU,IAE7BpG,EAAcoF,KAAS,EACvBpF,EAAcoF,KAASO,EACvB3F,EAAcoF,KAASM,EAAM1D,EAC7BhC,EAAcoF,KAASM,EAAMzD,GAGjC,GAAImD,EAAM/E,IAA0B,CAChCiG,QAAQC,KAAK,0DACb,KACJ,CAxCgB,CAyCpB,GAEKzB,EAAQQ,eAAiBR,EAAQQ,cAAcY,OAASd,KACzDN,EAAQQ,cAAgB,IAAIrF,aAAamF,IAE7CN,EAAQQ,cAAclE,IAAIpB,EAAcwG,SAAS,EAAGpB,IACpDN,EAAQS,WAAaH,EACrBN,EAAQO,QAAS,CACrB,CAEA,GAAY,IAARD,EAEA,YADAlE,EAAEyD,UAAUH,EAAUM,EAAQL,OAAQ3E,GAI1CoB,EAAEC,QAAQC,IAAI0D,EAAQQ,cAAekB,SAAS,EAAGpB,GAAMrF,EAAc,GACrEmB,EAAEuF,sBAAsBjC,EAAUM,EAAQL,OAAQ3E,EAAcC,EAAaqF,EACjF,CAAE,MAAO9D,GACLC,EAAgBD,EAAG,sCAAsCkD,eAAsBK,KACnF,CACJ,GAGE6B,EAA2C,CAC7CC,OAAU,EACVC,QAAW,EACXC,YAAe,EACfC,QAAW,EACXC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,SAAY,EACZC,OAAU,GACVC,OAAU,GACVC,OAAU,GACVC,OAAU,GACVC,WAAc,GACdC,WAAc,GACdC,WAAc,GACdC,WAAc,IAGZC,EAAiB,IAAIC,IAE3B,SAASlC,EAAiBH,GACtB,MAAMsC,EAAKrB,EAAiBjB,GAC5B,YAAWuC,IAAPD,EAAyBA,GACxBF,EAAeI,IAAIxC,KACpBoC,EAAeK,IAAIzC,GACnBa,QAAQC,KACJ,oCAAoCd,yBAChB0C,OAAOC,KAAK1B,GAAkB2B,KAAK,WAGxD,EACX,CCrdA,MAAMC,EAAY,IAAIC,aAENC,EAAqBT,EAAYU,EAAkBC,GAC/DJ,EAAUlH,IAAI2G,EAAI,CAAEU,KAAIC,MAAOA,GAAS,IAC5C,CAEM,SAAUC,EAAuBZ,GACnCO,EAAUM,OAAOb,EACrB,UAEgBc,IACZP,EAAUQ,OACd,UAUgBC,IACZ,OAAOT,CACX,CC/BA,IAAIU,GAAa,EACbC,GAAW,EAET,SAAUC,EAAcC,GAC1BH,EAAaG,CACjB,UAEgBC,IACZ,OAAOJ,CACX,UAEgBK,IACZ,OAAQL,CACZ,CAEM,SAAUM,EAAYH,GACxBF,EAAWE,CACf,UAEgBI,IACZ,OAAON,CACX,CCiDOO,eAAeC,EAClBC,EACAC,GAEA,IAAKA,EACD,MAAM,IAAIlJ,MACN,8IAIR,OAAOkJ,GACX,CAYOH,eAAeI,EAClBC,EACAC,SAEMA,EAAWC,mBACb,IAAIC,WAAWH,GACf,CAAEI,WAAW,EAAMC,gBAAgB,IAGvC,MAAMC,EAAQL,EAAWK,MAAMC,KAAKN,GAEpC,MAAO,CACHO,cAAeF,EAAM,eAAgB,KAAM,CAAC,SAAU,SAAU,SAAU,WAC1EG,kBAAmBH,EAAM,mBAAoB,KAAM,IAEnDI,oBAAqBJ,EAAM,qBAAsB,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAClJK,qBAAsBL,EAAM,sBAAuB,KAAM,CAAC,WAC1DM,iBAAkBN,EAAM,kBAAmB,SAAU,CAAC,WAEtDO,qBAAsBP,EAAM,sBAAuB,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAC9JQ,wBAAyBR,EAAM,yBAA0B,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAC1JS,yBAA0BT,EAAM,0BAA2B,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAEtKU,cAAeV,EAAM,eAAgB,KAAM,CAAC,WAE5CW,0BAA2BX,EAAM,2BAA4B,KAAM,CAAC,SAAU,SAAU,SAAU,WAClGY,6BAA8BZ,EAAM,8BAA+B,SAAU,IAC7Ea,kCAAmCb,EAAM,mCAAoC,SAAU,IAEvFc,uBAAwBd,EAAM,wBAAyB,KAAM,IAC7De,gCAAiCf,EAAM,iCAAkC,SAAU,IACnFgB,iCAAkChB,EAAM,kCAAmC,SAAU,IACrFiB,+BAAgCjB,EAAM,gCAAiC,SAAU,IACjFkB,gCAAiClB,EAAM,iCAAkC,SAAU,IACnFmB,6BAA8BnB,EAAM,8BAA+B,SAAU,IAC7EoB,8BAA+BpB,EAAM,+BAAgC,SAAU,IAC/EqB,4BAA6BrB,EAAM,6BAA8B,SAAU,IAC3EsB,6BAA8BtB,EAAM,8BAA+B,SAAU,IAE7EuB,oBAAqBvB,EAAM,qBAAsB,KAAM,CAAC,SAAU,SAAU,WAC5EwB,sBAAuBxB,EAAM,uBAAwB,KAAM,CAAC,SAAU,SAAU,WAChFyB,2BAA4BzB,EAAM,4BAA6B,KAAM,CAAC,SAAU,SAAU,WAC1F0B,2BAA4B1B,EAAM,4BAA6B,SAAU,CAAC,WAE1E2B,oBAAqB3B,EAAM,qBAAsB,KAAM,CAAC,SAAU,WAClE4B,oBAAqB5B,EAAM,qBAAsB,SAAU,IAE3D6B,4BAA6B7B,EAAM,6BAA8B,KAAM,CAAC,SAAU,WAClF8B,4BAA6B9B,EAAM,6BAA8B,SAAU,CAAC,WAC5E+B,qBAAsB/B,EAAM,sBAAuB,KAAM,CAAC,SAAU,WACpEgC,6BAA8BhC,EAAM,8BAA+B,KAAM,CAAC,SAAU,WAEpFiC,8BAA+BjC,EAAM,+BAAgC,KAAM,CAAC,SAAU,SAAU,SAAU,SAAU,SAAU,SAAU,WAExI,WAAIhJ,GAAY,OAAO2I,EAAW3I,OAAS,EAC3C,UAAIkL,GAAW,OAAOvC,EAAWuC,MAAQ,EACzC,WAAIC,GAAY,OAAOxC,EAAWwC,OAAS,EAC3ClM,QAAS0J,EAAW1J,QAAQgK,KAAKN,GACjCvJ,MAAOuJ,EAAWvJ,MAAM6J,KAAKN,GAErC,CCtIO,MAAMyC,EAAmBC,EAAuC,CACnEnI,SAAS,EACToI,eAAe,EACfC,cAAc,EACdC,cAAc,GACf,oBAMGC,EAAsB,CAAEjM,EAAG,GAAKC,EAAG,GAAKC,EAAG,EAAKC,EAAG,IACnD+L,EAAuB,CAAElM,EAAG,GAAKC,EAAG,EAAKC,EAAG,GAAKC,EAAG,IACpDgM,EAAyB,CAAEnM,EAAG,GAAKC,EAAG,EAAKC,EAAG,EAAKC,EAAG,IACtDiM,EAAsB,CAAEpM,EAAG,EAAKC,EAAG,EAAKC,EAAG,GAAKC,EAAG,IACnDkM,EAAwB,CAAErM,EAAG,EAAKC,EAAG,GAAKC,EAAG,GAAKC,EAAG,IACrDmM,EAAuB,CAAEtM,EAAG,EAAKC,EAAG,GAAKC,EAAG,GAAKC,EAAG,GACpDoM,EAAuB,IAIvBC,EAAuB,GAE7B,SAASC,EAAaC,GAClB,OAAOC,KAAKC,MAAM,GAAKF,EAAEhH,EAAIgH,EAAEjH,EAAIiH,EAAErL,EAAIqL,EAAEpL,GAAI,EAAI,GAAKoL,EAAEpL,EAAIoL,EAAEpL,EAAIoL,EAAEjH,EAAIiH,EAAEjH,GAChF,CAEA,SAASoH,EAAcC,GACnB,OAAQA,GACJ,KAAKC,EAASC,OAAQ,OAAOf,EAC7B,KAAKc,EAASE,UAAW,OAAOd,EAChC,KAAKY,EAASG,QACd,QAAS,OAAOhB,EAExB,CAaA,SAASiB,GACLC,EAAYC,EACZC,EAAeC,EACfC,EAAetM,GAEf,MAAMuM,EAAMd,KAAKc,IAAID,GACfE,EAAMf,KAAKe,IAAIF,GAOfG,EANU,CACZ,CAAEtM,GAAIiM,EAAOhM,GAAIiM,GACjB,CAAElM,EAAIiM,EAAOhM,GAAIiM,GACjB,CAAElM,EAAIiM,EAAOhM,EAAIiM,GACjB,CAAElM,GAAIiM,EAAOhM,EAAIiM,IAEDK,IAAIC,IAAC,CACrBxM,EAAG+L,EAAKS,EAAExM,EAAIoM,EAAMI,EAAEvM,EAAIoM,EAC1BpM,EAAG+L,EAAKQ,EAAExM,EAAIqM,EAAMG,EAAEvM,EAAImM,KAE9B,IAAK,IAAIjI,EAAI,EAAGA,EAAI,EAAGA,IACnBpF,EAAKW,KAAK4M,EAAInI,GAAImI,GAAKnI,EAAI,GAAK,GAAItE,EAAOqL,EAEnD,CAEA,SAASuB,GACLV,EAAYC,EACZrL,EAAgB+L,EAChBP,EAAetM,GAEf,MAAMuM,EAAMd,KAAKc,IAAID,GACfE,EAAMf,KAAKe,IAAIF,GAEfQ,EAAU,CAACC,EAAYC,KAAU,CACnC7M,EAAG+L,EAAKa,EAAKR,EAAMS,EAAKR,EACxBpM,EAAG+L,EAAKY,EAAKP,EAAMQ,EAAKT,IAGtBU,EAAUH,GAAShM,EAAQ+L,GAC3BK,EAAWJ,EAAQhM,EAAQ+L,GAC3BM,EAAaL,GAAShM,GAAS+L,GAC/BO,EAAcN,EAAQhM,GAAS+L,GAErC3N,EAAKW,KAAKoN,EAASE,EAAYnN,EAAOqL,GACtCnM,EAAKW,KAAKqN,EAAUE,EAAapN,EAAOqL,GAExC,IAAK,IAAI/G,EAAI,EAAGA,EAAIgH,EAAsBhH,IAAK,CAC3C,MAAM+I,EAAM/I,EAAIgH,EAAwBG,KAAK6B,GACvCC,GAAOjJ,EAAI,GAAKgH,EAAwBG,KAAK6B,GAC7CE,EAAKV,GACNhM,EAAS2K,KAAKc,IAAIc,GACnBR,EAAa/L,EAAS2K,KAAKe,IAAIa,IAE7BI,EAAKX,GACNhM,EAAS2K,KAAKc,IAAIgB,GACnBV,EAAa/L,EAAS2K,KAAKe,IAAIe,IAEnCrO,EAAKW,KAAK2N,EAAIC,EAAIzN,EAAOqL,EAC7B,CAEA,IAAK,IAAI/G,EAAI,EAAGA,EAAIgH,EAAsBhH,IAAK,CAC3C,MAAM+I,EAAK5B,KAAK6B,GAAMhJ,EAAIgH,EAAwBG,KAAK6B,GACjDC,EAAK9B,KAAK6B,IAAOhJ,EAAI,GAAKgH,EAAwBG,KAAK6B,GACvDE,EAAKV,GACNhM,EAAS2K,KAAKc,IAAIc,IAClBR,EAAa/L,EAAS2K,KAAKe,IAAIa,IAE9BI,EAAKX,GACNhM,EAAS2K,KAAKc,IAAIgB,IAClBV,EAAa/L,EAAS2K,KAAKe,IAAIe,IAEpCrO,EAAKW,KAAK2N,EAAIC,EAAIzN,EAAOqL,EAC7B,CACJ,CAEA,SAASqC,GACLvN,EAAWC,EACXuN,EAAYC,GAEZ,MAAMC,EAAO1N,EAxGM,GAwGFwN,EACXG,EAAO1N,EAzGM,GAyGFwN,EACjB1O,EAAKW,KAAK,CAAEM,IAAGC,KAAK,CAAED,EAAG0N,EAAMzN,EAAG0N,GAAQ3C,EAAgBE,GAE1D,MAAM0C,EAAMtC,KAAKuC,KAAKL,EAAKA,EAAKC,EAAKA,GACrC,GAAIG,EAAM,EAAG,OAEb,MACME,EAAkBxC,KAAK6B,GAAK,EAC5BY,EAAOP,EAAKI,EACZI,EAAOP,EAAKG,EAEZK,EAAQP,EALW,GAKgBK,EAAOzC,KAAKc,IAAI0B,GAAmBE,EAAO1C,KAAKe,IAAIyB,IACtFI,EAAQP,EANW,GAMgBI,EAAOzC,KAAKe,IAAIyB,GAAmBE,EAAO1C,KAAKc,IAAI0B,IACtFK,EAAST,EAPU,GAOiBK,EAAOzC,KAAKc,IAAI0B,GAAmBE,EAAO1C,KAAKe,IAAIyB,IACvFM,EAAST,EARU,IAQkBI,EAAOzC,KAAKe,IAAIyB,GAAmBE,EAAO1C,KAAKc,IAAI0B,IAE9F/O,EAAKW,KAAK,CAAEM,EAAG0N,EAAMzN,EAAG0N,GAAQ,CAAE3N,EAAGiO,EAAOhO,EAAGiO,GAASlD,EAAgBE,GACxEnM,EAAKW,KAAK,CAAEM,EAAG0N,EAAMzN,EAAG0N,GAAQ,CAAE3N,EAAGmO,EAAQlO,EAAGmO,GAAUpD,EAAgBE,EAC9E,UAEgBmD,GACZC,EACAC,EACAC,GAEA,MAAMC,EAASH,EAAII,YAAoCnE,GACvD,IAAKkE,IAAWA,EAAOpM,QAAS,OAEhC,MAAMsM,EApHV,SAA2BL,GACvB,MAAMM,EAAWN,EAAIO,MAAMC,0BAA0B,CAACC,IACtD,IAAK,MAAMC,KAAUJ,EAAU,CAC3B,MAAMK,EAASX,EAAIO,MAAM7L,IAAIgM,EAAQD,GACrC,GAAIE,GAAUA,EAAOC,cACjB,OAAOD,EAAOC,aAEtB,CACA,OAAO,GACX,CA2GgBC,CAAkBb,GACxBM,EAAWN,EAAIO,MAAMC,0BAA0B,CAACM,EAAWC,IAEjE,IAAIC,EAAmC,KACnCb,EAAO/D,cAAgB4D,EAAIiB,YAAYhB,KACvCe,EAAUhB,EAAII,YAA8BH,IAGhD,IAAK,MAAMS,KAAUJ,EAAU,CAC3B,MAAMY,EAAKlB,EAAIO,MAAM7L,IAAIgM,EAAQI,GACjC,IAAKI,EAAGnN,QAAS,SAEjB,MAAMoN,EAAKnB,EAAIO,MAAM7L,IAAIgM,EAAQK,GAC3BK,EAAKD,EAAGE,cAAc3P,EACtB4P,EAAKH,EAAGE,cAAc1P,EACtBkM,EAAQf,EAAaqE,EAAGI,eAE9B,GAAIpB,EAAOhE,cAAe,CACtB,GAAI6D,EAAIO,MAAM5I,IAAI+I,EAAQc,GAAc,CACpC,MAAMC,EAAMzB,EAAIO,MAAM7L,IAAIgM,EAAQc,GAC5BE,EAAYD,EAAIE,SAAWlF,EAAeS,EAAcgE,EAAG/D,UAC3DyE,EAAUH,EAAII,OAAOnQ,EAAI2O,EACzByB,EAAUL,EAAII,OAAOlQ,EAAI0O,EACzB0B,EAAO/E,KAAKc,IAAID,GAChBmE,EAAOhF,KAAKe,IAAIF,GAGtBL,GAFW4D,EAAKQ,EAAUG,EAAOD,EAAUE,EAChCV,EAAKM,EAAUI,EAAOF,EAAUC,EACpBN,EAAIQ,YAAYvQ,EAAI2O,EAAKoB,EAAIQ,YAAYtQ,EAAI0O,EAAKxC,EAAO6D,EACpF,CAEA,GAAI1B,EAAIO,MAAM5I,IAAI+I,EAAQwB,GAAiB,CACvC,MAAM/P,EAAS6N,EAAIO,MAAM7L,IAAIgM,EAAQwB,GAC/BR,EAAYvP,EAAOwP,SAAWlF,EAAeS,EAAcgE,EAAG/D,UAC9DyE,EAAUzP,EAAO0P,OAAOnQ,EAAI2O,EAC5ByB,EAAU3P,EAAO0P,OAAOlQ,EAAI0O,EAC5B0B,EAAO/E,KAAKc,IAAID,GAChBmE,EAAOhF,KAAKe,IAAIF,GAChBJ,EAAK2D,EAAKQ,EAAUG,EAAOD,EAAUE,EACrCtE,EAAK4D,EAAKM,EAAUI,EAAOF,EAAUC,EAC3CtR,EAAK+B,cACD,CAAEd,EAAG+L,EAAI9L,EAAG+L,GACZvL,EAAOE,OAASgO,EAChBqB,EACA9E,EA/KI,GAkLZ,CAEA,GAAIoD,EAAIO,MAAM5I,IAAI+I,EAAQyB,GAAkB,CACxC,MAAMC,EAAUpC,EAAIO,MAAM7L,IAAIgM,EAAQyB,GAChCT,EAAYU,EAAQT,SAAWlF,EAAeS,EAAcgE,EAAG/D,UAC/DyE,EAAUQ,EAAQP,OAAOnQ,EAAI2O,EAC7ByB,EAAUM,EAAQP,OAAOlQ,EAAI0O,EAC7B0B,EAAO/E,KAAKc,IAAID,GAChBmE,EAAOhF,KAAKe,IAAIF,GAGtBM,GAFWiD,EAAKQ,EAAUG,EAAOD,EAAUE,EAChCV,EAAKM,EAAUI,EAAOF,EAAUC,EACvBK,EAAQ/P,OAASgO,EAAK+B,EAAQhE,WAAaiC,EAAKxC,EAAO6D,EAC/E,CACJ,CAEA,GAAIvB,EAAO/D,cAAgB4E,GAAWE,EAAG/D,WAAaC,EAASG,QAAS,CACpE,MAAM8E,EAAMrB,EAAQsB,kBAAkB5B,GACtCzB,GAAkBmC,EAAIE,EAAIe,EAAI3Q,EAAI2O,EAAKgC,EAAI1Q,EAAI0O,EACnD,CACJ,CAEA,GAAIF,EAAO9D,cAAgB2D,EAAIiB,YAAYf,GAAmB,CAC1D,MAAMqC,EAASvC,EAAII,YAA+BF,GAClD,IAAK,MAAMsC,KAAaD,EAAOE,gBAC3BhS,EAAK0B,OACD,CAAET,EAAG8Q,EAAUE,SAAU/Q,EAAG6Q,EAAUG,UA7MzB,EA+MbhG,GACA,EA9MQ,GAkNpB,CACJ,UAEgBiG,GACZ5C,EACAC,EACAC,GAEAF,EAAI6C,eAAe5G,EAAkB,CACjClI,SAAS,EACToI,eAAe,EACfC,cAAc,EACdC,cAAc,IAGlBnE,EAAqB,qBAAsB,KACvC6H,GAAiBC,EAAKC,EAAeC,IAE7C,CCnNO,MAAM4C,GAAgB5G,EAAkC,CAC3DuG,gBAAiB,GACjBM,eAAgB,GAChBC,aAAc,GACdC,YAAa,IACd,iBAEUC,GAAahH,EAAwB,KAAO,cAMzD,SAASY,GAAaC,GAClB,OAAOC,KAAKC,MAAM,GAAKF,EAAEhH,EAAIgH,EAAEjH,EAAIiH,EAAErL,EAAIqL,EAAEpL,GAAI,EAAI,GAAKoL,EAAEpL,EAAIoL,EAAEpL,EAAIoL,EAAEjH,EAAIiH,EAAEjH,GAChF,CAEA,SAASqN,GAAatF,GAClB,MAAMuF,EAAe,GAARvF,EACb,MAAO,CAAE9H,EAAGiH,KAAKc,IAAIsF,GAAO1R,EAAG,EAAGC,EAAG,EAAGmE,EAAGkH,KAAKe,IAAIqF,GACxD,OAiBaC,GAKT,WAAAC,CAAYlK,EAAiB+G,EAA8B,CAAA,EAAI9G,GAC3DkK,KAAKC,SAAWpK,EAChBmK,KAAKE,SAAWpK,EAChBkK,KAAKG,QAAU,CACXC,QAASxD,EAAOwD,SAAW,CAAEjS,EAAG,EAAGC,SACnCiS,cAAezD,EAAOyD,eAAiB,EAAI,GAC3CC,aAAc1D,EAAO0D,cAAgB,EACrCC,oBAAqB3D,EAAO2D,oBAEpC,CAEA,KAAAC,CAAM/D,GACFA,EAAI6C,eAAeC,GAAe,CAC9BL,gBAAiB,GACjBM,eAAgB,GAChBC,aAAc,GACdC,YAAa,KAGjB,MAAMe,EAAkB,IAAIxM,IACtByM,EAAc,IAAIhM,IAElBiM,EAAc/K,EAAkBoK,KAAKC,SAAUD,KAAKE,UAAUU,KAC/D7U,IACGA,EAAOyK,cACHwJ,KAAKG,QAAQC,QAAQjS,EACrB6R,KAAKG,QAAQC,QAAQhS,EACrB4R,KAAKG,QAAQE,cACbL,KAAKG,QAAQG,cAGjB,MAAMxD,EA/CtB,SAA2BL,GACvB,MAAMM,EAAWN,EAAIO,MAAMC,0BAA0B,CAACC,IACtD,IAAK,MAAMC,KAAUJ,EAAU,CAC3B,MAAMK,EAASX,EAAIO,MAAM7L,IAAIgM,EAAQD,GACrC,GAAIE,GAAUA,EAAOC,cACjB,OAAOD,EAAOC,aAEtB,CACA,OAAO,GACX,CAsC4BC,CAAkBb,GACxBoE,EAAS,EAAI/D,EAEbE,EAAQP,EAAIO,MAElBA,EAAM8D,UAAW3D,IACTsD,EAAgBrM,IAAI+I,KACpBpR,EAAO4K,qBAAqBwG,GAC5BsD,EAAgB1L,OAAOoI,GACvBuD,EAAY3L,OAAOoI,MAI3BV,EAAIsE,oBACAC,EAASC,WACTC,EACI,CAACC,EAAIC,IACJC,IACG,GAAI9L,MAAeG,IAAc,OAEjC,MAAMqH,EAAWC,EAAMC,0BAA0B,CAACM,EAAWC,IACvD8D,EAAkB,IAAIrN,IAE5B,IAAK,MAAMkJ,KAAUJ,EAAU,CAC3BuE,EAAgBjN,IAAI8I,GACpB,MAAMQ,EAAKX,EAAM7L,IAAIgM,EAAQI,GACvBK,EAAKZ,EAAM7L,IAAIgM,EAAQK,GAE7B,GAAKiD,EAAgBrM,IAAI+I,GAsBlB,CACH,MAAMoE,EAAOb,EAAYvP,IAAIgM,IACzBoE,GACCA,EAAK3H,WAAa+D,EAAG/D,UACrB2H,EAAKC,eAAiB7D,EAAG6D,cACzBD,EAAKE,gBAAkB9D,EAAG8D,eAC1BF,EAAKG,iBAAmB/D,EAAG+D,gBAC3BH,EAAKI,gBAAkBhE,EAAGgE,eAC1BJ,EAAKK,SAAWjE,EAAGiE,SACpB7V,EAAOwM,8BACH4E,EAAQQ,EAAG/D,SACX+D,EAAG6D,aAAc7D,EAAG8D,cAAe9D,EAAG+D,eACtC/D,EAAGgE,cAAgB,EAAI,EAAGhE,EAAGiE,OAAS,EAAI,GAE9CL,EAAK3H,SAAW+D,EAAG/D,SACnB2H,EAAKC,aAAe7D,EAAG6D,aACvBD,EAAKE,cAAgB9D,EAAG8D,cACxBF,EAAKG,eAAiB/D,EAAG+D,eACzBH,EAAKI,cAAgBhE,EAAGgE,cACxBJ,EAAKK,OAASjE,EAAGiE,OAEzB,KA3CkC,CAC9B,IAAKjE,EAAGnN,QAAS,SAEjB,MAAM8J,EAAQf,GAAaqE,EAAGI,eAE9BjS,EAAO2K,oBACHyG,EAAQQ,EAAG/D,SACXgE,EAAGE,cAAc3P,EAAI0S,EAAQjD,EAAGE,cAAc1P,EAAIyS,EAAQvG,EAC1DqD,EAAG6D,aAAc7D,EAAG8D,cAAe9D,EAAG+D,eACtC/D,EAAGgE,cAAgB,EAAI,EAAGhE,EAAGiE,OAAS,EAAI,GAG9CC,GAAkBpF,EAAK1Q,EAAQoR,EAAQ6C,KAAKG,QAAQI,qBACpDE,EAAgBpM,IAAI8I,GACpBuD,EAAYnT,IAAI4P,EAAQ,CACpBvD,SAAU+D,EAAG/D,SACb4H,aAAc7D,EAAG6D,aACjBC,cAAe9D,EAAG8D,cAClBC,eAAgB/D,EAAG+D,eACnBC,cAAehE,EAAGgE,cAClBC,OAAQjE,EAAGiE,QAEnB,CAuBA,GAAIjE,EAAG/D,WAAaC,EAASE,UAAW,CACpC,MAAMO,EAAQf,GAAaqE,EAAGI,eAC9BjS,EAAOkL,0BACHkG,EACAS,EAAGE,cAAc3P,EAAI0S,EAAQjD,EAAGE,cAAc1P,EAAIyS,EAClDvG,EAER,CACJ,CAEA,IAAK,MAAM6C,KAAUsD,EACZa,EAAgBlN,IAAI+I,KACrBpR,EAAO4K,qBAAqBwG,GAC5BsD,EAAgB1L,OAAOoI,GACvBuD,EAAY3L,OAAOoI,IAI3BpR,EAAOiL,cAAcqK,EAAKS,OA+EtD,SAA+BrF,EAAU1Q,EAA2B+Q,GAChE,MAAMiF,EAAQhW,EAAOmL,+BACrB,GAAc,IAAV6K,EAAa,OAEjB,MAAMC,EAAMjW,EAAOoL,oCACb8K,EAAUD,GAAO,EAEvB,IAAK,IAAI1P,EAAI,EAAGA,EAAIyP,EAAOzP,IAAK,CAC5B,MAAMgM,EAAS2D,EAAc,EAAJ3P,EACnB4P,EAAWnW,EAAO0M,QAAQ6F,GAC1B6D,EAASpW,EAAOuB,QAAQgR,EAAS,GAAKxB,EACtCsF,EAASrW,EAAOuB,QAAQgR,EAAS,GAAKxB,EACtCuF,EAAatW,EAAOuB,QAAQgR,EAAS,GAE3C,IAAK7B,EAAIO,MAAMsF,MAAMJ,GAAW,SAEhC,MAAMrR,EAAY4L,EAAIO,MAAM7L,IAAI+Q,EAAU1E,GAC1C,IAAK3M,EAAW,SAEhB,IAAI0R,EAASJ,EACTK,EAASJ,EACTK,EAAaJ,EAEjB,GAAI5F,EAAIO,MAAM5I,IAAI8N,EAAUQ,GAAS,CACjC,MAAMC,EAAalG,EAAIO,MAAM7L,IAAI+Q,EAAUQ,GAC3C,GAAIC,GAAclG,EAAIO,MAAMsF,MAAMK,EAAWxF,SAAWV,EAAIO,MAAM5I,IAAIuO,EAAWxF,OAAQK,GAAY,CACjG,MAAMoF,EAAMnG,EAAIO,MAAM7L,IAAIwR,EAAWxF,OAAQK,GACvCqF,EAActJ,GAAaqJ,EAAI5E,eAC/B8E,EAAKX,EAASS,EAAI9E,cAAc3P,EAChC4U,EAAKX,EAASQ,EAAI9E,cAAc1P,EAChCmM,EAAMd,KAAKc,KAAKsI,GAChBrI,EAAMf,KAAKe,KAAKqI,GAGtBN,GAAUO,EAAKvI,EAAMwI,EAAKvI,IAFM,IAArBoI,EAAII,WAAW7U,EAAUyU,EAAII,WAAW7U,EAAI,GAGvDqU,GAAUM,EAAKtI,EAAMuI,EAAKxI,IAFM,IAArBqI,EAAII,WAAW5U,EAAUwU,EAAII,WAAW5U,EAAI,GAGvDqU,EAAaJ,EAAaQ,CAC9B,CACJ,CAEAhS,EAAUvC,SAASH,EAAIoU,EACvB1R,EAAUvC,SAASF,EAAIoU,EACvB,MAAMhJ,EAAIoG,GAAa6C,GACvB5R,EAAUrB,SAASgD,EAAIgH,EAAEhH,EACzB3B,EAAUrB,SAASrB,EAAIqL,EAAErL,EACzB0C,EAAUrB,SAASpB,EAAIoL,EAAEpL,EACzByC,EAAUrB,SAAS+C,EAAIiH,EAAEjH,EAEzBkK,EAAIO,MAAMiG,OAAOf,EAAU1E,EAAW3M,EAC1C,CACJ,CA/H4BqS,CAAsBzG,EAAK1Q,EAAQ+Q,GAiI/D,SAAuBL,EAAU1Q,EAA2B+Q,GACxD/Q,EAAOqL,yBAEP,MAAM8H,EAAyC,GACzCiE,EAAapX,EAAOsL,kCAC1B,GAAI8L,EAAa,EAAG,CAChB,MAAMC,EAAWrX,EAAOuL,oCAAsC,EAC9D,IAAK,IAAIhF,EAAI,EAAGA,EAAI6Q,EAAY7Q,IAAK,CACjC,MAAM+Q,EAAOD,EAAe,EAAJ9Q,EACxB4M,EAAgBoE,KAAK,CACjBC,QAASxX,EAAO0M,QAAQ4K,GACxBG,QAASzX,EAAO0M,QAAQ4K,EAAO,GAC/BI,QAAS1X,EAAOuB,QAAQ+V,EAAO,GAC/BK,QAAS3X,EAAOuB,QAAQ+V,EAAO,GAC/BlE,SAAUpT,EAAOuB,QAAQ+V,EAAO,GAAKvG,EACrCsC,SAAUrT,EAAOuB,QAAQ+V,EAAO,GAAKvG,GAE7C,CACJ,CAEA,MAAM0C,EAA8D,GAC9DmE,EAAY5X,EAAOwL,iCACzB,GAAIoM,EAAY,EAAG,CACf,MAAMC,EAAU7X,EAAOyL,mCAAqC,EAC5D,IAAK,IAAIlF,EAAI,EAAGA,EAAIqR,EAAWrR,IAAK,CAChC,MAAM+Q,EAAOO,EAAc,EAAJtR,EACvBkN,EAAe8D,KAAK,CAChBC,QAASxX,EAAO0M,QAAQ4K,GACxBG,QAASzX,EAAO0M,QAAQ4K,EAAO,IAEvC,CACJ,CAEA,MAAM5D,EAA8B,GAC9BoE,EAAmB9X,EAAO0L,+BAChC,GAAIoM,EAAmB,EAAG,CACtB,MAAMC,EAAiB/X,EAAO2L,iCAAmC,EACjE,IAAK,IAAIpF,EAAI,EAAGA,EAAIuR,EAAkBvR,IAAK,CACvC,MAAM+Q,EAAOS,EAAqB,EAAJxR,EAC9BmN,EAAa6D,KAAK,CACdS,aAAchY,EAAO0M,QAAQ4K,GAC7BW,cAAejY,EAAO0M,QAAQ4K,EAAO,IAE7C,CACJ,CAEA,MAAM3D,EAA6B,GAC7BuE,EAAkBlY,EAAO4L,8BAC/B,GAAIsM,EAAkB,EAAG,CACrB,MAAMC,EAAgBnY,EAAO6L,gCAAkC,EAC/D,IAAK,IAAItF,EAAI,EAAGA,EAAI2R,EAAiB3R,IAAK,CACtC,MAAM+Q,EAAOa,EAAoB,EAAJ5R,EAC7BoN,EAAY4D,KAAK,CACbS,aAAchY,EAAO0M,QAAQ4K,GAC7BW,cAAejY,EAAO0M,QAAQ4K,EAAO,IAE7C,CACJ,CAEA5G,EAAI6C,eAAeC,GAAe,CAC9BL,kBACAM,iBACAC,eACAC,eAER,CAjM4ByE,CAAc1H,EAAK1Q,EAAQ+Q,IAE/B,CAAElL,KAAM,mBAIhB6K,EAAI2H,cAAgBrY,EACpB0Q,EAAI6C,eAAeK,GAAY0E,GAAQC,YAAYvY,IACnDsT,GAAsB5C,EAAKkD,GAAYJ,IACvC9C,EAAI8H,iBAAiBvE,KAAKG,QAAQE,iBAI1CM,EAAY6D,MAAO/W,IACfgF,QAAQgS,MAAM,4CAA6ChX,KAE/DgP,EAAIiI,mBAAqB/D,CAC7B,EAOJ,MAAMgE,GAAuB,GAE7B,SAASC,GAAqBC,EAAsBC,EAAkBC,GAClE,IAAKA,EAAY,OAAOD,EACxB,IAAK,IAAIxS,EAAI,EAAGA,EAAIqS,GAAsBrS,IACtC,GAAIuS,IAAkB,GAAKvS,EAAI,OAAOyS,EAAWzS,GAErD,OAAOwS,CACX,CAEA,SAASjD,GAAkBpF,EAAU1Q,EAA2BoR,EAAgB4H,GAC5E,MAAM/H,EAAQP,EAAIO,MAElB,GAAIA,EAAM5I,IAAI+I,EAAQc,GAAc,CAChC,MAAMC,EAAMlB,EAAM7L,IAAIgM,EAAQc,GACxB+G,EAAW9G,EAAI2G,cAAgB,EAC/BI,EAAOL,GAAqBI,EAAU9G,EAAI4G,UAAY,MAAQC,GAOpE,YANAhZ,EAAO8K,qBACHsG,EAAQe,EAAIQ,YAAYvQ,EAAG+P,EAAIQ,YAAYtQ,EAC3C8P,EAAII,OAAOnQ,EAAG+P,EAAII,OAAOlQ,EACzB8P,EAAIgH,QAAShH,EAAIiH,SAAUjH,EAAIkH,YAAalH,EAAIE,SAAW,EAAI,EAC/D4G,EAAUC,EAGlB,CAEA,GAAIjI,EAAM5I,IAAI+I,EAAQwB,GAAiB,CACnC,MAAM/P,EAASoO,EAAM7L,IAAIgM,EAAQwB,GAC3BqG,EAAWpW,EAAOiW,cAAgB,EAClCI,EAAOL,GAAqBI,EAAUpW,EAAOkW,UAAY,MAAQC,GAOvE,YANAhZ,EAAO+K,wBACHqG,EAAQvO,EAAOE,OACfF,EAAO0P,OAAOnQ,EAAGS,EAAO0P,OAAOlQ,EAC/BQ,EAAOsW,QAAStW,EAAOuW,SAAUvW,EAAOwW,YAAaxW,EAAOwP,SAAW,EAAI,EAC3E4G,EAAUC,EAGlB,CAEA,GAAIjI,EAAM5I,IAAI+I,EAAQyB,GAAkB,CACpC,MAAMC,EAAU7B,EAAM7L,IAAIgM,EAAQyB,GAC5BoG,EAAWnG,EAAQgG,cAAgB,EACnCI,EAAOL,GAAqBI,EAAUnG,EAAQiG,UAAY,MAAQC,GACxEhZ,EAAOgL,yBACHoG,EAAQ0B,EAAQ/P,OAAQ+P,EAAQhE,WAChCgE,EAAQP,OAAOnQ,EAAG0Q,EAAQP,OAAOlQ,EACjCyQ,EAAQqG,QAASrG,EAAQsG,SAAUtG,EAAQuG,YAAavG,EAAQT,SAAW,EAAI,EAC/E4G,EAAUC,EAElB,CACJ,OA6HaZ,GAGT,WAAAtE,CAAYtD,GAER,GADAuD,KAAKqF,QAAU5I,EAAI2H,eACdpE,KAAKqF,QACN,MAAM,IAAIzY,MAAM,oEAExB,CAGA,kBAAO0X,CAAYvY,GACf,MAAMuZ,EAAWhR,OAAOiR,OAAOlB,GAAQmB,WAEvC,OADAF,EAASD,QAAUtZ,EACZuZ,CACX,CAEA,UAAAG,CAAWtI,EAAgBuI,GACvB1F,KAAKqF,QAAQxN,oBAAoBsF,EAAQuI,EAAMvX,EAAGuX,EAAMtX,EAC5D,CAEA,YAAAuX,CAAaxI,EAAgByI,GACzB5F,KAAKqF,QAAQvN,sBAAsBqF,EAAQyI,EAAQzX,EAAGyX,EAAQxX,EAClE,CAEA,iBAAAyX,CAAkB1I,EAAgB2I,GAC9B9F,KAAKqF,QAAQtN,2BAA2BoF,EAAQ2I,EAAS3X,EAAG2X,EAAS1X,EACzE,CAEA,iBAAA2Q,CAAkB5B,GACd,MACMkG,EADMrD,KAAKqF,QAAQrN,2BAA2BmF,IAChC,EACpB,MAAO,CAAEhP,EAAG6R,KAAKqF,QAAQ/X,QAAQ+V,GAAOjV,EAAG4R,KAAKqF,QAAQ/X,QAAQ+V,EAAO,GAC3E,CAEA,UAAA0C,CAAW3F,GACPJ,KAAKqF,QAAQpN,oBAAoBmI,EAAQjS,EAAGiS,EAAQhS,EACxD,CAEA,UAAA4X,GACI,MACM3C,EADMrD,KAAKqF,QAAQnN,uBACL,EACpB,MAAO,CAAE/J,EAAG6R,KAAKqF,QAAQ/X,QAAQ+V,GAAOjV,EAAG4R,KAAKqF,QAAQ/X,QAAQ+V,EAAO,GAC3E,CAEA,kBAAA4C,CAAmB9I,EAAgB+I,GAC/BlG,KAAKqF,QAAQlN,4BAA4BgF,EAAQ+I,EACrD,CAEA,kBAAAC,CAAmBhJ,GACf,OAAO6C,KAAKqF,QAAQjN,4BAA4B+E,EACpD,CAEA,WAAAiJ,CAAYjJ,EAAgBkJ,GACxBrG,KAAKqF,QAAQhN,qBAAqB8E,EAAQkJ,EAC9C,CAEA,mBAAAC,CAAoBnJ,EAAgByI,GAChC5F,KAAKqF,QAAQ/M,6BAA6B6E,EAAQyI,EACtD,CAEA,mBAAOW,CAAa9J,EAAUjM,GAC1B,MAAMoM,EAASH,EAAII,YAAoCnE,GACnDkE,IACAA,EAAOpM,QAAUA,EACjBiM,EAAI6C,eAAe5G,EAAkBkE,GAE7C,CAEA,yBAAO4J,CAAmB/J,EAAUG,GAChC,MAAM6J,EAAUhK,EAAII,YAAoCnE,GACpD+N,GACAhK,EAAI6C,eAAe5G,EAAkB,IAAK+N,KAAY7J,GAE9D"}
\ No newline at end of file