Skip to content

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

feat: add collision layer system and skip physics in editor scene view

esengined622f2c7aa62
diff --git a/build-tools/tasks/sdk.js b/build-tools/tasks/sdk.js
index 89ca9a77f..6647a164e 100644
--- a/build-tools/tasks/sdk.js
+++ b/build-tools/tasks/sdk.js
@@ -1,5 +1,5 @@
import path from 'path';
-import { mkdir, cp, readFile, writeFile } from 'fs/promises';
+import { mkdir, cp, readFile, writeFile, readdir } from 'fs/promises';
import { existsSync } from 'fs';
import config from '../build.config.js';
import * as logger from '../utils/logger.js';
@@ -94,8 +94,10 @@ async function copyDistOutputs(sdkDir, outputDir) {
const spineDir = path.join(esmDir, 'spine');
const physicsDir = path.join(esmDir, 'physics');
+ const sharedDir = path.join(esmDir, 'shared');
await mkdir(spineDir, { recursive: true });
await mkdir(physicsDir, { recursive: true });
+ await mkdir(sharedDir, { recursive: true });
const files = [
{ src: 'index.js', dest: path.join(esmDir, 'esengine.js') },
@@ -117,6 +119,15 @@ async function copyDistOutputs(sdkDir, outputDir) {
logger.debug(`Copied ${src}`);
}
}
+
+ const srcSharedDir = path.join(distDir, 'shared');
+ if (existsSync(srcSharedDir)) {
+ const sharedFiles = await readdir(srcSharedDir);
+ for (const file of sharedFiles) {
+ await cp(path.join(srcSharedDir, file), path.join(sharedDir, file));
+ }
+ logger.debug(`Copied ${sharedFiles.length} shared chunks`);
+ }
}
export async function buildSdkDirect(format = 'all') {
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index c81a07414..a919bb913 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}),Ce=ne("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ee=ne("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),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}}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=>{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),Qr(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===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,Zr._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}}function Qr(e,t,s){const n=e.world;if(n.has(s,Te)){const e=n.get(s,Te);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Ce)){const e=n.get(s,Ce);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Ee)){const e=n.get(s,Ee);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class Zr{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(Zr.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 ea={nearest:0,linear:1},ta={repeat:0,clamp:1,mirror:2};function sa(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=ea[n.filterMode??"linear"]??1,a=ta[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 na(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 ia(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 oa(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]=sa(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=na(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=sa(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=sa(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,sa(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=sa(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=ia(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 ra(e,t,s){return{name:e,async setup(){await oa({...s,sceneData:t,sceneName:e})}}}async function aa(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(ra(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Es(t.world,n)}class la{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 ca="__preview__";const ua={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),ua.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 da;exports.LogLevel=void 0,(da=exports.LogLevel||(exports.LogLevel={}))[da.Debug=0]="Debug",da[da.Info=1]="Info",da[da.Warn=2]="Warn",da[da.Error=3]="Error";class ha{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 pa{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new ha)}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 fa=new pa;const ma={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},ga={Running:0,Paused:1,Completed:2,Cancelled:3},ya={None:0,Restart:1,PingPong:2};const _a=1.70158,xa=2.70158,wa=2.5949095;const ba=2*Math.PI/3,va=2*Math.PI/4.5;const Sa=7.5625,Pa=2.75;const Ma=1e-6;function Ta(e,t,s){switch(e){case ma.Linear:return t;case ma.EaseInQuad:return function(e){return e*e}(t);case ma.EaseOutQuad:return function(e){return e*(2-e)}(t);case ma.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case ma.EaseInCubic:return function(e){return e*e*e}(t);case ma.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case ma.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case ma.EaseInBack:return function(e){return xa*e*e*e-_a*e*e}(t);case ma.EaseOutBack:return function(e){const t=e-1;return 1+xa*t*t*t+_a*t*t}(t);case ma.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-wa)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+wa)+2)/2}(t);case ma.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*ba)}(t);case ma.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*ba)+1}(t);case ma.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*va)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*va)/2+1}(t);case ma.EaseOutBounce:return function(e){return e<1/Pa?Sa*e*e:e<2/Pa?Sa*(e-=1.5/Pa)*e+.75:e<2.5/Pa?Sa*(e-=2.25/Pa)*e+.9375:Sa*(e-=2.625/Pa)*e+.984375}(t);case ma.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)<Ma)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)<Ma)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 ma.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ca=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??ma.Linear,bezierPoints:null,state:ga.Running,loop:i?.loop??ya.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)===ga.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==ga.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=Ta(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==ya.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===ya.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=ga.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===ga.Running&&(t.state=ga.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===ga.Paused&&(t.state=ga.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=ga.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:ga.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 Ea{constructor(e){this.id=e}get state(){return Ca.getState(this.id)}bezier(e,t,s,n){return Ca.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Ea?Ca.setSequenceNext(this.id,e.id):Ca.setSequenceNextExternal(this.id,e),this}pause(){Ca.pause(this.id)}resume(){Ca.resume(this.id)}cancel(){Ca.cancel(this.id)}}class Aa{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 Ea?(Ca.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 Ra=null,Ia=null;function Fa(e,t){Ra=e,Ia=t,Ca.init(e,t)}function ka(){Ca.shutdown(),Ra=null,Ia=null}function Ba(){if(!Ra)throw new Error("Tween API not initialized");return Ra}function La(){if(!Ia)throw new Error("Tween API not initialized");return Ia}const Da={to(e,t,s,n,i,o){const r=Ba(),a=La(),l=o?.easing??ma.Linear,c=o?.delay??0,u=o?.loop??ya.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Aa(r,a,h)},value(e,t,s,n,i){const o=Ca.create(e,t,s,n,i);return new Ea(o)},cancel(e){Ba()._anim_cancelTween(La(),e.entity)},cancelAll(e){Ba()._anim_cancelAllTweens(La(),e)},update(e){Ba()._anim_updateTweens(La(),e),Ca.update(e)}};class Ua{constructor(){this.name="AnimationPlugin"}build(e){Fa(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Da.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Gt(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){ka()}}const Wa=new Ua;var za;exports.AttenuationModel=void 0,(za=exports.AttenuationModel||(exports.AttenuationModel={}))[za.Linear=0]="Linear",za[za.Inverse=1]="Inverse",za[za.Exponential=2]="Exponential";const $a={model:exports.AttenuationModel.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Oa(e,t=$a){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 Ha(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const Va=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}),Na=K("AudioListener",{enabled:!0});class ja{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([Na,ce]);for(const e of h){if(n.get(e,Na).enabled){const t=n.get(e,ce);i=t.position.x,u=t.position.y,d=!0;break}}const p=n.getEntitiesWithComponents([Va]);a.clear();for(const e of p){const t=n.get(e,Va);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=Oa(Math.sqrt(p*p+f*f),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=Ha(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 Xa=new ja;let Ya=null,Ga=null;function qa(e,t){Ya=e,Ga=t}function Ka(){Ya=null,Ga=null}const Ja={update(e){Ya&&Ga&&Ya.particle_update?.(Ga,e)},play(e){Ya&&Ga&&Ya.particle_play?.(Ga,e)},stop(e){Ya&&Ga&&Ya.particle_stop?.(Ga,e)},reset(e){Ya&&Ga&&Ya.particle_reset?.(Ga,e)},getAliveCount:e=>Ya?Ya.particle_getAliveCount?.(e)??0:0};class Qa{constructor(){this.name="ParticlePlugin"}build(e){qa(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(exports.Schedule.Update,mt([Fe(De)],e=>{Ja.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){Ka()}}const Za=new Qa,el=1e6;class tl{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:el,l=i?.valid?i.worldTop:el,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 sl=new tl;function nl(e,t){return e.toFixed(t)}function il(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class ol{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">${nl(e.fps,1)}</span> Frame: <span style="color:#d19a66">${nl(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>${il(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${nl(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 rl(){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 al=Ie(rl(),"Stats");const ll="StatsCollect";class cl{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 ul{constructor(e){this.name="Stats",this.collector_=new cl,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(al,rl());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new ol(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(al);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(ll),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:ll});e.addSystemToSchedule(exports.Schedule.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const dl=new ul;class hl{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 pl(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 fl=[Ji,co,_o,zo,Go,To,Qo,nr,cr,Vo,Fo,dr,mr,xr,vr,Er,Rr],ml=[...fl,Wa,Xa,Za,sl,On];function gl(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:ml,...t})}class yl{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 _l(e){return(t,s)=>(a(e,t).then(e=>{s(e.instance,e.module)}),{})}async function xl(e,t){try{return await e({instantiateWasm:_l(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=Ua,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=Na,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=ja,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=Va,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=ma,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=pa,exports.LoopMode=ya,exports.Material=Ft,exports.MaterialLoader=Ht,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ve,exports.Parent=fe,exports.Particle=Ja,exports.ParticleEasing=we,exports.ParticleEmitter=be,exports.ParticlePlugin=Qa,exports.Physics=Zr,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:ca,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(ca),this.loadPromise_=t.load(ca).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 la(this.baseUrl_);await s.prefetch(t);let i=null;const o=this.app_.spineInitPromise;if(o){i=(await o).controller.raw}await oa({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:i,sceneName:ca})}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(ca),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(ca),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=ua,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=al,exports.StatsCollector=cl,exports.StatsOverlay=ol,exports.StatsPlugin=ul,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=tl,exports.Time=De,exports.Toggle=$o,exports.TogglePlugin=Ho,exports.Transform=ae,exports.Tween=Da,exports.TweenHandle=Aa,exports.TweenState=ga,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=yl,exports.WebAssetProvider=la,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=Wa,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=Xa,exports.calculateAttenuation=Oa,exports.calculatePanning=Ha,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=ra,exports.createWebApp=gl,exports.debug=function(e,t,s){fa.debug(e,t,s)},exports.defaultFrameStats=rl,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){fa.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 fa},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){fa.info(e,t,s)},exports.initDrawAPI=Ys,exports.initGLDebugAPI=qn,exports.initGeometryAPI=dn,exports.initMaterialAPI=At,exports.initParticleAPI=qa,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 pl(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 pl(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new hl(n);await aa({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=aa,exports.initTilemapAPI=is,exports.initTweenAPI=Fa,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:_l("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=gl(a,{glContextHandle:c,getViewportSize:()=>({width:i.width,height:i.height})});e.runtimeConfig&&V(u,e.runtimeConfig);let d=null;e.spineFactory&&(d=await xl(e.spineFactory,"spine.wasm"));let h=null;e.physicsFactory&&(h=await xl(e.physicsFactory,"physics.wasm"));const p=new yl(n),f=[];for(const t of e.sceneNames){const e=await o(`scenes/${t}.json`);f.push({name:t,data:JSON.parse(e)})}await aa({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=oa,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=Za,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){fa.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=Ka,exports.shutdownPostProcessAPI=Pn,exports.shutdownRendererAPI=Xn,exports.shutdownTilemapAPI=os,exports.shutdownTweenAPI=ka,exports.sliderPlugin=cr,exports.spriteAnimatorSystemUpdate=Gt,exports.statsPlugin=dl,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=sl,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=fl,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){fa.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){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}`))}})})};
//# 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 892a4f4c6..db57ed307 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}),ut=De("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),dt=De("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),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}}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=>{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),gl(e,s,i),t.add(i),n.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===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,yl._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}}function gl(e,t,n){const s=e.world;if(s.has(n,ct)){const e=s.get(n,ct);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,ut)){const e=s.get(n,ut);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,dt)){const e=s.get(n,dt);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class yl{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(yl.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 _l={nearest:0,linear:1},wl={repeat:0,clamp:1,mirror:2};function xl(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=_l[s.filterMode??"linear"]??1,a=wl[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 bl(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 vl(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 Sl(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]=xl(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=bl(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=xl(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=xl(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,xl(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=xl(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=vl(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 Ml(e,t,n){return{name:e,async setup(){await Sl({...n,sceneData:t,sceneName:e})}}}async function Pl(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(Ml(t.name,t.data,i));n&&(o.setInitial(n),await o.load(n)),void 0!==s&&Is(t.world,s)}class Tl{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 Cl="__preview__";class El{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:Cl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Cl),this.loadPromise_=t.load(Cl).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 Tl(this.baseUrl_);await n.prefetch(t);let s=null;const i=this.app_.spineInitPromise;if(i){s=(await i).controller.raw}await Sl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:n,spineModule:s,sceneName:Cl})}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(Cl),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(Cl),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 Al={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),Al.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 Rl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Rl||(Rl={}));class Il{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Rl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,n=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Rl.Debug:console.debug(t,n);break;case Rl.Info:console.log(t,n);break;case Rl.Warn:console.warn(t,n);break;case Rl.Error:console.error(t,n)}}}class kl{constructor(){this.handlers_=[],this.minLevel_=Rl.Info,this.addHandler(new Il)}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(Rl.Debug,e,t,n)}info(e,t,n){this.log(Rl.Info,e,t,n)}warn(e,t,n){this.log(Rl.Warn,e,t,n)}error(e,t,n){this.log(Rl.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 Fl=new kl;function Bl(){return Fl}function zl(e){Fl.setMinLevel(e)}function Ul(e,t,n){Fl.debug(e,t,n)}function Wl(e,t,n){Fl.info(e,t,n)}function $l(e,t,n){Fl.warn(e,t,n)}function Dl(e,t,n){Fl.error(e,t,n)}const Ll={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},Ol={Running:0,Paused:1,Completed:2,Cancelled:3},Hl={None:0,Restart:1,PingPong:2};const jl=1.70158,Vl=2.70158,Nl=2.5949095;const Xl=2*Math.PI/3,Yl=2*Math.PI/4.5;const ql=7.5625,Gl=2.75;const Kl=1e-6;function Jl(e,t,n){switch(e){case Ll.Linear:return t;case Ll.EaseInQuad:return function(e){return e*e}(t);case Ll.EaseOutQuad:return function(e){return e*(2-e)}(t);case Ll.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Ll.EaseInCubic:return function(e){return e*e*e}(t);case Ll.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Ll.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Ll.EaseInBack:return function(e){return Vl*e*e*e-jl*e*e}(t);case Ll.EaseOutBack:return function(e){const t=e-1;return 1+Vl*t*t*t+jl*t*t}(t);case Ll.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Nl)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Nl)+2)/2}(t);case Ll.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Xl)}(t);case Ll.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Xl)+1}(t);case Ll.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Yl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Yl)/2+1}(t);case Ll.EaseOutBounce:return function(e){return e<1/Gl?ql*e*e:e<2/Gl?ql*(e-=1.5/Gl)*e+.75:e<2.5/Gl?ql*(e-=2.25/Gl)*e+.9375:ql*(e-=2.625/Gl)*e+.984375}(t);case Ll.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)<Kl)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)<Kl)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 Ll.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ql=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??Ll.Linear,bezierPoints:null,state:Ol.Running,loop:i?.loop??Hl.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)===Ol.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Ol.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=Jl(t.easing,n,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*s),n>=1){if(t.loop!==Hl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Hl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Ol.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Ol.Running&&(t.state=Ol.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Ol.Paused&&(t.state=Ol.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Ol.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Ol.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 Zl{constructor(e){this.id=e}get state(){return Ql.getState(this.id)}bezier(e,t,n,s){return Ql.setBezier(this.id,e,t,n,s),this}then(e){return e instanceof Zl?Ql.setSequenceNext(this.id,e.id):Ql.setSequenceNextExternal(this.id,e),this}pause(){Ql.pause(this.id)}resume(){Ql.resume(this.id)}cancel(){Ql.cancel(this.id)}}const ec={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 tc{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 Zl?(Ql.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 nc=null,sc=null;function ic(e,t){nc=e,sc=t,Ql.init(e,t)}function oc(){Ql.shutdown(),nc=null,sc=null}function rc(){if(!nc)throw new Error("Tween API not initialized");return nc}function ac(){if(!sc)throw new Error("Tween API not initialized");return sc}const lc={to(e,t,n,s,i,o){const r=rc(),a=ac(),l=o?.easing??Ll.Linear,c=o?.delay??0,u=o?.loop??Hl.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,n,s,i,l,c,u,d);return new tc(r,a,h)},value(e,t,n,s,i){const o=Ql.create(e,t,n,s,i);return new Zl(o)},cancel(e){rc()._anim_cancelTween(ac(),e.entity)},cancelAll(e){rc()._anim_cancelAllTweens(ac(),e)},update(e){rc()._anim_updateTweens(ac(),e),Ql.update(e)}};class cc{constructor(){this.name="AnimationPlugin"}build(e){ic(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{lc.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Xn(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){oc()}}const uc=new cc;var dc;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(dc||(dc={}));const hc={model:dc.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function fc(e,t=hc){const{model:n,refDistance:s,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(n){case dc.Linear:{const e=i-s;if(e<=0)return 1;a=1-(Math.min(Math.max(r,s),i)-s)/e;break}case dc.Inverse:a=s/Math.max(r,s);break;case dc.Exponential:a=Math.pow(Math.max(r,s)/s,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function pc(e,t,n,s,i){const o=e-n;return Math.max(-1,Math.min(1,o/i))}const mc=Ae("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:dc.Inverse,rolloff:1,priority:0,enabled:!0}),gc=Ae("AudioListener",{enabled:!0});class yc{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([gc,Ne]);for(const e of h){if(s.get(e,gc).enabled){const t=s.get(e,Ne);i=t.position.x,u=t.position.y,d=!0;break}}const f=s.getEntitiesWithComponents([mc]);a.clear();for(const e of f){const t=s.get(e,mc);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=fc(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=pc(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 _c=new yc;let wc=null,xc=null;function bc(e,t){wc=e,xc=t}function vc(){wc=null,xc=null}const Sc={update(e){wc&&xc&&wc.particle_update?.(xc,e)},play(e){wc&&xc&&wc.particle_play?.(xc,e)},stop(e){wc&&xc&&wc.particle_stop?.(xc,e)},reset(e){wc&&xc&&wc.particle_reset?.(xc,e)},getAliveCount:e=>wc?wc.particle_getAliveCount?.(e)??0:0};class Mc{constructor(){this.name="ParticlePlugin"}build(e){bc(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(sn.Update,an([mt(wt)],e=>{Sc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){vc()}}const Pc=new Mc,Tc=1e6;class Cc{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:Tc,l=i?.valid?i.worldTop:Tc,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 Ec=new Cc;function Ac(e,t){return e.toFixed(t)}function Rc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Ic{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">${Ac(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Ac(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>${Rc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Ac(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 kc(){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 Fc=pt(kc(),"Stats");class Bc{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 zc="StatsCollect";class Uc{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 Wc{constructor(e){this.name="Stats",this.collector_=new Uc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(Fc,kc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ic(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(Fc);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(zc),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:zc});e.addSystemToSchedule(sn.Last,s)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const $c=new Wc;class Dc{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 Lc(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 Oc(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 Lc(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 Lc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Dc(s);await Pl({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 Hc=[cr,Sr,Ir,ta,ua,Hr,pa,wa,Pa,oa,qr,Ca,Ia,Ua,Da,Na,Ya],jc=[...Hc,uc,_c,Pc,Ec,Gi];function Vc(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:jc,...t})}class Nc{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 Xc(e){return(t,n)=>(u(e,t).then(e=>{n(e.instance,e.module)}),{})}async function Yc(e,t){try{return await e({instantiateWasm:Xc(t)})}catch(e){return console.warn(`[ESEngine] Failed to load WASM module: ${t}`,e),null}}async function qc(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:Xc("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=Vc(a,{glContextHandle:u,getViewportSize:()=>({width:o.width,height:o.height})});e.runtimeConfig&&me(d,e.runtimeConfig);let h=null;e.spineFactory&&(h=await Yc(e.spineFactory,"spine.wasm"));let f=null;e.physicsFactory&&(f=await Yc(e.physicsFactory,"physics.wasm"));const p=new Nc(i),m=[];for(const t of e.sceneNames){const e=await l(`scenes/${t}.json`);m.push({name:t,data:JSON.parse(e)})}await Pl({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,cc as AnimationPlugin,go as App,zs as AssetPlugin,Ws as AssetRefCounter,Fs as AssetServer,Bs as Assets,Un as AsyncCache,dc as AttenuationModel,Yn as Audio,p as AudioBus,gc as AudioListener,m as AudioMixer,yc as AudioPlugin,g as AudioPool,mc 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,Ll 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,Bc 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,Rl as LogLevel,kl as Logger,Hl as LoopMode,Cn as Material,Wn as MaterialLoader,zt as Mut,it as Name,Ke as Parent,Sc as Particle,nt as ParticleEasing,st as ParticleEmitter,Mc as ParticlePlugin,yl 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,El 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,Al 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,Fc as Stats,Uc as StatsCollector,Ic as StatsOverlay,Wc 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,Cc as TilemapPlugin,wt as Time,na as Toggle,ia as TogglePlugin,je as Transform,lc as Tween,tc as TweenHandle,Ol as TweenState,ec 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,Nc as WeChatAssetProvider,Tl as WebAssetProvider,Bt as World,Ne as WorldTransform,un as addStartupSystem,cn as addSystem,dn as addSystemToSchedule,uc as animationPlugin,me as applyBuildRuntimeConfig,Lo as applyDirectionalFill,fe as applyRuntimeConfig,Us as assetPlugin,_c as audioPlugin,fc as calculateAttenuation,pc 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,Ml as createRuntimeSceneConfig,Vc as createWebApp,Ul as debug,kc as defaultFrameStats,Ae as defineComponent,Kt as defineEvent,pt as defineResource,an as defineSystem,Re as defineTag,pa as dragPlugin,Da as dropdownPlugin,Dl 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,Bl as getLogger,t as getPlatform,s as getPlatformType,Jn as getTextureDimensions,es as getTilemapSource,Ie as getUserComponent,B as getWeChatPackOptions,ta as imagePlugin,Wl as info,Zs as initDrawAPI,so as initGLDebugAPI,gi as initGeometryAPI,Mn as initMaterialAPI,bc as initParticleAPI,Oc as initPlayableRuntime,Ei as initPostProcessAPI,Zi as initRendererAPI,Pl as initRuntime,ss as initTilemapAPI,ic as initTweenAPI,qc 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,Sl as loadRuntimeScene,Cs as loadSceneData,Es as loadSceneWithAssets,gs as loadTiledMap,k as looksLikeAssetPath,Dn as parseAnimClipData,fs as parseTiledMap,ds as parseTmjJson,Pc 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,zl as setLogLevel,Wr as setPlayMode,Tt as setWasmErrorHandler,ei as shutdownDrawAPI,io as shutdownGLDebugAPI,yi as shutdownGeometryAPI,Pn as shutdownMaterialAPI,vc as shutdownParticleAPI,Ai as shutdownPostProcessAPI,eo as shutdownRendererAPI,is as shutdownTilemapAPI,oc as shutdownTweenAPI,Pa as sliderPlugin,Xn as spriteAnimatorSystemUpdate,$c as statsPlugin,qo as syncFillSpriteSize,Di as syncPostProcessVolume,qr as textInputPlugin,cr as textPlugin,Ec as tilemapPlugin,W as toBuildPath,oa as togglePlugin,qa as transitionTo,Hr as uiInteractionPlugin,Ir as uiLayoutPlugin,Sr as uiMaskPlugin,Hc 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,$l 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){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};
//# sourceMappingURL=index.wechat.js.map
diff --git a/desktop/public/sdk/esm/esengine.d.ts b/desktop/public/sdk/esm/esengine.d.ts
index f4b30376c..9ee8ab9aa 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -1,3 +1,10 @@
+import { a as Entity, E as ESEngineModule, C as Color, V as Vec2, c as CppRegistry, T as TextureHandle } from './shared/wasm.js';
+export { e as CppResourceManager, F as FontHandle, I as INVALID_ENTITY, f as INVALID_FONT, g as INVALID_MATERIAL, h as INVALID_TEXTURE, Q as Quat, b as Vec3, d as Vec4, i as color, q as quat, v as vec2, j as vec3, k as vec4 } from './shared/wasm.js';
+import { g as PostProcessStack, h as ShaderHandle, P as Plugin, A as App, R as ResourceDef, B as BuiltinComponentDef, W as World, C as ComponentDef, M as MaskProcessorFn, i as AssetServer, j as PrefabOverride, I as InstantiatePrefabResult, k as SceneData, e as SpineWasmModule, m as AddressableManifest, n as SceneConfig, o as BlendMode, p as MaterialHandle, q as WebAppOptions } from './shared/app.js';
+export { r as Added, s as AddedWrapper, t as AddressableAssetType, u as AddressableManifestAsset, v as AddressableManifestGroup, x as AddressableResultMap, y as AnyComponentDef, z as AssetBuildTransform, D as AssetBundle, E as AssetContentType, F as AssetFieldType, G as AssetTypeEntry, H as BitmapText, J as BitmapTextData, K as Camera, L as CameraData, N as CameraRenderParams, O as Canvas, Q as CanvasData, T as Changed, U as ChangedWrapper, V as Children, X as ChildrenData, Y as ClearFlags, Z as Commands, _ as CommandsDescriptor, $ as CommandsInstance, a0 as ComponentData, a1 as DrawCallback, a2 as EditorAssetType, a3 as EmitterShape, a4 as EntityCommands, a5 as EventDef, a6 as EventReader, a7 as EventReaderDescriptor, a8 as EventReaderInstance, a9 as EventRegistry, aa as EventWriter, ab as EventWriterDescriptor, ac as EventWriterInstance, ad as FileLoadOptions, ae as GetWorld, af as GetWorldDescriptor, ag as InferParam, ah as InferParams, ai as InstantiatePrefabOptions, aj as LoadedMaterial, ak as LocalTransform, al as LocalTransformData, am as Material, an as MaterialAssetData, ao as MaterialLoader, ap as MaterialOptions, aq as Mut, ar as MutWrapper, as as Name, at as NameData, au as Parent, av as ParentData, aw as ParticleEasing, ax as ParticleEmitter, ay as ParticleEmitterData, az as PluginDependency, aA as PostProcessVolume, aB as PostProcessVolumeData, aC as PrefabData, aD as PrefabEntityData, aE as ProjectionType, aF as Query, aG as QueryBuilder, aH as QueryDescriptor, aI as QueryInstance, aJ as QueryResult, aK as Removed, aL as RemovedQueryDescriptor, aM as RemovedQueryInstance, aN as RenderParams, aO as RenderPipeline, aP as Res, aQ as ResDescriptor, aR as ResMut, aS as ResMutDescriptor, aT as ResMutInstance, aU as ScaleMode, aV as SceneComponentData, aW as SceneContext, aX as SceneEntityData, aY as SceneLoadOptions, aZ as SceneManager, a_ as SceneManagerState, a$ as SceneOwner, b0 as SceneOwnerData, b1 as SceneStatus, b2 as Schedule, b3 as ShaderLoader, b4 as ShaderSources, b5 as SimulationSpace, b6 as SliceBorder, b7 as SpineAnimation, b8 as SpineAnimationData, b9 as SpineDescriptor, ba as SpineLoadResult, bb as SpineRendererFn, bc as Sprite, bd as SpriteData, be as SystemDef, bf as SystemOptions, bg as SystemParam, bh as SystemRunner, bi as TextureInfo, bj as TextureRef, bk as Time, bl as TimeData, bm as Transform, bn as TransformData, bo as TransitionOptions, bp as UniformValue, bq as Velocity, br as VelocityData, bs as WorldTransform, bt as WorldTransformData, bu as addStartupSystem, bv as addSystem, bw as addSystemToSchedule, bx as clearDrawCallbacks, by as clearUserComponents, bz as defineComponent, bA as defineEvent, bB as defineResource, bC as defineSystem, bD as defineTag, bE as findEntityByName, bF as flushPendingSystems, bG as getAddressableType, bH as getAddressableTypeByEditorType, bI as getAllAssetExtensions, bJ as getAssetBuildTransform, bK as getAssetMimeType, bL as getAssetTypeEntry, bM as getComponent, bN as getComponentAssetFieldDescriptors, bO as getComponentAssetFields, bP as getComponentDefaults, bQ as getComponentEntityFields, bR as getComponentSpineFieldDescriptor, bS as getCustomExtensions, bT as getEditorType, bU as getUserComponent, bV as getWeChatPackOptions, bW as initMaterialAPI, bX as instantiatePrefab, bY as isBuiltinComponent, bZ as isCustomExtension, b_ as isKnownAssetExtension, b$ as isTextureRef, c0 as loadComponent, c1 as loadSceneData, c2 as loadSceneWithAssets, c3 as looksLikeAssetPath, c4 as registerAssetBuildTransform, c5 as registerComponent, c6 as registerComponentAssetFields, c7 as registerComponentEntityFields, c8 as registerDrawCallback, c9 as registerMaterialCallback, ca as remapEntityFields, cb as shutdownMaterialAPI, cc as toBuildPath, cd as unregisterComponent, ce as unregisterDrawCallback, cf as updateCameraAspectRatio, cg as wrapSceneSystem } from './shared/app.js';
+import { PhysicsWasmModule } from './physics/index.js';
+export { BodyType, BoxCollider, BoxColliderData, CapsuleCollider, CapsuleColliderData, CircleCollider, CircleColliderData, CollisionEnterEvent, Physics, PhysicsEvents, PhysicsEventsData, PhysicsModuleFactory, PhysicsPlugin, PhysicsPluginConfig, RigidBody, RigidBodyData, SensorEvent, loadPhysicsModule } from './physics/index.js';
+
declare const DEFAULT_DESIGN_WIDTH = 1920;
declare const DEFAULT_DESIGN_HEIGHT = 1080;
declare const DEFAULT_PIXELS_PER_UNIT = 100;
@@ -62,379 +69,6 @@ declare function applyBuildRuntimeConfig(app: {
setMaxFixedSteps(v: number): void;
}, config: RuntimeBuildConfig): void;
-/**
- * @file types.ts
- * @brief Core type definitions for ESEngine SDK
- */
-type Entity = number;
-declare const INVALID_ENTITY: Entity;
-type TextureHandle = number;
-declare const INVALID_TEXTURE: TextureHandle;
-type FontHandle = number;
-declare const INVALID_FONT: FontHandle;
-declare const INVALID_MATERIAL = 0;
-interface Vec2 {
- x: number;
- y: number;
-}
-interface Vec3 {
- x: number;
- y: number;
- z: number;
-}
-interface Vec4 {
- x: number;
- y: number;
- z: number;
- w: number;
-}
-interface Quat {
- w: number;
- x: number;
- y: number;
- z: number;
-}
-interface Color {
- r: number;
- g: number;
- b: number;
- a: number;
-}
-declare const vec2: (x?: number, y?: number) => Vec2;
-declare const vec3: (x?: number, y?: number, z?: number) => Vec3;
-declare const vec4: (x?: number, y?: number, z?: number, w?: number) => Vec4;
-declare const color: (r?: number, g?: number, b?: number, a?: number) => Color;
-declare const quat: (w?: number, x?: number, y?: number, z?: number) => Quat;
-
-interface RigidBodyData {
- bodyType: number;
- gravityScale: number;
- linearDamping: number;
- angularDamping: number;
- fixedRotation: boolean;
- bullet: boolean;
- enabled: boolean;
-}
-interface BoxColliderData {
- halfExtents: Vec2;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CircleColliderData {
- radius: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CapsuleColliderData {
- radius: number;
- halfHeight: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-declare const RigidBody$1: BuiltinComponentDef<RigidBodyData>;
-declare const BoxCollider$1: BuiltinComponentDef<BoxColliderData>;
-declare const CircleCollider$1: BuiltinComponentDef<CircleColliderData>;
-declare const CapsuleCollider$1: BuiltinComponentDef<CapsuleColliderData>;
-declare const BodyType: {
- readonly Static: 0;
- readonly Kinematic: 1;
- readonly Dynamic: 2;
-};
-type BodyType = (typeof BodyType)[keyof typeof BodyType];
-
-/**
- * @file component.ts
- * @brief Component definition and builtin components
- */
-
-interface ComponentDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _default: T;
- readonly _builtin: false;
- create(data?: Partial<T>): T;
-}
-declare function defineComponent<T extends object>(name: string, defaults: T): ComponentDef<T>;
-declare function defineTag(name: string): ComponentDef<{}>;
-declare function getUserComponent(name: string): ComponentDef<any> | undefined;
-declare function clearUserComponents(): void;
-declare function unregisterComponent(name: string): void;
-interface BuiltinComponentDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _cppName: string;
- readonly _builtin: true;
- readonly _default: T;
-}
-type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
-declare function isBuiltinComponent(comp: AnyComponentDef): comp is BuiltinComponentDef<any>;
-declare function registerComponent(name: string, def: AnyComponentDef): void;
-declare function getComponent(name: string): AnyComponentDef | undefined;
-declare const ProjectionType: {
- readonly Perspective: 0;
- readonly Orthographic: 1;
-};
-type ProjectionType = (typeof ProjectionType)[keyof typeof ProjectionType];
-declare const ClearFlags: {
- readonly None: 0;
- readonly ColorOnly: 1;
- readonly DepthOnly: 2;
- readonly ColorAndDepth: 3;
-};
-type ClearFlags = (typeof ClearFlags)[keyof typeof ClearFlags];
-declare const ScaleMode: {
- readonly FixedWidth: 0;
- readonly FixedHeight: 1;
- readonly Expand: 2;
- readonly Shrink: 3;
- readonly Match: 4;
-};
-type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];
-interface TransformData {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
- worldPosition: Vec3;
- worldRotation: Quat;
- worldScale: Vec3;
-}
-type LocalTransformData = TransformData;
-type WorldTransformData = TransformData;
-interface SpriteData {
- texture: number;
- color: Color;
- size: Vec2;
- uvOffset: Vec2;
- uvScale: Vec2;
- layer: number;
- flipX: boolean;
- flipY: boolean;
- material: number;
- enabled: boolean;
-}
-interface CameraData {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- aspectRatio: number;
- isActive: boolean;
- priority: number;
- /** Editor-only: not synced to C++ Camera component, used for gizmo rendering */
- showFrustum: boolean;
- viewportX: number;
- viewportY: number;
- viewportW: number;
- viewportH: number;
- clearFlags: number;
-}
-interface CanvasData {
- designResolution: Vec2;
- pixelsPerUnit: number;
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: Color;
-}
-interface VelocityData {
- linear: Vec3;
- angular: Vec3;
-}
-interface ParentData {
- entity: Entity;
-}
-interface ChildrenData {
- entities: Entity[];
-}
-interface SpineAnimationData {
- skeletonPath: string;
- atlasPath: string;
- skin: string;
- animation: string;
- timeScale: number;
- loop: boolean;
- playing: boolean;
- flipX: boolean;
- flipY: boolean;
- color: Color;
- layer: number;
- skeletonScale: number;
- material: number;
- enabled: boolean;
-}
-interface BitmapTextData {
- text: string;
- color: Color;
- fontSize: number;
- align: number;
- spacing: number;
- layer: number;
- font: number;
- enabled: boolean;
-}
-interface NameData {
- value: string;
-}
-interface SceneOwnerData {
- scene: string;
- persistent: boolean;
-}
-declare const Transform$1: BuiltinComponentDef<TransformData>;
-declare const LocalTransform: BuiltinComponentDef<TransformData>;
-declare const WorldTransform: BuiltinComponentDef<TransformData>;
-declare const Sprite$1: BuiltinComponentDef<SpriteData>;
-declare const Camera$1: BuiltinComponentDef<CameraData>;
-declare const Canvas$1: BuiltinComponentDef<CanvasData>;
-declare const Velocity$1: BuiltinComponentDef<VelocityData>;
-declare const Parent$1: BuiltinComponentDef<ParentData>;
-declare const Children$1: BuiltinComponentDef<ChildrenData>;
-declare const BitmapText$1: BuiltinComponentDef<BitmapTextData>;
-declare const SpineAnimation$1: BuiltinComponentDef<SpineAnimationData>;
-declare const EmitterShape: {
- readonly Point: 0;
- readonly Circle: 1;
- readonly Rectangle: 2;
- readonly Cone: 3;
-};
-type EmitterShape = (typeof EmitterShape)[keyof typeof EmitterShape];
-declare const SimulationSpace: {
- readonly World: 0;
- readonly Local: 1;
-};
-type SimulationSpace = (typeof SimulationSpace)[keyof typeof SimulationSpace];
-declare const ParticleEasing: {
- readonly Linear: 0;
- readonly EaseIn: 1;
- readonly EaseOut: 2;
- readonly EaseInOut: 3;
-};
-type ParticleEasing = (typeof ParticleEasing)[keyof typeof ParticleEasing];
-interface ParticleEmitterData {
- rate: number;
- burstCount: number;
- burstInterval: number;
- duration: number;
- looping: boolean;
- playOnStart: boolean;
- maxParticles: number;
- lifetimeMin: number;
- lifetimeMax: number;
- shape: number;
- shapeRadius: number;
- shapeSize: Vec2;
- shapeAngle: number;
- speedMin: number;
- speedMax: number;
- angleSpreadMin: number;
- angleSpreadMax: number;
- startSizeMin: number;
- startSizeMax: number;
- endSizeMin: number;
- endSizeMax: number;
- sizeEasing: number;
- startColor: Color;
- endColor: Color;
- colorEasing: number;
- rotationMin: number;
- rotationMax: number;
- angularVelocityMin: number;
- angularVelocityMax: number;
- gravity: Vec2;
- damping: number;
- texture: number;
- spriteColumns: number;
- spriteRows: number;
- spriteFPS: number;
- spriteLoop: boolean;
- blendMode: number;
- layer: number;
- material: number;
- simulationSpace: number;
- enabled: boolean;
-}
-declare const ParticleEmitter$1: BuiltinComponentDef<ParticleEmitterData>;
-declare const Name: ComponentDef<NameData>;
-declare const SceneOwner: ComponentDef<SceneOwnerData>;
-interface PostProcessVolumeData$1 {
- effects: {
- type: string;
- enabled: boolean;
- uniforms: Record<string, number>;
- }[];
- isGlobal: boolean;
- shape: 'box' | 'sphere';
- size: {
- x: number;
- y: number;
- };
- priority: number;
- weight: number;
- blendDistance: number;
-}
-declare const PostProcessVolume: ComponentDef<PostProcessVolumeData$1>;
-
-type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
-declare function getComponentDefaults(typeName: string): Record<string, unknown> | null;
-
-/**
- * @file resource.ts
- * @brief Resource system for global singleton data
- */
-interface ResourceDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _default: T;
-}
-declare function defineResource<T>(defaultValue: T, name?: string): ResourceDef<T>;
-interface ResDescriptor<T> {
- readonly _type: 'res';
- readonly _resource: ResourceDef<T>;
-}
-interface ResMutDescriptor<T> {
- readonly _type: 'res_mut';
- readonly _resource: ResourceDef<T>;
-}
-declare function Res<T>(resource: ResourceDef<T>): ResDescriptor<T>;
-declare function ResMut<T>(resource: ResourceDef<T>): ResMutDescriptor<T>;
-declare class ResMutInstance<T> {
- private value_;
- private readonly setter_;
- constructor(value: T, setter: (v: T) => void);
- get(): T;
- set(value: T): void;
- modify(fn: (value: T) => void): void;
- /** @internal */
- updateValue(value: T): void;
-}
-declare class ResourceStorage {
- private resources_;
- private resMutPool_;
- insert<T>(resource: ResourceDef<T>, value: T): void;
- get<T>(resource: ResourceDef<T>): T;
- set<T>(resource: ResourceDef<T>, value: T): void;
- has<T>(resource: ResourceDef<T>): boolean;
- remove<T>(resource: ResourceDef<T>): void;
- getResMut<T>(resource: ResourceDef<T>): ResMutInstance<T>;
-}
-interface TimeData {
- delta: number;
- elapsed: number;
- frameCount: number;
-}
-declare const Time: ResourceDef<TimeData>;
-
declare const Storage: {
getString(key: string, defaultValue?: string): string | undefined;
setString(key: string, value: string): void;
@@ -449,1541 +83,6 @@ declare const Storage: {
clear(): void;
};
-/**
- * @file wasm.generated.ts
- * @brief ESEngine WASM Bindings TypeScript Definitions
- * @details Generated by EHT - DO NOT EDIT
- */
-
-interface UVec2 {
- x: number;
- y: number;
-}
-interface VectorEntity {
- size(): number;
- get(index: number): number;
- push_back(value: number): void;
- set(index: number, value: number): boolean;
- delete(): void;
-}
-interface UIRect$1 {
- anchorMin: Vec2;
- anchorMax: Vec2;
- offsetMin: Vec2;
- offsetMax: Vec2;
- size: Vec2;
- pivot: Vec2;
-}
-interface FlexItem {
- flexGrow: number;
- flexShrink: number;
- flexBasis: number;
- order: number;
-}
-interface BoxCollider {
- halfExtents: Vec2;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CircleCollider {
- radius: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CapsuleCollider {
- radius: number;
- halfHeight: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface ParticleEmitter {
- rate: number;
- burstCount: number;
- burstInterval: number;
- duration: number;
- looping: boolean;
- playOnStart: boolean;
- maxParticles: number;
- lifetimeMin: number;
- lifetimeMax: number;
- shape: number;
- shapeRadius: number;
- shapeSize: Vec2;
- shapeAngle: number;
- speedMin: number;
- speedMax: number;
- angleSpreadMin: number;
- angleSpreadMax: number;
- startSizeMin: number;
- startSizeMax: number;
- endSizeMin: number;
- endSizeMax: number;
- sizeEasing: number;
- startColor: Vec4;
- endColor: Vec4;
- colorEasing: number;
- rotationMin: number;
- rotationMax: number;
- angularVelocityMin: number;
- angularVelocityMax: number;
- gravity: Vec2;
- damping: number;
- texture: number;
- spriteColumns: number;
- spriteRows: number;
- spriteFPS: number;
- spriteLoop: boolean;
- blendMode: number;
- layer: number;
- material: number;
- simulationSpace: number;
- enabled: boolean;
-}
-interface Transform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
- worldPosition: Vec3;
- worldRotation: Quat;
- worldScale: Vec3;
-}
-interface Velocity {
- linear: Vec3;
- angular: Vec3;
-}
-interface SpineAnimation {
- skeletonPath: string;
- atlasPath: string;
- skin: string;
- animation: string;
- timeScale: number;
- loop: boolean;
- playing: boolean;
- flipX: boolean;
- flipY: boolean;
- color: Vec4;
- layer: number;
- skeletonScale: number;
- material: number;
- enabled: boolean;
-}
-interface Interactable$1 {
- enabled: boolean;
- blockRaycast: boolean;
- raycastTarget: boolean;
-}
-interface UIInteraction$1 {
- hovered: boolean;
- pressed: boolean;
- justPressed: boolean;
- justReleased: boolean;
-}
-interface RigidBody {
- bodyType: number;
- gravityScale: number;
- linearDamping: number;
- angularDamping: number;
- fixedRotation: boolean;
- bullet: boolean;
- enabled: boolean;
-}
-interface BitmapText {
- text: string;
- color: Vec4;
- fontSize: number;
- align: number;
- spacing: number;
- layer: number;
- font: number;
- enabled: boolean;
-}
-interface Sprite {
- texture: number;
- color: Vec4;
- size: Vec2;
- uvOffset: Vec2;
- uvScale: Vec2;
- layer: number;
- flipX: boolean;
- flipY: boolean;
- material: number;
- enabled: boolean;
-}
-interface UIMask$1 {
- enabled: boolean;
- mode: number;
-}
-interface FlexContainer {
- direction: number;
- wrap: number;
- justifyContent: number;
- alignItems: number;
- gap: Vec2;
- padding: Vec4;
-}
-interface Parent {
- entity: number;
-}
-interface Children {
- entities: VectorEntity;
-}
-interface ScreenSpace {
-}
-interface Canvas {
- designResolution: UVec2;
- pixelsPerUnit: number;
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: Vec4;
-}
-interface Camera {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- aspectRatio: number;
- isActive: boolean;
- priority: number;
- viewportX: number;
- viewportY: number;
- viewportW: number;
- viewportH: number;
- clearFlags: number;
-}
-interface Registry {
- create(): Entity;
- destroy(entity: Entity): void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- hasUIRect(entity: Entity): boolean;
- getUIRect(entity: Entity): UIRect$1;
- addUIRect(entity: Entity, component: UIRect$1): void;
- removeUIRect(entity: Entity): void;
- hasFlexItem(entity: Entity): boolean;
- getFlexItem(entity: Entity): FlexItem;
- addFlexItem(entity: Entity, component: FlexItem): void;
- removeFlexItem(entity: Entity): void;
- hasBoxCollider(entity: Entity): boolean;
- getBoxCollider(entity: Entity): BoxCollider;
- addBoxCollider(entity: Entity, component: BoxCollider): void;
- removeBoxCollider(entity: Entity): void;
- hasCircleCollider(entity: Entity): boolean;
- getCircleCollider(entity: Entity): CircleCollider;
- addCircleCollider(entity: Entity, component: CircleCollider): void;
- removeCircleCollider(entity: Entity): void;
- hasCapsuleCollider(entity: Entity): boolean;
- getCapsuleCollider(entity: Entity): CapsuleCollider;
- addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
- removeCapsuleCollider(entity: Entity): void;
- hasParticleEmitter(entity: Entity): boolean;
- getParticleEmitter(entity: Entity): ParticleEmitter;
- addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
- removeParticleEmitter(entity: Entity): void;
- hasTransform(entity: Entity): boolean;
- getTransform(entity: Entity): Transform;
- addTransform(entity: Entity, component: Transform): void;
- removeTransform(entity: Entity): void;
- hasVelocity(entity: Entity): boolean;
- getVelocity(entity: Entity): Velocity;
- addVelocity(entity: Entity, component: Velocity): void;
- removeVelocity(entity: Entity): void;
- hasSpineAnimation(entity: Entity): boolean;
- getSpineAnimation(entity: Entity): SpineAnimation;
- addSpineAnimation(entity: Entity, component: SpineAnimation): void;
- removeSpineAnimation(entity: Entity): void;
- hasInteractable(entity: Entity): boolean;
- getInteractable(entity: Entity): Interactable$1;
- addInteractable(entity: Entity, component: Interactable$1): void;
- removeInteractable(entity: Entity): void;
- hasUIInteraction(entity: Entity): boolean;
- getUIInteraction(entity: Entity): UIInteraction$1;
- addUIInteraction(entity: Entity, component: UIInteraction$1): void;
- removeUIInteraction(entity: Entity): void;
- hasRigidBody(entity: Entity): boolean;
- getRigidBody(entity: Entity): RigidBody;
- addRigidBody(entity: Entity, component: RigidBody): void;
- removeRigidBody(entity: Entity): void;
- hasBitmapText(entity: Entity): boolean;
- getBitmapText(entity: Entity): BitmapText;
- addBitmapText(entity: Entity, component: BitmapText): void;
- removeBitmapText(entity: Entity): void;
- hasSprite(entity: Entity): boolean;
- getSprite(entity: Entity): Sprite;
- addSprite(entity: Entity, component: Sprite): void;
- removeSprite(entity: Entity): void;
- hasUIMask(entity: Entity): boolean;
- getUIMask(entity: Entity): UIMask$1;
- addUIMask(entity: Entity, component: UIMask$1): void;
- removeUIMask(entity: Entity): void;
- hasFlexContainer(entity: Entity): boolean;
- getFlexContainer(entity: Entity): FlexContainer;
- addFlexContainer(entity: Entity, component: FlexContainer): void;
- removeFlexContainer(entity: Entity): void;
- hasParent(entity: Entity): boolean;
- getParent(entity: Entity): Parent;
- addParent(entity: Entity, component: Parent): void;
- removeParent(entity: Entity): void;
- hasChildren(entity: Entity): boolean;
- getChildren(entity: Entity): Children;
- addChildren(entity: Entity, component: Children): void;
- removeChildren(entity: Entity): void;
- hasScreenSpace(entity: Entity): boolean;
- getScreenSpace(entity: Entity): ScreenSpace;
- addScreenSpace(entity: Entity, component: ScreenSpace): void;
- removeScreenSpace(entity: Entity): void;
- hasCanvas(entity: Entity): boolean;
- getCanvas(entity: Entity): Canvas;
- addCanvas(entity: Entity, component: Canvas): void;
- removeCanvas(entity: Entity): void;
- hasCamera(entity: Entity): boolean;
- getCamera(entity: Entity): Camera;
- addCamera(entity: Entity, component: Camera): void;
- removeCamera(entity: Entity): void;
- setParent(child: Entity, parent: Entity): void;
-}
-
-/**
- * @file wasm.ts
- * @brief WASM module type definitions
- */
-
-interface CppRegistry extends Registry {
- delete(): void;
- removeParent(entity: Entity): void;
- [key: string]: Function | undefined;
-}
-interface CppResourceManager {
- createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
- createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
- createShader(vertSrc: string, fragSrc: string): number;
- registerExternalTexture(glTextureId: number, width: number, height: number): number;
- getTextureGLId(handle: number): number;
- releaseTexture(handle: number): void;
- releaseShader(handle: number): void;
- setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
- registerTextureWithPath(handle: number, path: string): void;
- loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
- createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
- releaseBitmapFont(handle: number): void;
- measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
- width: number;
- height: number;
- };
-}
-interface EmscriptenFS {
- writeFile(path: string, data: string | Uint8Array): void;
- readFile(path: string, opts?: {
- encoding?: string;
- }): string | Uint8Array;
- mkdir(path: string): void;
- mkdirTree(path: string): void;
- unlink(path: string): void;
- stat(path: string): {
- mode: number;
- size: number;
- };
- isFile(mode: number): boolean;
- isDir(mode: number): boolean;
- analyzePath(path: string): {
- exists: boolean;
- parentExists: boolean;
- };
-}
-interface SpineBounds {
- x: number;
- y: number;
- width: number;
- height: number;
- valid: boolean;
-}
-interface ESEngineModule {
- Registry: new () => CppRegistry;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- HEAPF32: Float32Array;
- FS: EmscriptenFS;
- materialDataProvider?: (materialId: number, outShaderIdPtr: number, outBlendModePtr: number, outUniformBufferPtr: number, outUniformCountPtr: number) => void;
- initRenderer(): void;
- initRendererWithCanvas(canvasSelector: string): boolean;
- initRendererWithContext(contextHandle: number): boolean;
- shutdownRenderer(): void;
- GL: {
- registerContext(ctx: WebGLRenderingContext | WebGL2RenderingContext, options: {
- majorVersion: number;
- minorVersion: number;
- enableExtensionsByDefault?: boolean;
- }): number;
- };
- renderFrame(registry: CppRegistry, width: number, height: number): void;
- renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;
- getResourceManager(): CppResourceManager;
- getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;
- invalidateMaterialCache(materialId: number): void;
- clearMaterialCache(): void;
- draw_begin(matrixPtr: number): void;
- draw_end(): void;
- draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_rect(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
- draw_rectOutline(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_circle(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
- draw_circleOutline(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
- draw_texture(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_textureRotated(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_setLayer(layer: number): void;
- draw_setDepth(depth: number): void;
- draw_getDrawCallCount(): number;
- draw_getPrimitiveCount(): number;
- draw_setBlendMode(mode: number): void;
- draw_setDepthTest(enabled: boolean): void;
- draw_mesh(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
- draw_meshWithUniforms(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
- geometry_create(): number;
- geometry_init(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
- geometry_setIndices16(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_setIndices32(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_updateVertices(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
- geometry_release(handle: number): void;
- geometry_isValid(handle: number): boolean;
- postprocess_init(width: number, height: number): boolean;
- postprocess_shutdown(): void;
- postprocess_resize(width: number, height: number): void;
- postprocess_addPass(name: string, shaderHandle: number): number;
- postprocess_removePass(name: string): void;
- postprocess_setPassEnabled(name: string, enabled: boolean): void;
- postprocess_isPassEnabled(name: string): boolean;
- postprocess_setUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- postprocess_begin(): void;
- postprocess_end(): void;
- postprocess_getPassCount(): number;
- postprocess_isInitialized(): boolean;
- postprocess_setBypass(bypass: boolean): void;
- postprocess_isBypassed(): boolean;
- postprocess_clearPasses(): void;
- postprocess_setOutputTarget(fboId: number): void;
- postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
- postprocess_beginScreenCapture(): void;
- postprocess_endScreenCapture(): void;
- postprocess_executeScreenPasses(): void;
- postprocess_addScreenPass(name: string, shaderHandle: number): number;
- postprocess_clearScreenPasses(): void;
- postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- renderer_init(width: number, height: number): void;
- renderer_resize(width: number, height: number): void;
- renderer_begin(matrixPtr: number, targetHandle: number): void;
- renderer_flush(): void;
- renderer_end(): void;
- renderer_submitSprites(registry: CppRegistry): void;
- renderer_submitBitmapText(registry: CppRegistry): void;
- renderer_submitSpine?(registry: CppRegistry): void;
- renderer_submitParticles?(registry: CppRegistry): void;
- renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
- particle_update?(registry: CppRegistry, dt: number): void;
- particle_play?(registry: CppRegistry, entity: number): void;
- particle_stop?(registry: CppRegistry, entity: number): void;
- particle_reset?(registry: CppRegistry, entity: number): void;
- particle_getAliveCount?(entity: number): number;
- tilemap_initLayer?(entity: number, width: number, height: number, tileWidth: number, tileHeight: number): void;
- tilemap_destroyLayer?(entity: number): void;
- tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
- tilemap_getTile?(entity: number, x: number, y: number): number;
- tilemap_fillRect?(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
- tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
- tilemap_hasLayer?(entity: number): boolean;
- tilemap_submitLayer?(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- renderer_setStage(stage: number): void;
- renderer_createTarget(width: number, height: number, flags: number): number;
- renderer_releaseTarget(handle: number): void;
- renderer_getTargetTexture(handle: number): number;
- renderer_getTargetDepthTexture(handle: number): number;
- renderer_getDrawCalls(): number;
- renderer_getTriangles(): number;
- renderer_getSprites(): number;
- renderer_getText(): number;
- renderer_getSpine?(): number;
- renderer_getMeshes(): number;
- renderer_getCulled(): number;
- renderer_setClearColor(r: number, g: number, b: number, a: number): void;
- renderer_setViewport(x: number, y: number, w: number, h: number): void;
- renderer_setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
- renderer_clearBuffers(flags: number): void;
- renderer_setEntityClipRect(entity: number, x: number, y: number, w: number, h: number): void;
- renderer_clearEntityClipRect(entity: number): void;
- renderer_clearAllClipRects(): void;
- renderer_clearStencil(): void;
- renderer_setEntityStencilMask(entity: number, refValue: number): void;
- renderer_setEntityStencilTest(entity: number, refValue: number): void;
- renderer_clearEntityStencilMask(entity: number): void;
- renderer_clearAllStencilMasks(): void;
- registry_getCanvasEntity(registry: CppRegistry): number;
- registry_getCameraEntities(registry: CppRegistry): number[];
- getChildEntities(registry: CppRegistry, entity: number): number[];
- registry_getGeneration(registry: CppRegistry, entity: number): number;
- registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;
- gl_enableErrorCheck(enabled: boolean): void;
- gl_checkErrors(context: string): number;
- renderer_diagnose(): void;
- uiLayout_update(registry: CppRegistry, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
- uiHitTest_getHitEntity(): number;
- uiHitTest_getHitEntityPrev(): number;
- uiRenderOrder_update(registry: CppRegistry): void;
- uiFlexLayout_update(registry: CppRegistry): void;
- getUIRectComputedWidth(registry: CppRegistry, entity: number): number;
- getUIRectComputedHeight(registry: CppRegistry, entity: number): number;
- transform_update(registry: CppRegistry): void;
- _anim_createTween(registry: CppRegistry, entity: number, targetProp: number, from: number, to: number, duration: number, easing: number, delay: number, loopMode: number, loopCount: number): number;
- _anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
- _anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_setTweenBezier(registry: CppRegistry, tweenEntity: number, p1x: number, p1y: number, p2x: number, p2y: number): void;
- _anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
- _anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
- _anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-
-/**
- * @file world.ts
- * @brief ECS World with C++ Registry integration
- */
-
-declare class World {
- private cppRegistry_;
- private module_;
- private entities_;
- private tsStorage_;
- private entityComponents_;
- private queryPool_;
- private queryPoolIdx_;
- private worldVersion_;
- private queryCache_;
- private builtinMethodCache_;
- private iterationDepth_;
- private nextEntityId_;
- private nextGeneration_;
- private spawnCallbacks_;
- private despawnCallbacks_;
- private worldTick_;
- private componentAddedTicks_;
- private componentChangedTicks_;
- private componentRemovedBuffer_;
- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void;
- disconnectCpp(): void;
- get hasCpp(): boolean;
- getCppRegistry(): CppRegistry | null;
- spawn(): Entity;
- despawn(entity: Entity): void;
- onSpawn(callback: (entity: Entity) => void): () => void;
- onDespawn(callback: (entity: Entity) => void): () => void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- getWorldVersion(): number;
- beginIteration(): void;
- endIteration(): void;
- resetIterationDepth(): void;
- isIterating(): boolean;
- getAllEntities(): Entity[];
- setParent(child: Entity, parent: Entity): void;
- removeParent(entity: Entity): void;
- insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
- set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
- get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
- has(entity: Entity, component: AnyComponentDef): boolean;
- tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null;
- remove(entity: Entity, component: AnyComponentDef): void;
- private getBuiltinMethods;
- private insertBuiltin;
- private getBuiltin;
- private hasBuiltin;
- private removeBuiltin;
- private insertScript;
- private getScript;
- private hasScript;
- private removeScript;
- private getStorage;
- resetQueryPool(): void;
- getComponentTypes(entity: Entity): string[];
- getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string): Entity[];
- advanceTick(): void;
- getWorldTick(): number;
- isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
- isChangedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
- getRemovedEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[];
- cleanRemovedBuffer(beforeTick: number): void;
- private recordAddedTick_;
- private recordChangedTick_;
- private recordRemovedTick_;
-}
-
-/**
- * @file query.ts
- * @brief Component query system with mutable component support
- */
-
-interface MutWrapper<T extends AnyComponentDef> {
- readonly _type: 'mut';
- readonly _component: T;
-}
-declare function Mut<T extends AnyComponentDef>(component: T): MutWrapper<T>;
-interface AddedWrapper<T extends AnyComponentDef> {
- readonly _filterType: 'added';
- readonly _component: T;
-}
-interface ChangedWrapper<T extends AnyComponentDef> {
- readonly _filterType: 'changed';
- readonly _component: T;
-}
-declare function Added<T extends AnyComponentDef>(component: T): AddedWrapper<T>;
-declare function Changed<T extends AnyComponentDef>(component: T): ChangedWrapper<T>;
-type QueryArg$1 = AnyComponentDef | MutWrapper<AnyComponentDef> | AddedWrapper<AnyComponentDef> | ChangedWrapper<AnyComponentDef>;
-interface QueryDescriptor<C extends readonly QueryArg$1[]> {
- readonly _type: 'query';
- readonly _components: C;
- readonly _mutIndices: number[];
- readonly _with: AnyComponentDef[];
- readonly _without: AnyComponentDef[];
- readonly _addedFilters: Array<{
- index: number;
- component: AnyComponentDef;
- }>;
- readonly _changedFilters: Array<{
- index: number;
- component: AnyComponentDef;
- }>;
-}
-interface QueryBuilder<C extends readonly QueryArg$1[]> extends QueryDescriptor<C> {
- with(...components: AnyComponentDef[]): QueryBuilder<C>;
- without(...components: AnyComponentDef[]): QueryBuilder<C>;
-}
-declare function Query<C extends QueryArg$1[]>(...components: C): QueryBuilder<C>;
-type UnwrapQueryArg<T> = T extends MutWrapper<infer C> ? C : T extends AddedWrapper<infer C> ? C : T extends ChangedWrapper<infer C> ? C : T;
-type ComponentsData<C extends readonly QueryArg$1[]> = {
- [K in keyof C]: ComponentData<UnwrapQueryArg<C[K]>>;
-};
-type QueryResult<C extends readonly QueryArg$1[]> = [
- Entity,
- ...ComponentsData<C>
-];
-declare class QueryInstance<C extends readonly QueryArg$1[]> implements Iterable<QueryResult<C>> {
- private readonly world_;
- private readonly descriptor_;
- private readonly actualComponents_;
- private readonly allRequired_;
- private readonly result_;
- private readonly mutData_;
- private readonly cacheKey_;
- private readonly lastRunTick_;
- constructor(world: World, descriptor: QueryDescriptor<C>, lastRunTick?: number);
- private passesChangeFilters_;
- [Symbol.iterator](): Iterator<QueryResult<C>>;
- forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void;
- single(): QueryResult<C> | null;
- isEmpty(): boolean;
- count(): number;
- toArray(): QueryResult<C>[];
-}
-interface RemovedQueryDescriptor<T extends AnyComponentDef> {
- readonly _type: 'removed';
- readonly _component: T;
-}
-declare function Removed<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>;
-declare class RemovedQueryInstance<T extends AnyComponentDef> implements Iterable<Entity> {
- private readonly world_;
- private readonly component_;
- private readonly lastRunTick_;
- constructor(world: World, component: T, lastRunTick: number);
- [Symbol.iterator](): Iterator<Entity>;
- isEmpty(): boolean;
- toArray(): Entity[];
-}
-
-/**
- * @file commands.ts
- * @brief Deferred entity/component operations
- */
-
-interface CommandsDescriptor {
- readonly _type: 'commands';
-}
-declare function Commands(): CommandsDescriptor;
-interface SpawnComponentEntry {
- component: AnyComponentDef;
- data: unknown;
-}
-declare class EntityCommands {
- private readonly commands_;
- private readonly entityRef_;
- private readonly components_;
- private isNew_;
- constructor(commands: CommandsInstance, entity: Entity | null);
- insert<T extends object>(component: AnyComponentDef, data?: Partial<T>): this;
- remove(component: AnyComponentDef): this;
- id(): Entity;
- finalize(): void;
-}
-declare class CommandsInstance {
- private readonly world_;
- private readonly resources_;
- private pending_;
- private spawned_;
- constructor(world: World, resources: ResourceStorage);
- spawn(): EntityCommands;
- entity(entity: Entity): EntityCommands;
- despawn(entity: Entity): this;
- insertResource<T>(resource: ResourceDef<T>, value: T): this;
- queueInsert(entity: Entity, component: AnyComponentDef, data: unknown): void;
- queueRemove(entity: Entity, component: AnyComponentDef): void;
- spawnImmediate(components: SpawnComponentEntry[], entityRef: {
- entity: Entity;
- }): void;
- flush(): void;
- private executeCommand;
-}
-
-/**
- * @file event.ts
- * @brief Event system with double-buffered event buses
- */
-interface EventDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _phantom?: T;
-}
-declare function defineEvent<T>(name: string): EventDef<T>;
-declare class EventBus<T> {
- private readBuffer_;
- private writeBuffer_;
- send(event: T): void;
- getReadBuffer(): readonly T[];
- swap(): void;
-}
-declare class EventRegistry {
- private readonly buses_;
- register<T>(event: EventDef<T>): void;
- getBus<T>(event: EventDef<T>): EventBus<T>;
- swapAll(): void;
-}
-interface EventWriterDescriptor<T> {
- readonly _type: 'event_writer';
- readonly _event: EventDef<T>;
-}
-interface EventReaderDescriptor<T> {
- readonly _type: 'event_reader';
- readonly _event: EventDef<T>;
-}
-declare function EventWriter<T>(event: EventDef<T>): EventWriterDescriptor<T>;
-declare function EventReader<T>(event: EventDef<T>): EventReaderDescriptor<T>;
-declare class EventWriterInstance<T> {
- private readonly bus_;
- constructor(bus: EventBus<T>);
- send(event: T): void;
-}
-declare class EventReaderInstance<T> implements Iterable<T> {
- private readonly bus_;
- constructor(bus: EventBus<T>);
- [Symbol.iterator](): Iterator<T>;
- isEmpty(): boolean;
- toArray(): T[];
-}
-
-/**
- * @file system.ts
- * @brief System definition and scheduling
- */
-
-declare enum Schedule {
- Startup = 0,
- First = 1,
- PreUpdate = 2,
- Update = 3,
- PostUpdate = 4,
- Last = 5,
- FixedPreUpdate = 10,
- FixedUpdate = 11,
- FixedPostUpdate = 12
-}
-interface GetWorldDescriptor {
- readonly _type: 'get_world';
-}
-declare function GetWorld(): GetWorldDescriptor;
-type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
-type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
-type InferParam<P> = P extends QueryDescriptor<infer C> ? QueryInstance<C> : P extends ResDescriptor<infer T> ? T : P extends ResMutDescriptor<infer T> ? ResMutInstance<T> : P extends CommandsDescriptor ? CommandsInstance : P extends EventWriterDescriptor<infer T> ? EventWriterInstance<T> : P extends EventReaderDescriptor<infer T> ? EventReaderInstance<T> : P extends RemovedQueryDescriptor<infer _T> ? RemovedQueryInstance<_T> : P extends GetWorldDescriptor ? World : never;
-type InferParams<P extends readonly SystemParam[]> = {
- [K in keyof P]: InferParam<P[K]>;
-};
-interface SystemDef {
- readonly _id: symbol;
- readonly _params: readonly SystemParam[];
- readonly _fn: (...args: never[]) => void;
- readonly _name: string;
-}
-interface SystemOptions {
- name?: string;
- runBefore?: string[];
- runAfter?: string[];
-}
-declare function defineSystem<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void, options?: SystemOptions): SystemDef;
-declare function addSystem(system: SystemDef): void;
-declare function addStartupSystem(system: SystemDef): void;
-declare function addSystemToSchedule(schedule: Schedule, system: SystemDef): void;
-declare class SystemRunner {
- private readonly world_;
- private readonly resources_;
- private readonly eventRegistry_;
- private readonly argsCache_;
- private readonly systemTicks_;
- private currentLastRunTick_;
- private timings_;
- constructor(world: World, resources: ResourceStorage, eventRegistry?: EventRegistry);
- setTimingEnabled(enabled: boolean): void;
- getTimings(): ReadonlyMap<string, number> | null;
- run(system: SystemDef): void;
- private resolveParam;
-}
-
-/**
- * @file renderPipeline.ts
- * @brief Unified render pipeline for runtime and editor
- */
-
-interface RenderParams {
- registry: {
- _cpp: CppRegistry;
- };
- viewProjection: Float32Array;
- width: number;
- height: number;
- elapsed: number;
-}
-interface CameraRenderParams {
- registry: {
- _cpp: CppRegistry;
- };
- viewProjection: Float32Array;
- viewportPixels: {
- x: number;
- y: number;
- w: number;
- h: number;
- };
- clearFlags: number;
- elapsed: number;
- cameraEntity?: Entity;
-}
-type SpineRendererFn = (registry: {
- _cpp: CppRegistry;
-}, elapsed: number) => void;
-type TilemapRendererFn = () => void;
-type MaskProcessorFn = (registry: CppRegistry, vp: Float32Array, viewportX: number, viewportY: number, viewportW: number, viewportH: number) => void;
-declare class RenderPipeline {
- private spineRenderer_;
- private tilemapRenderer_;
- private maskProcessor_;
- private lastWidth_;
- private lastHeight_;
- private activeScenes_;
- get spineRenderer(): SpineRendererFn | null;
- setSpineRenderer(fn: SpineRendererFn | null): void;
- setTilemapRenderer(fn: TilemapRendererFn | null): void;
- get maskProcessor(): MaskProcessorFn | null;
- setMaskProcessor(fn: MaskProcessorFn | null): void;
- setActiveScenes(scenes: Set<string> | null): void;
- beginScreenCapture(): void;
- endScreenCapture(): void;
- render(params: RenderParams): void;
- renderCamera(params: CameraRenderParams): void;
- private executeDrawCallbacks;
-}
-
-/**
- * @file blend.ts
- * @brief Blend mode definitions for rendering
- */
-declare enum BlendMode {
- Normal = 0,
- Additive = 1,
- Multiply = 2,
- Screen = 3,
- PremultipliedAlpha = 4
-}
-
-/**
- * @file material.ts
- * @brief Material and Shader API for custom rendering
- * @details Provides shader creation and material management for custom visual effects.
- */
-
-type ShaderHandle = number;
-type MaterialHandle = number;
-interface TextureRef {
- __textureRef: true;
- textureId: number;
- slot?: number;
-}
-type UniformValue = number | Vec2 | Vec3 | Vec4 | number[] | TextureRef;
-declare function isTextureRef(v: UniformValue): v is TextureRef;
-interface MaterialOptions {
- shader: ShaderHandle;
- uniforms?: Record<string, UniformValue>;
- blendMode?: BlendMode;
- depthTest?: boolean;
-}
-interface MaterialAssetData {
- version: string;
- type: 'material';
- shader: string;
- blendMode: number;
- depthTest: boolean;
- properties: Record<string, unknown>;
-}
-interface MaterialData {
- shader: ShaderHandle;
- uniforms: Map<string, UniformValue>;
- blendMode: BlendMode;
- depthTest: boolean;
- dirty_: boolean;
- cachedBuffer_: Float32Array | null;
- cachedIdx_: number;
-}
-declare function initMaterialAPI(wasmModule: ESEngineModule): void;
-declare function shutdownMaterialAPI(): void;
-declare const Material: {
- /**
- * Creates a shader from vertex and fragment source code.
- * @param vertexSrc GLSL vertex shader source
- * @param fragmentSrc GLSL fragment shader source
- * @returns Shader handle, or 0 on failure
- */
- createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle;
- /**
- * Releases a shader.
- * @param shader Shader handle to release
- */
- releaseShader(shader: ShaderHandle): void;
- /**
- * Creates a material with a shader and optional settings.
- * @param options Material creation options
- * @returns Material handle
- */
- create(options: MaterialOptions): MaterialHandle;
- /**
- * Gets material data by handle.
- * @param material Material handle
- * @returns Material data or undefined
- */
- get(material: MaterialHandle): MaterialData | undefined;
- /**
- * Sets a uniform value on a material.
- * @param material Material handle
- * @param name Uniform name
- * @param value Uniform value
- */
- setUniform(material: MaterialHandle, name: string, value: UniformValue): void;
- /**
- * Gets a uniform value from a material.
- * @param material Material handle
- * @param name Uniform name
- * @returns Uniform value or undefined
- */
- getUniform(material: MaterialHandle, name: string): UniformValue | undefined;
- /**
- * Sets the blend mode for a material.
- * @param material Material handle
- * @param mode Blend mode
- */
- setBlendMode(material: MaterialHandle, mode: BlendMode): void;
- /**
- * Gets the blend mode of a material.
- * @param material Material handle
- * @returns Blend mode
- */
- getBlendMode(material: MaterialHandle): BlendMode;
- /**
- * Sets depth test enabled for a material.
- * @param material Material handle
- * @param enabled Whether depth test is enabled
- */
- setDepthTest(material: MaterialHandle, enabled: boolean): void;
- /**
- * Gets the shader handle for a material.
- * @param material Material handle
- * @returns Shader handle
- */
- getShader(material: MaterialHandle): ShaderHandle;
- /**
- * Releases a material (does not release the shader).
- * @param material Material handle
- */
- release(material: MaterialHandle): void;
- /**
- * Checks if a material exists.
- * @param material Material handle
- * @returns True if material exists
- */
- isValid(material: MaterialHandle): boolean;
- releaseAll(): void;
- /**
- * Creates a material from asset data.
- * @param data Material asset data (properties object)
- * @param shaderHandle Pre-loaded shader handle
- * @returns Material handle
- */
- createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle): MaterialHandle;
- /**
- * Creates a material instance that shares the shader with source.
- * @param source Source material handle
- * @returns New material handle with copied settings
- */
- createInstance(source: MaterialHandle): MaterialHandle;
- /**
- * Exports material to serializable asset data.
- * @param material Material handle
- * @param shaderPath Shader file path for asset reference
- * @returns Material asset data
- */
- toAssetData(material: MaterialHandle, shaderPath: string): MaterialAssetData | null;
- /**
- * Gets all uniforms from a material.
- * @param material Material handle
- * @returns Map of uniform names to values
- */
- getUniforms(material: MaterialHandle): Map<string, UniformValue>;
- tex(textureId: number, slot?: number): TextureRef;
-};
-declare function registerMaterialCallback(): void;
-declare const ShaderSources: {
- SPRITE_VERTEX: string;
- SPRITE_FRAGMENT: string;
- COLOR_VERTEX: string;
- COLOR_FRAGMENT: string;
-};
-
-/**
- * @file MaterialLoader.ts
- * @brief Material asset loading and caching
- */
-
-interface LoadedMaterial {
- handle: MaterialHandle;
- shaderHandle: ShaderHandle;
- path: string;
-}
-interface ShaderLoader {
- load(path: string): Promise<ShaderHandle>;
- get(path: string): ShaderHandle | undefined;
-}
-declare class MaterialLoader {
- private cache_;
- private shaderLoader_;
- private basePath_;
- constructor(shaderLoader: ShaderLoader, basePath?: string);
- load(path: string): Promise<LoadedMaterial>;
- get(path: string): LoadedMaterial | undefined;
- has(path: string): boolean;
- release(path: string): void;
- releaseAll(): void;
- private loadInternal;
- private resolvePath;
- private resolveShaderPath;
-}
-
-interface PrefabData {
- version: string;
- name: string;
- rootEntityId: number;
- entities: PrefabEntityData[];
-}
-interface PrefabEntityData {
- prefabEntityId: number;
- name: string;
- parent: number | null;
- children: number[];
- components: {
- type: string;
- data: Record<string, unknown>;
- }[];
- visible: boolean;
- nestedPrefab?: {
- prefabPath: string;
- overrides: PrefabOverride[];
- };
-}
-interface PrefabOverride {
- prefabEntityId: number;
- type: 'property' | 'component_added' | 'component_removed' | 'name' | 'visibility';
- componentType?: string;
- propertyName?: string;
- value?: unknown;
- componentData?: {
- type: string;
- data: Record<string, unknown>;
- };
-}
-interface InstantiatePrefabOptions {
- assetServer?: AssetServer;
- assetBaseUrl?: string;
- parent?: Entity;
- overrides?: PrefabOverride[];
-}
-interface InstantiatePrefabResult {
- root: Entity;
- entities: Map<number, Entity>;
-}
-declare function instantiatePrefab(world: World, prefab: PrefabData, options?: InstantiatePrefabOptions): Promise<InstantiatePrefabResult>;
-
-/**
- * @file SpineModuleLoader.ts
- * @brief Loads and initializes the standalone Spine WASM module
- */
-interface SpineWasmModule {
- _spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;
- _spine_unloadSkeleton(handle: number): void;
- _spine_getAtlasPageCount(handle: number): number;
- _spine_getAtlasPageTextureName(handle: number, pageIndex: number): number;
- _spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
- _spine_createInstance(skeletonHandle: number): number;
- _spine_destroyInstance(instanceId: number): void;
- _spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;
- _spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;
- _spine_setSkin(instanceId: number, name: number): void;
- _spine_update(instanceId: number, dt: number): void;
- _spine_getAnimations(instanceId: number): number;
- _spine_getSkins(instanceId: number): number;
- _spine_getBonePosition(instanceId: number, bone: number, outXPtr: number, outYPtr: number): number;
- _spine_getBoneRotation(instanceId: number, bone: number): number;
- _spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;
- _spine_getMeshBatchCount(instanceId: number): number;
- _spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
- _spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
- _spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;
- cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;
- UTF8ToString(ptr: number): string;
- stringToNewUTF8(str: string): number;
- HEAPF32: Float32Array;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-interface SpineWrappedAPI {
- loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: string, atlasLen: number, isBinary: boolean): number;
- getLastError(): string;
- unloadSkeleton(handle: number): void;
- getAtlasPageCount(handle: number): number;
- getAtlasPageTextureName(handle: number, pageIndex: number): string;
- setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
- createInstance(skeletonHandle: number): number;
- destroyInstance(instanceId: number): void;
- playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;
- addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;
- setSkin(instanceId: number, name: string): void;
- update(instanceId: number, dt: number): void;
- getAnimations(instanceId: number): string;
- getSkins(instanceId: number): string;
- getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;
- getBoneRotation(instanceId: number, bone: string): number;
- getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;
- getMeshBatchCount(instanceId: number): number;
- getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
- getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
- getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;
-}
-
-/**
- * @file SpineController.ts
- * @brief Spine animation control for the modular Spine WASM module
- */
-
-type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';
-type SpineEventCallback = (event: SpineEvent) => void;
-interface SpineEvent {
- type: SpineEventType;
- entity: Entity;
- track: number;
- animation: string | null;
- eventName?: string;
- intValue?: number;
- floatValue?: number;
- stringValue?: string;
-}
-declare class SpineModuleController {
- private raw_;
- private api_;
- private listeners_;
- constructor(raw: SpineWasmModule, api: SpineWrappedAPI);
- get raw(): SpineWasmModule;
- loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number;
- getLastError(): string;
- unloadSkeleton(handle: number): void;
- getAtlasPageCount(handle: number): number;
- getAtlasPageTextureName(handle: number, pageIndex: number): string;
- setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
- createInstance(skeletonHandle: number): number;
- destroyInstance(instanceId: number): void;
- play(instanceId: number, animation: string, loop?: boolean, track?: number): boolean;
- addAnimation(instanceId: number, animation: string, loop?: boolean, delay?: number, track?: number): boolean;
- setSkin(instanceId: number, skinName: string): void;
- update(instanceId: number, dt: number): void;
- getAnimations(instanceId: number): string[];
- getSkins(instanceId: number): string[];
- getBonePosition(instanceId: number, boneName: string): Vec2 | null;
- getBoneRotation(instanceId: number, boneName: string): number;
- getBounds(instanceId: number): {
- x: number;
- y: number;
- width: number;
- height: number;
- };
- extractMeshBatches(instanceId: number): {
- vertices: Float32Array;
- indices: Uint16Array;
- textureId: number;
- blendMode: number;
- }[];
- on(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;
- off(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;
- removeAllListeners(entity: Entity): void;
-}
-
-type AssetContentType = 'json' | 'text' | 'binary' | 'image' | 'audio';
-type AddressableAssetType = 'texture' | 'material' | 'spine' | 'bitmap-font' | 'prefab' | 'json' | 'text' | 'binary' | 'audio';
-type EditorAssetType = 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton' | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'anim-clip' | 'tilemap' | 'unknown';
-type AssetBuildTransform = (content: string, context: unknown) => string;
-interface AssetTypeEntry {
- extensions: string[];
- contentType: AssetContentType;
- editorType: EditorAssetType;
- addressableType: AddressableAssetType | null;
- wechatPackInclude: boolean;
- hasTransitiveDeps: boolean;
- buildTransform?: AssetBuildTransform;
-}
-declare function getAssetTypeEntry(extensionOrPath: string): AssetTypeEntry | undefined;
-declare function getEditorType(path: string): EditorAssetType;
-declare function getAddressableType(path: string): AddressableAssetType | null;
-declare function getAddressableTypeByEditorType(editorType: string): AddressableAssetType | null;
-declare function isKnownAssetExtension(ext: string): boolean;
-declare function getAllAssetExtensions(): Set<string>;
-declare function looksLikeAssetPath(value: unknown): value is string;
-declare function getCustomExtensions(): string[];
-declare function getWeChatPackOptions(): Array<{
- type: string;
- value: string;
-}>;
-declare function getAssetMimeType(ext: string): string | undefined;
-declare function isCustomExtension(path: string): boolean;
-declare function toBuildPath(path: string): string;
-declare function registerAssetBuildTransform(editorType: EditorAssetType, transform: AssetBuildTransform): void;
-declare function getAssetBuildTransform(extensionOrPath: string): AssetBuildTransform | undefined;
-
-/**
- * @file AssetServer.ts
- * @brief Asset loading and caching system
- */
-
-interface TextureInfo {
- handle: TextureHandle;
- width: number;
- height: number;
-}
-interface SliceBorder$1 {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-interface SpineLoadResult {
- success: boolean;
- error?: string;
-}
-interface SpineDescriptor {
- skeleton: string;
- atlas: string;
- baseUrl?: string;
-}
-interface FileLoadOptions {
- baseUrl?: string;
- noCache?: boolean;
-}
-
-interface AddressableResultMap {
- texture: TextureInfo;
- material: LoadedMaterial;
- spine: SpineLoadResult;
- 'bitmap-font': FontHandle;
- prefab: PrefabData;
- json: unknown;
- text: string;
- binary: ArrayBuffer;
- audio: ArrayBuffer;
-}
-interface AssetBundle {
- textures: Map<string, TextureInfo>;
- materials: Map<string, LoadedMaterial>;
- spine: Map<string, SpineLoadResult>;
- fonts: Map<string, FontHandle>;
- prefabs: Map<string, PrefabData>;
- json: Map<string, unknown>;
- text: Map<string, string>;
- binary: Map<string, ArrayBuffer>;
-}
-interface AddressableManifestAsset {
- path: string;
- address?: string;
- type: AddressableAssetType;
- size: number;
- labels: string[];
- metadata?: {
- atlas?: string;
- atlasPage?: number;
- atlasFrame?: {
- x: number;
- y: number;
- width: number;
- height: number;
- };
- };
-}
-interface AddressableManifestGroup {
- bundleMode: string;
- labels: string[];
- assets: Record<string, AddressableManifestAsset>;
-}
-interface AddressableManifest {
- version: '2.0';
- groups: Record<string, AddressableManifestGroup>;
-}
-declare class AssetServer {
- baseUrl?: string;
- private module_;
- private textureCache_;
- private shaderCache_;
- private jsonCache_;
- private textCache_;
- private binaryCache_;
- private loadedSpines_;
- private virtualFSPaths_;
- private materialLoader_;
- private canvas_;
- private ctx_;
- private fontCache_;
- private prefabCache_;
- private embedded_;
- private embeddedOnly_;
- private addressableManifest_;
- private addressIndex_;
- private labelIndex_;
- private groupAssets_;
- private spineController_;
- private spineSkeletons_;
- private textureRefCounts_;
- private assetRefResolver_;
- constructor(module: ESEngineModule);
- registerEmbeddedAssets(assets: Record<string, string>): void;
- setEmbeddedOnly(value: boolean): void;
- /**
- * Load texture with vertical flip (for Sprite/UI).
- * OpenGL UV origin is bottom-left, so standard images need flipping.
- */
- loadTexture(source: string): Promise<TextureInfo>;
- /**
- * Load texture without flip (for Spine).
- * Spine runtime handles UV coordinates internally.
- */
- loadTextureRaw(source: string): Promise<TextureInfo>;
- getTexture(source: string): TextureInfo | undefined;
- hasTexture(source: string): boolean;
- getTextureRefCount(source: string): number;
- releaseTexture(source: string): void;
- releaseAll(): void;
- private cleanupVirtualFS;
- setTextureMetadata(handle: TextureHandle, border: SliceBorder$1): void;
- setTextureMetadataByPath(source: string, border: SliceBorder$1): boolean;
- setSpineController(controller: SpineModuleController): void;
- getSpineSkeletonHandle(skeletonPath: string, atlasPath: string): number | undefined;
- loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;
- isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;
- releaseSpine(key: string): void;
- loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle>;
- getFont(fontPath: string): FontHandle | undefined;
- releaseFont(fontPath: string): void;
- private loadBmfontAsset;
- private loadFntFile;
- setAssetRefResolver(resolver: (ref: string) => string | null): void;
- loadPrefab(path: string, baseUrl?: string): Promise<PrefabData>;
- private resolvePrefabRefs_;
- loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;
- getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;
- hasMaterial(path: string, baseUrl?: string): boolean;
- loadShader(path: string): Promise<ShaderHandle>;
- loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T>;
- loadText(path: string, options?: FileLoadOptions): Promise<string>;
- loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;
- loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;
- loadAll(manifest: AddressableManifest): Promise<AssetBundle>;
- setAddressableManifest(manifest: AddressableManifest): void;
- resolveAddress(address: string): AddressableManifestAsset | undefined;
- load<T extends AddressableAssetType = AddressableAssetType>(address: string): Promise<AddressableResultMap[T]>;
- loadByLabel(label: string): Promise<AssetBundle>;
- loadGroup(groupName: string): Promise<AssetBundle>;
- private loadAddressableAsset;
- private loadAddressableAssets;
- private textureCacheKey;
- private loadTextureWithFlip;
- private loadTextureInternal;
- private loadImage;
- private loadImageFromSrc;
- private createTextureFromImage;
- private getWebGL2Context;
- private createTextureWebGL2;
- private createTextureFallback;
- private unpremultiplyAlpha;
- private loadShaderInternal;
- private parseEsShader;
- private decodeDataUrlText;
- private decodeDataUrlBinary;
- private isLocalPath;
- private toLocalPath;
- private getEmbedded;
- private fetchJson;
- private fetchText;
- private fetchBinary;
- private writeToVirtualFS;
- private ensureVirtualDir;
- private resolveUrl;
- private nextPowerOf2;
- private parseAtlasTextures;
-}
-
-/**
- * @file scene.ts
- * @brief Scene loading utilities
- */
-
-interface SceneEntityData {
- id: number;
- name: string;
- parent: number | null;
- children: number[];
- components: SceneComponentData[];
- visible?: boolean;
-}
-interface SceneComponentData {
- type: string;
- data: Record<string, unknown>;
-}
-interface SliceBorder {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-interface TextureMetadata {
- version: string;
- type: 'texture';
- sliceBorder: SliceBorder;
-}
-interface SceneData {
- version: string;
- name: string;
- entities: SceneEntityData[];
- textureMetadata?: Record<string, TextureMetadata>;
-}
-interface LoadedSceneAssets {
- textureUrls: Set<string>;
- materialHandles: Set<number>;
- fontPaths: Set<string>;
- spineKeys: Set<string>;
-}
-interface SceneLoadOptions {
- assetServer?: AssetServer;
- assetBaseUrl?: string;
- collectAssets?: LoadedSceneAssets;
-}
-type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap';
-interface AssetFieldDescriptor {
- field: string;
- type: AssetFieldType;
-}
-interface SpineFieldDescriptor {
- skeletonField: string;
- atlasField: string;
-}
-interface ComponentAssetFields {
- fields?: AssetFieldDescriptor[];
- spine?: SpineFieldDescriptor;
-}
-declare function registerComponentAssetFields(componentType: string, config: ComponentAssetFields): void;
-declare function getComponentAssetFields(componentType: string): string[];
-declare function getComponentAssetFieldDescriptors(componentType: string): readonly {
- field: string;
- type: AssetFieldType;
-}[];
-declare function getComponentSpineFieldDescriptor(componentType: string): {
- skeletonField: string;
- atlasField: string;
-} | null;
-declare function registerComponentEntityFields(componentType: string, fields: string[]): void;
-declare function getComponentEntityFields(componentType: string): string[] | undefined;
-declare function remapEntityFields(compData: SceneComponentData, entityMap: Map<number, Entity>): void;
-declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;
-declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;
-declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void;
-declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;
-declare function findEntityByName(world: World, name: string): Entity | null;
-
-/**
- * @file customDraw.ts
- * @brief Custom draw callback registration for the render pipeline
- */
-type DrawCallback = (elapsed: number) => void;
-declare function registerDrawCallback(id: string, fn: DrawCallback, scene?: string): void;
-declare function unregisterDrawCallback(id: string): void;
-declare function clearDrawCallbacks(): void;
-
-interface PassConfig {
- name: string;
- shader: ShaderHandle;
- enabled: boolean;
- floatUniforms: Map<string, number>;
- vec4Uniforms: Map<string, Vec4>;
-}
-declare class PostProcessStack {
- readonly id: number;
- private passes_;
- private destroyed_;
- constructor();
- addPass(name: string, shader: ShaderHandle): this;
- removePass(name: string): this;
- setEnabled(name: string, enabled: boolean): this;
- setUniform(passName: string, uniform: string, value: number): this;
- setUniformVec4(passName: string, uniform: string, value: Vec4): this;
- setAllPassesEnabled(enabled: boolean): void;
- get passCount(): number;
- get enabledPassCount(): number;
- get passes(): readonly PassConfig[];
- get isDestroyed(): boolean;
- destroy(): void;
-}
-
declare function initPostProcessAPI(wasmModule: ESEngineModule): void;
declare function shutdownPostProcessAPI(): void;
declare const PostProcess: {
@@ -2059,189 +158,6 @@ declare class PostProcessPlugin implements Plugin {
}
declare const postProcessPlugin: PostProcessPlugin;
-type SceneStatus = 'loading' | 'running' | 'paused' | 'sleeping' | 'unloading';
-interface SceneConfig {
- name: string;
- path?: string;
- data?: SceneData;
- systems?: Array<{
- schedule: Schedule;
- system: SystemDef;
- }>;
- setup?: (ctx: SceneContext) => void | Promise<void>;
- cleanup?: (ctx: SceneContext) => void;
-}
-interface SceneContext {
- readonly name: string;
- readonly entities: ReadonlySet<Entity>;
- spawn(): Entity;
- despawn(entity: Entity): void;
- registerDrawCallback(id: string, fn: DrawCallback): void;
- bindPostProcess(camera: Entity, stack: PostProcessStack): void;
- unbindPostProcess(camera: Entity): void;
- setPersistent(entity: Entity, persistent: boolean): void;
-}
-interface TransitionOptions {
- keepPersistent?: boolean;
- transition?: 'none' | 'fade';
- duration?: number;
- color?: Color;
- onStart?: () => void;
- onComplete?: () => void;
-}
-declare class SceneManagerState {
- private readonly app_;
- private readonly configs_;
- private readonly scenes_;
- private readonly contexts_;
- private readonly additiveScenes_;
- private readonly pausedScenes_;
- private readonly sleepingScenes_;
- private readonly loadOrder_;
- private activeScene_;
- private initialScene_;
- private transition_;
- private switching_;
- private loadPromises_;
- constructor(app: App);
- reset(): void;
- register(config: SceneConfig): void;
- setInitial(name: string): void;
- getInitial(): string | null;
- isTransitioning(): boolean;
- switchTo(name: string, options?: TransitionOptions): Promise<void>;
- private startFadeTransition;
- updateTransition(dt: number): void;
- load(name: string): Promise<SceneContext>;
- loadAdditive(name: string): Promise<SceneContext>;
- unload(name: string, options?: TransitionOptions): Promise<void>;
- private loadSceneData_;
- private releaseSceneAssets_;
- pause(name: string): void;
- resume(name: string): void;
- sleep(name: string): void;
- wake(name: string): void;
- private setPostProcessPassesEnabled;
- isPaused(name: string): boolean;
- isSleeping(name: string): boolean;
- isLoaded(name: string): boolean;
- isActive(name: string): boolean;
- getActive(): string | null;
- getActiveScenes(): string[];
- getLoaded(): string[];
- getLoadOrder(): string[];
- bringToTop(name: string): void;
- getScene(name: string): SceneContext | null;
- getSceneStatus(name: string): SceneStatus | null;
-}
-declare const SceneManager: ResourceDef<SceneManagerState>;
-declare function wrapSceneSystem(app: App, sceneName: string, system: SystemDef): SystemDef;
-
-/**
- * @file app.ts
- * @brief Application builder and web platform integration
- */
-
-type PluginDependency = string | ResourceDef<any>;
-interface Plugin {
- name?: string;
- dependencies?: PluginDependency[];
- build(app: App): void;
- finish?(app: App): void;
- cleanup?(app?: App): void;
-}
-declare class App {
- private readonly world_;
- private readonly resources_;
- private readonly systems_;
- private runner_;
- private running_;
- private lastTime_;
- private fixedTimestep_;
- private fixedAccumulator_;
- private maxDeltaTime_;
- private maxFixedSteps_;
- private module_;
- private pipeline_;
- private spineInitPromise_?;
- private physicsInitPromise_?;
- private physicsModule_?;
- private readonly installed_plugins_;
- private readonly installedPluginSet_;
- private readonly installedPluginNames_;
- private pluginsFinished_;
- private readonly eventRegistry_;
- private readonly sortedSystemsCache_;
- private error_handler_;
- private system_error_handler_;
- private statsEnabled_;
- private phaseTimings_;
- private frame_paused_;
- private user_paused_;
- private step_pending_;
- private play_speed_;
- private constructor();
- static new(): App;
- addPlugin(plugin: Plugin): this;
- addEvent<T>(event: EventDef<T>): this;
- addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
- runBefore?: string[];
- runAfter?: string[];
- }): this;
- addSystem(system: SystemDef): this;
- addStartupSystem(system: SystemDef): this;
- removeSystem(systemId: symbol): boolean;
- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
- get wasmModule(): ESEngineModule | null;
- get pipeline(): RenderPipeline | null;
- setPipeline(pipeline: RenderPipeline): void;
- setSpineRenderer(fn: SpineRendererFn | null): void;
- get spineInitPromise(): Promise<unknown> | undefined;
- set spineInitPromise(p: Promise<unknown> | undefined);
- get physicsInitPromise(): Promise<unknown> | undefined;
- set physicsInitPromise(p: Promise<unknown> | undefined);
- get physicsModule(): unknown;
- set physicsModule(m: unknown);
- get world(): World;
- setFixedTimestep(timestep: number): this;
- setMaxDeltaTime(v: number): this;
- setMaxFixedSteps(v: number): this;
- onError(handler: (error: unknown, systemName: string) => void): this;
- onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
- onWasmError(handler: (error: unknown, context: string) => void): this;
- setPaused(paused: boolean): void;
- isPaused(): boolean;
- stepFrame(): void;
- setPlaySpeed(speed: number): void;
- getPlaySpeed(): number;
- enableStats(): this;
- getSystemTimings(): ReadonlyMap<string, number> | null;
- getPhaseTimings(): ReadonlyMap<string, number> | null;
- getEntityCount(): number;
- insertResource<T>(resource: ResourceDef<T>, value: T): this;
- getResource<T>(resource: ResourceDef<T>): T;
- hasResource<T>(resource: ResourceDef<T>): boolean;
- registerScene(config: SceneConfig): this;
- setInitialScene(name: string): this;
- tick(delta: number): void;
- run(): void;
- private mainLoop;
- quit(): void;
- private finishPlugins_;
- private sortSystems;
- private runSchedule;
- private updateTime;
-}
-interface WebAppOptions {
- getViewportSize?: () => {
- width: number;
- height: number;
- };
- glContextHandle?: number;
- plugins?: Plugin[];
-}
-declare function flushPendingSystems(app: App): void;
-
declare class InputState {
keysDown: Set<string>;
keysPressed: Set<string>;
@@ -2919,52 +835,6 @@ declare class PrefabsPlugin implements Plugin {
}
declare const prefabsPlugin: PrefabsPlugin;
-/**
- * @file PhysicsModuleLoader.ts
- * @brief Loads and initializes the Physics WASM module (standalone or side module)
- */
-interface PhysicsWasmModule {
- _physics_init(gx: number, gy: number, timestep: number, substeps: number): void;
- _physics_shutdown(): void;
- _physics_createBody(entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number): void;
- _physics_destroyBody(entityId: number): void;
- _physics_hasBody(entityId: number): number;
- _physics_addBoxShape(entityId: number, halfW: number, halfH: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;
- _physics_addCircleShape(entityId: number, radius: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;
- _physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;
- _physics_step(dt: number): void;
- _physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;
- _physics_getDynamicBodyCount(): number;
- _physics_getDynamicBodyTransforms(): number;
- _physics_collectEvents(): void;
- _physics_getCollisionEnterCount(): number;
- _physics_getCollisionEnterBuffer(): number;
- _physics_getCollisionExitCount(): number;
- _physics_getCollisionExitBuffer(): number;
- _physics_getSensorEnterCount(): number;
- _physics_getSensorEnterBuffer(): number;
- _physics_getSensorExitCount(): number;
- _physics_getSensorExitBuffer(): number;
- _physics_applyForce(entityId: number, forceX: number, forceY: number): void;
- _physics_applyImpulse(entityId: number, impulseX: number, impulseY: number): void;
- _physics_setLinearVelocity(entityId: number, vx: number, vy: number): void;
- _physics_getLinearVelocity(entityId: number): number;
- _physics_setGravity(gx: number, gy: number): void;
- _physics_getGravity(): number;
- _physics_setAngularVelocity(entityId: number, omega: number): void;
- _physics_getAngularVelocity(entityId: number): number;
- _physics_applyTorque(entityId: number, torque: number): void;
- _physics_applyAngularImpulse(entityId: number, impulse: number): void;
- _physics_updateBodyProperties(entityId: number, bodyType: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number): void;
- HEAPF32: Float32Array;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-type PhysicsModuleFactory = (config?: Record<string, unknown>) => Promise<PhysicsWasmModule>;
-declare function loadPhysicsModule(wasmUrl: string, factory?: PhysicsModuleFactory): Promise<PhysicsWasmModule>;
-
/**
* @file runtimeLoader.ts
* @brief Runtime scene loader for builder targets (WeChat, Playable, etc.)
@@ -3527,66 +1397,6 @@ declare function isRuntime(): boolean;
declare function setPlayMode(active: boolean): void;
declare function isPlayMode(): boolean;
-interface PhysicsDebugDrawConfig {
- enabled: boolean;
- showColliders: boolean;
- showVelocity: boolean;
- showContacts: boolean;
-}
-
-interface PhysicsPluginConfig {
- gravity?: Vec2;
- fixedTimestep?: number;
- subStepCount?: number;
-}
-interface CollisionEnterEvent {
- entityA: Entity;
- entityB: Entity;
- normalX: number;
- normalY: number;
- contactX: number;
- contactY: number;
-}
-interface SensorEvent {
- sensorEntity: Entity;
- visitorEntity: Entity;
-}
-interface PhysicsEventsData {
- collisionEnters: CollisionEnterEvent[];
- collisionExits: Array<{
- entityA: Entity;
- entityB: Entity;
- }>;
- sensorEnters: SensorEvent[];
- sensorExits: SensorEvent[];
-}
-declare const PhysicsEvents: ResourceDef<PhysicsEventsData>;
-declare class PhysicsPlugin implements Plugin {
- private config_;
- private wasmUrl_;
- private factory_?;
- constructor(wasmUrl: string, config?: PhysicsPluginConfig, factory?: PhysicsModuleFactory);
- build(app: App): void;
-}
-declare class Physics {
- private module_;
- constructor(app: App);
- /** @internal */
- static _fromModule(module: PhysicsWasmModule): Physics;
- applyForce(entity: Entity, force: Vec2): void;
- applyImpulse(entity: Entity, impulse: Vec2): void;
- setLinearVelocity(entity: Entity, velocity: Vec2): void;
- getLinearVelocity(entity: Entity): Vec2;
- setGravity(gravity: Vec2): void;
- getGravity(): Vec2;
- setAngularVelocity(entity: Entity, omega: number): void;
- getAngularVelocity(entity: Entity): number;
- applyTorque(entity: Entity, torque: number): void;
- applyAngularImpulse(entity: Entity, impulse: number): void;
- static setDebugDraw(app: App, enabled: boolean): void;
- static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void;
-}
-
/**
* @file logger.ts
* @brief Centralized logging system for SDK
@@ -4191,5 +2001,5 @@ declare const uiPlugins: Plugin[];
declare function createWebApp(module: ESEngineModule, options?: WebAppOptions): App;
-export { Added, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BitmapText$1 as BitmapText, BlendMode, BodyType, BoxCollider$1 as BoxCollider, Button, ButtonState, Camera$1 as Camera, Canvas$1 as Canvas, CapsuleCollider$1 as CapsuleCollider, Changed, Children$1 as Children, CircleCollider$1 as CircleCollider, ClearFlags, Commands, CommandsInstance, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragPlugin, DragState, Draggable, Draw, Dropdown, DropdownPlugin, EasingType, EmitterShape, EntityCommands, EventReader, EventReaderInstance, EventRegistry, EventWriter, EventWriterInstance, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, FocusPlugin, Focusable, FrameHistory, GLDebug, Geometry, GetWorld, INVALID_ENTITY, INVALID_FONT, INVALID_MATERIAL, INVALID_TEXTURE, Image, ImagePlugin, ImageType, Input, InputPlugin, InputState, Interactable, LayoutGroupPlugin, ListView, ListViewPlugin, LocalTransform, LogLevel, Logger, LoopMode, MaskMode, Material, MaterialLoader, Mut, Name, Parent$1 as Parent, Particle, ParticleEasing, ParticleEmitter$1 as ParticleEmitter, ParticlePlugin, Physics, PhysicsEvents, PhysicsPlugin, PostProcess, PostProcessPlugin, PostProcessStack, PostProcessVolume, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, ProjectionType, Query, QueryInstance, Removed, RemovedQueryInstance, RenderPipeline, RenderStage, RenderTexture, Renderer, Res, ResMut, ResMutInstance, RigidBody$1 as RigidBody, RuntimeConfig, SafeArea, SafeAreaPlugin, ScaleMode, SceneManager, SceneManagerState, SceneOwner, Schedule, ScrollView, ScrollViewPlugin, ShaderSources, SimulationSpace, Slider, SliderDirection, SliderPlugin, SpineAnimation$1 as SpineAnimation, Sprite$1 as Sprite, SpriteAnimator, Stats, StatsCollector, StatsOverlay, StatsPlugin, Storage, SystemRunner, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Tilemap, TilemapAPI, TilemapLayer, TilemapPlugin, Time, Toggle, TogglePlugin, Transform$1 as Transform, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Velocity$1 as Velocity, WebAssetProvider, World, WorldTransform, addStartupSystem, addSystem, addSystemToSchedule, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, cleanupAllPostProcessVolumes, cleanupPostProcessVolume, clearAnimClips, clearDrawCallbacks, clearTextureDimensionsCache, clearTilemapSourceCache, clearUserComponents, color, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, defineComponent, defineEvent, defineResource, defineSystem, defineTag, dragPlugin, dropdownPlugin, error, extractAnimClipTexturePaths, findEntityByName, flushPendingSystems, focusPlugin, getAddressableType, getAddressableTypeByEditorType, getAllAssetExtensions, getAllEffectDefs, getAnimClip, getAssetBuildTransform, getAssetMimeType, getAssetTypeEntry, getComponent, getComponentAssetFieldDescriptors, getComponentAssetFields, getComponentDefaults, getComponentEntityFields, getComponentSpineFieldDescriptor, getCustomExtensions, getEditorType, getEffectDef, getEffectTypes, getLogger, getPlatform, getPlatformType, getTextureDimensions, getTilemapSource, getUserComponent, getWeChatPackOptions, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initMaterialAPI, initParticleAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTilemapAPI, initTweenAPI, inputPlugin, instantiatePrefab, intersectRects, invertMatrix4, isBuiltinComponent, isCustomExtension, isEditor, isKnownAssetExtension, isPlatformInitialized, isPlayMode, isRuntime, isTextureRef, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadComponent, loadPhysicsModule, loadRuntimeScene, loadSceneData, loadSceneWithAssets, loadTiledMap, looksLikeAssetPath, parseAnimClipData, parseTiledMap, parseTmjJson, particlePlugin, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, postProcessPlugin, prefabsPlugin, progressBarPlugin, quat, registerAnimClip, registerAssetBuildTransform, registerComponent, registerComponentAssetFields, registerComponentEntityFields, registerDrawCallback, registerEmbeddedAssets, registerMaterialCallback, registerTextureDimensions, registerTilemapSource, remapEntityFields, resolveRelativePath, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownParticleAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTilemapAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, syncPostProcessVolume, textInputPlugin, textPlugin, tilemapPlugin, toBuildPath, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, unregisterComponent, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4, warn, wrapSceneSystem };
-export type { AddedWrapper, AddressableAssetType, AddressableManifest, AddressableManifestAsset, AddressableManifestGroup, AddressableResultMap, AnimClipAssetData, AnyComponentDef, AssetBuildTransform, AssetBundle, AssetContentType, AssetFieldType, AssetRefInfo, AssetTypeEntry, AssetsData, AudioBackendInitOptions, AudioBufferHandle, AudioBusConfig, AudioHandle, AudioListenerData, AudioMixerConfig, AudioPluginConfig, AudioSourceData, BezierPoints, BitmapTextData, BoxColliderData, BuiltinComponentDef, ButtonData, ButtonTransition, CameraData, CameraRenderParams, CanvasData, CapsuleColliderData, ChangedWrapper, ChildrenData, CircleColliderData, CollisionEnterEvent, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DragStateData, DraggableData, DrawAPI, DrawCallback, DropdownData, ESEngineModule, EditorAssetType, EffectDef, EffectUniformDef, Entity, EventDef, EventReaderDescriptor, EventWriterDescriptor, FileLoadOptions, FocusableData, FontHandle, FrameSnapshot, FrameStats, GeometryHandle, GeometryOptions, GetWorldDescriptor, ImageData, InferParam, InferParams, InstantiatePrefabOptions, InstantiatePrefabResult, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadRuntimeSceneOptions, LoadedMaterial, LoadedTilemapLayer, LoadedTilemapSource, LoadedTilemapTileset, LocalTransformData, LogEntry, LogHandler, MaskProcessorFn, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, NameData, ParentData, ParticleEmitterData, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, Plugin, PluginDependency, PooledAudioNode, PostProcessEffectData, PostProcessVolumeData$1 as PostProcessVolumeData, PrefabData, PrefabEntityData, PrefabOverride, ProgressBarData, Quat, QueryBuilder, QueryDescriptor, QueryResult, RemovedQueryDescriptor, RenderParams, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, ResDescriptor, ResMutDescriptor, ResourceDef, RigidBodyData, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeInitConfig, SafeAreaData, SceneComponentData, SceneConfig, SceneContext, SceneData, SceneEntityData, SceneLoadOptions, SceneOwnerData, SceneStatus, ScreenRect, ScrollViewData, SensorEvent, ShaderHandle, ShaderLoader, SliceBorder$1 as SliceBorder, SliderData, SpatialAudioConfig, SpineAnimationData, SpineDescriptor, SpineLoadResult, SpineRendererFn, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, SpriteData, StatsPluginOptions, StatsPosition, SystemDef, SystemOptions, SystemParam, TextData, TextInputData, TextRenderResult, TextureDimensions, TextureHandle, TextureInfo, TextureRef, TiledLayerData, TiledMapData, TiledTilesetData, TilemapData, TilemapLayerData, TimeData, ToggleData, ToggleTransition, TransformData, TransitionConfig, TransitionOptions, TweenOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
+export { AddressableManifest, AnimationPlugin, App, AssetPlugin, AssetRefCounter, AssetServer, Assets, AsyncCache, AttenuationModel, Audio, AudioBus, AudioListener, AudioMixer, AudioPlugin, AudioPool, AudioSource, BlendMode, BuiltinComponentDef, Button, ButtonState, Color, ComponentDef, CppRegistry, DEFAULT_DESIGN_HEIGHT, DEFAULT_DESIGN_WIDTH, DEFAULT_FALLBACK_DT, DEFAULT_FIXED_TIMESTEP, DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, DEFAULT_GRAVITY, DEFAULT_LINE_HEIGHT, DEFAULT_MAX_DELTA_TIME, DEFAULT_PIXELS_PER_UNIT, DEFAULT_SPINE_SKIN, DEFAULT_SPRITE_SIZE, DEFAULT_TEXT_CANVAS_SIZE, DataType, DragPlugin, DragState, Draggable, Draw, Dropdown, DropdownPlugin, ESEngineModule, EasingType, Entity, FillDirection, FillMethod, FillOrigin, FocusManager, FocusManagerState, FocusPlugin, Focusable, FrameHistory, GLDebug, Geometry, Image, ImagePlugin, ImageType, Input, InputPlugin, InputState, InstantiatePrefabResult, Interactable, LayoutGroupPlugin, ListView, ListViewPlugin, LogLevel, Logger, LoopMode, MaskMode, MaskProcessorFn, MaterialHandle, Particle, ParticlePlugin, PhysicsWasmModule, Plugin, PostProcess, PostProcessPlugin, PostProcessStack, PrefabOverride, PrefabServer, Prefabs, PrefabsPlugin, PreviewPlugin, ProgressBar, ProgressBarDirection, ProgressBarPlugin, RenderStage, RenderTexture, Renderer, ResourceDef, RuntimeConfig, SafeArea, SafeAreaPlugin, SceneConfig, SceneData, ScrollView, ScrollViewPlugin, ShaderHandle, Slider, SliderDirection, SliderPlugin, SpriteAnimator, Stats, StatsCollector, StatsOverlay, StatsPlugin, Storage, Text, TextAlign, TextInput, TextInputPlugin, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, TextureHandle, Tilemap, TilemapAPI, TilemapLayer, TilemapPlugin, Toggle, TogglePlugin, Tween, TweenHandle, TweenState, TweenTarget, UICameraInfo, UIEventQueue, UIEvents, UIInteraction, UIInteractionPlugin, UILayoutPlugin, UIMask, UIMaskPlugin, UIRect, UIRenderOrderPlugin, Vec2, WebAppOptions, WebAssetProvider, World, animationPlugin, applyBuildRuntimeConfig, applyDirectionalFill, applyRuntimeConfig, assetPlugin, audioPlugin, calculateAttenuation, calculatePanning, cleanupAllPostProcessVolumes, cleanupPostProcessVolume, clearAnimClips, clearTextureDimensionsCache, clearTilemapSourceCache, computeFillAnchors, computeFillSize, computeHandleAnchors, computeUIRectLayout, createMaskProcessor, createRuntimeSceneConfig, createWebApp, debug, defaultFrameStats, dragPlugin, dropdownPlugin, error, extractAnimClipTexturePaths, focusPlugin, getAllEffectDefs, getAnimClip, getEffectDef, getEffectTypes, getLogger, getPlatform, getPlatformType, getTextureDimensions, getTilemapSource, imagePlugin, info, initDrawAPI, initGLDebugAPI, initGeometryAPI, initParticleAPI, initPlayableRuntime, initPostProcessAPI, initRendererAPI, initRuntime, initTilemapAPI, initTweenAPI, inputPlugin, intersectRects, invertMatrix4, isEditor, isPlatformInitialized, isPlayMode, isRuntime, isWeChat, isWeb, layoutGroupPlugin, listViewPlugin, loadRuntimeScene, loadTiledMap, parseAnimClipData, parseTiledMap, parseTmjJson, particlePlugin, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, pointInOBB, pointInWorldRect, postProcessPlugin, prefabsPlugin, progressBarPlugin, registerAnimClip, registerEmbeddedAssets, registerTextureDimensions, registerTilemapSource, resolveRelativePath, safeAreaPlugin, sceneManagerPlugin, screenToWorld, scrollViewPlugin, setEditorMode, setListViewRenderer, setLogLevel, setPlayMode, setWasmErrorHandler, shutdownDrawAPI, shutdownGLDebugAPI, shutdownGeometryAPI, shutdownParticleAPI, shutdownPostProcessAPI, shutdownRendererAPI, shutdownTilemapAPI, shutdownTweenAPI, sliderPlugin, spriteAnimatorSystemUpdate, statsPlugin, syncFillSpriteSize, syncPostProcessVolume, textInputPlugin, textPlugin, tilemapPlugin, togglePlugin, transitionTo, uiInteractionPlugin, uiLayoutPlugin, uiMaskPlugin, uiPlugins, uiRenderOrderPlugin, unregisterAnimClip, warn };
+export type { AnimClipAssetData, AssetRefInfo, AssetsData, AudioBackendInitOptions, AudioBufferHandle, AudioBusConfig, AudioHandle, AudioListenerData, AudioMixerConfig, AudioPluginConfig, AudioSourceData, BezierPoints, ButtonData, ButtonTransition, DragStateData, DraggableData, DrawAPI, DropdownData, EffectDef, EffectUniformDef, FocusableData, FrameSnapshot, FrameStats, GeometryHandle, GeometryOptions, ImageData, InteractableData, LayoutRect, LayoutResult, ListViewData, ListViewItemRenderer, LoadRuntimeSceneOptions, LoadedTilemapLayer, LoadedTilemapSource, LoadedTilemapTileset, LogEntry, LogHandler, PlatformAdapter, PlatformAudioBackend, PlatformRequestOptions, PlatformResponse, PlatformType, PlayConfig, PlayableRuntimeConfig, PooledAudioNode, PostProcessEffectData, ProgressBarData, RenderStats, RenderTargetHandle, RenderTextureHandle, RenderTextureOptions, RuntimeAssetProvider, RuntimeBuildConfig, RuntimeInitConfig, SafeAreaData, ScreenRect, ScrollViewData, SliderData, SpatialAudioConfig, SpriteAnimClip, SpriteAnimFrame, SpriteAnimatorData, StatsPluginOptions, StatsPosition, TextData, TextInputData, TextRenderResult, TextureDimensions, TiledLayerData, TiledMapData, TiledTilesetData, TilemapData, TilemapLayerData, ToggleData, ToggleTransition, TransitionConfig, TweenOptions, UICameraData, UIEvent, UIEventType, UIInteractionData, UIMaskData, UIRectData, VertexAttributeDescriptor };
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 2f744ad29..672ee9816 100644
--- a/desktop/public/sdk/esm/esengine.js
+++ b/desktop/public/sdk/esm/esengine.js
@@ -1,2 +1,2 @@
-let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function i(){return"wechat"===e?.name}function o(){return"web"===e?.name}async function r(e,s){return t().fetch(e,s)}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,s){return t().instantiateWasm(e,s)}function h(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(){if("wechat"===e?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}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),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.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 _{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class y{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new m(this.context_,e.mixerConfig),this.pool_=new g(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const s=this.loadingUrls_.get(e);if(s)return s;const n=this.doLoadBuffer_(e);this.loadingUrls_.set(e,n);try{return await n}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const s=this.urlToId_.get(e);if(void 0!==s&&this.buffers_.has(s)){return{id:s,duration:this.buffers_.get(s).duration}}let n;try{n=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,n),this.urlToId_.set(e,i),{id:i,duration:n.duration}}async doLoadBuffer_(e){const s=await t().readFile(e);return this.loadBufferFromData(e,s)}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new _(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const w=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((s,n)=>{t.crossOrigin="anonymous",t.onload=()=>s(),t.onerror=()=>n(new Error(`Failed to load image: ${e}`)),t.src=e});const s=this.createCanvas(t.width,t.height).getContext("2d");s.drawImage(t,0,0);const n=s.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(n.data.buffer)}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},r=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},u=()=>{e.onPointerUp(0)},h=t=>{const s=t;let n=s.deltaX,i=s.deltaY;1===s.deltaMode?(n*=16,i*=16):2===s.deltaMode&&(n*=window.innerWidth,i*=window.innerHeight),e.onWheel(n,i)};document.addEventListener("keydown",n),document.addEventListener("keyup",i),s.addEventListener("mousemove",o),s.addEventListener("mousedown",r),document.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",u),s.addEventListener("wheel",h),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",i),s.removeEventListener("mousemove",o),s.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",u),s.removeEventListener("wheel",h)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new y}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let s=0;s<localStorage.length;s++){const n=localStorage.key(s);null!==n&&n.startsWith(e)&&t.push(n)}for(const e of t)localStorage.removeItem(e)}},x=1920,v=1080,b=100,S=512,M={x:100,y:100},P="Arial",T=24,E=1.2,C=.5,R=1/60,A={x:0,y:-9.81},I=1/60,k="default",F={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512,assetLoadTimeout:3e4,assetFailureCooldown:5e3};function B(e){e.Text&&(e.Text._default.fontFamily=F.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=F.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=F.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=F.canvasMatchWidthOrHeight)}const z={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function U(e,t){if(void 0!==t.maxDeltaTime&&(F.maxDeltaTime=t.maxDeltaTime,e.setMaxDeltaTime(t.maxDeltaTime)),void 0!==t.maxFixedSteps&&(F.maxFixedSteps=t.maxFixedSteps,e.setMaxFixedSteps(t.maxFixedSteps)),void 0!==t.textCanvasSize&&(F.textCanvasSize=t.textCanvasSize),void 0!==t.defaultFontFamily&&(F.defaultFontFamily=t.defaultFontFamily),void 0!==t.sceneTransitionDuration&&(F.sceneTransitionDuration=t.sceneTransitionDuration),t.sceneTransitionColor){const e=t.sceneTransitionColor.replace("#","");F.sceneTransitionColor={r:parseInt(e.substring(0,2),16)/255,g:parseInt(e.substring(2,4),16)/255,b:parseInt(e.substring(4,6),16)/255,a:1}}void 0!==t.canvasScaleMode&&(F.canvasScaleMode=z[t.canvasScaleMode]??1),void 0!==t.canvasMatchWidthOrHeight&&(F.canvasMatchWidthOrHeight=t.canvasMatchWidthOrHeight),void 0!==t.assetLoadTimeout&&(F.assetLoadTimeout=t.assetLoadTimeout),void 0!==t.assetFailureCooldown&&(F.assetFailureCooldown=t.assetFailureCooldown)}const L=0,$=4294967295,D=4294967295,O=0,W=(e=0,t=0)=>({x:e,y:t}),H=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),V=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),j=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),N=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});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 q(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 G(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function K(e,t){const s=ne.get(e)??G().get(e);if(s)return s;const n=q(e,t);return G().set(e,n),ne.set(e,n),te(e,t,!1),n}function J(e){const t=ne.get(e)??G().get(e);if(t)return t;const s=q(e,{});return G().set(e,s),ne.set(e,s),te(e,{},!0),s}function Q(e){return G().get(e)}function Z(){const e=G();for(const t of e.keys())ne.delete(t);e.clear()}function ee(e){G().delete(e),ne.delete(e)}function te(e,t,s){const n=globalThis;n.__esengine_registerComponent&&n.__esengine_registerComponent(e,t,s)}function se(e){return!0===e._builtin}const ne=new Map;function ie(e,t){ne.set(e,t)}function oe(e){return ne.get(e)??Q(e)}function re(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return ne.set(e,s),s}const ae={Perspective:0,Orthographic:1},le={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},ce={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ue=re("Transform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:0},worldRotation:{w:1,x:0,y:0,z:0},worldScale:{x:1,y:1,z:1}}),he=ue,de=ue,fe=re("Sprite",{texture:$,color:{r:1,g:1,b:1,a:1},size:{x:M.x,y:M.y},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),pe=re("Camera",{projectionType:ae.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth}),me=re("Canvas",{designResolution:{x:x,y:v},pixelsPerUnit:100,scaleMode:ce.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),ge=re("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),_e=re("Parent",{entity:0}),ye=re("Children",{entities:[]}),we=re("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:D,enabled:!0}),xe=re("SpineAnimation",{skeletonPath:"",atlasPath:"",skin:"",animation:"",timeScale:1,loop:!0,playing:!0,flipX:!1,flipY:!1,color:{r:1,g:1,b:1,a:1},layer:0,skeletonScale:1,material:0,enabled:!0}),ve={Point:0,Circle:1,Rectangle:2,Cone:3},be={World:0,Local:1},Se={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},Me=re("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:ve.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:Se.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:Se.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:$,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:be.World,enabled:!0}),Pe=K("Name",{value:""}),Te=K("SceneOwner",{scene:"",persistent:!1}),Ee=K("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function Ce(e){const t=oe(e);return t?X(t._default):null}const Re=re("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Ae=re("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Ie=re("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),ke=re("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),Fe={Static:0,Kinematic:1,Dynamic:2};let Be=0;function ze(e,t){const s=++Be;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Ue(e){return{_type:"res",_resource:e}}function Le(e){return{_type:"res_mut",_resource:e}}class $e{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 De{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 $e(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Oe=ze({delta:0,elapsed:0,frameCount:0},"Time"),We="esengine:",He={getString(e,s){const n=t().getStorageItem(We+e);return null!==n?n:s},setString(e,s){t().setStorageItem(We+e,s)},getNumber(e,s){const n=t().getStorageItem(We+e);if(null===n)return s;const i=Number(n);return Number.isNaN(i)?s:i},setNumber(e,s){t().setStorageItem(We+e,String(s))},getBoolean(e,s){const n=t().getStorageItem(We+e);return null===n?s:"true"===n},setBoolean(e,s){t().setStorageItem(We+e,String(s))},getJSON(e,s){const n=t().getStorageItem(We+e);if(null===n)return s;try{return JSON.parse(n)}catch{return s}},setJSON(e,s){t().setStorageItem(We+e,JSON.stringify(s))},remove(e){t().removeStorageItem(We+e)},has:e=>null!==t().getStorageItem(We+e),clear(){t().clearStorage(We)}};function Ve(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=je(t[e]),o=je(i);"null"!==s&&"undefined"!==s&&(s!==o&&null!=i&&n.push({field:e,expected:s,actual:o,value:i}))}return n}function je(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ne(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 Xe=null;function Ye(e){Xe=e}function qe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Xe&&Xe(e,t)}function Ge(e){let t=!1;for(const s of Object.keys(e)){const n=e[s];if(null!=n&&"object"==typeof n&&!Array.isArray(n)){if("r"in n&&"g"in n&&"b"in n&&"a"in n&&!("x"in n)){t=!0;break}}}if(!t)return e;const s={};for(const t of Object.keys(e)){const n=e[t];if(null==n||"object"!=typeof n||Array.isArray(n))s[t]=n;else{const e=n;s[t]="r"in e&&"g"in e&&"b"in e&&"a"in e&&!("x"in e)?{x:e.r,y:e.g,z:e.b,w:e.a}:n}}return s}let Ke=1;const Je=new WeakMap;function Qe(e){let t=Je.get(e);return void 0===t&&(t=Ke++,Je.set(e,t)),t}const Ze=[];function et(e,t=[],s=[]){Ze.length=0;for(const t of e)Ze.push(Qe(t));Ze.sort((e,t)=>e-t);let n=Ze.join(",");if(t.length>0){Ze.length=0;for(const e of t)Ze.push(Qe(e));Ze.sort((e,t)=>e-t),n+="|+"+Ze.join(",")}if(s.length>0){Ze.length=0;for(const e of s)Ze.push(Qe(e));Ze.sort((e,t)=>e-t),n+="|-"+Ze.join(",")}return n}class tt{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 qe(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){qe(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){qe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){qe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return se(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}set(e,t,s){if(se(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,Ge(o))}catch(s){qe(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 se(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return se(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(se(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return qe(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.");se(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=Ve(t._name,n,i);if(e.length>0)throw new Error(Ne(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,Ge(o))}catch(s){qe(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 qe(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 qe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_){try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){qe(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=Ve(t._name,t._default,e);if(i.length>0)throw new Error(Ne(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 ne)if(se(n)&&!t.has(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.add(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e=G();for(const n of s)for(const[s,i]of e)if(i._id===n){t.add(s);break}}return Array.from(t)}getEntitiesWithComponents(e,t=[],s=[],n){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();const i=n??et(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(!se(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 st(e){return{_type:"mut",_component:e}}function nt(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function it(e){return{_filterType:"added",_component:e}}function ot(e){return{_filterType:"changed",_component:e}}function rt(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"added"===e._filterType}function at(e){return"object"==typeof e&&null!==e&&"_filterType"in e&&"changed"===e._filterType}function lt(e){return nt(e)||rt(e)||at(e)?e._component:e}function ct(e,t=[],s=[]){const n=[],i=[],o=[];return e.forEach((e,t)=>{nt(e)&&n.push(t),rt(e)?i.push({index:t,component:e._component}):at(e)&&o.push({index:t,component:e._component})}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s,_addedFilters:i,_changedFilters:o,with:(...n)=>ct(e,[...t,...n],s),without:(...n)=>ct(e,t,[...s,...n])}}function ut(...e){return ct(e)}class ht{constructor(e,t,s=-1){this.world_=e,this.descriptor_=t,this.lastRunTick_=s,this.actualComponents_=t._components.map(lt),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_=et(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}}function dt(e){return{_type:"removed",_component:e}}class ft{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_)}}function pt(){return{_type:"commands"}}class mt{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=se(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 gt{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new mt(this,null);return this.spawned_.push(e),e}entity(e){return new mt(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)}}}function _t(e){return{_id:Symbol(`Event_${e}`),_name:e}}class yt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(e){this.writeBuffer_.push(e)}getReadBuffer(){return this.readBuffer_}swap(){const e=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=e,this.writeBuffer_.length=0}}class wt{constructor(){this.buses_=new Map}register(e){this.buses_.has(e._id)||this.buses_.set(e._id,new yt)}getBus(e){let t=this.buses_.get(e._id);return t||(t=new yt,this.buses_.set(e._id,t)),t}swapAll(){for(const e of this.buses_.values())e.swap()}}function xt(e){return{_type:"event_writer",_event:e}}function vt(e){return{_type:"event_reader",_event:e}}class bt{constructor(e){this.bus_=e}send(e){this.bus_.send(e)}}class St{constructor(e){this.bus_=e}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var Mt;function Pt(){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"}(Mt||(Mt={}));let Tt=0;function Et(e,t,s){const n=++Tt;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ct(){const e=globalThis;return e.__esengine_pendingSystems??(e.__esengine_pendingSystems=[])}function Rt(e){Ct().push({schedule:Mt.Update,system:e})}function At(e){Ct().push({schedule:Mt.Startup,system:e})}function It(e,t){Ct().push({schedule:e,system:t})}class kt{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 gt&&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 ht(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,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new bt(s)}case"event_reader":{const t=e,s=this.eventRegistry_?this.eventRegistry_.getBus(t._event):(()=>{throw new Error("EventRegistry not available")})();return new St(s)}case"removed":{const t=e;return new ft(this.world_,t._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}class Ft{constructor(){this.keysDown=new Set,this.keysPressed=new Set,this.keysReleased=new Set,this.mouseX=0,this.mouseY=0,this.mouseButtons=new Set,this.mouseButtonsPressed=new Set,this.mouseButtonsReleased=new Set,this.scrollDeltaX=0,this.scrollDeltaY=0}isKeyDown(e){return this.keysDown.has(e)}isKeyPressed(e){return this.keysPressed.has(e)}isKeyReleased(e){return this.keysReleased.has(e)}getMousePosition(){return{x:this.mouseX,y:this.mouseY}}isMouseButtonDown(e){return this.mouseButtons.has(e)}isMouseButtonPressed(e){return this.mouseButtonsPressed.has(e)}isMouseButtonReleased(e){return this.mouseButtonsReleased.has(e)}getScrollDelta(){return{x:this.scrollDeltaX,y:this.scrollDeltaY}}}const Bt=ze(new Ft,"Input");class zt{constructor(e){this.target_=e??null}build(e){const s=new Ft;e.insertResource(Bt,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(Mt.Last,Et([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Ut=new zt,Lt=ze({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 $t;function Dt(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"}($t||($t={}));let Ot=null,Wt=null,Ht=1;const Vt=new Map;function jt(e){Ot=e,Wt=e.getResourceManager(),es()}function Nt(){0!==Gt&&Ot&&(Ot._free(Gt),Gt=0),Vt.clear(),Ht=1,qt=!1,Jt.clear(),Qt=null,Wt=null,Ot=null}function Xt(){if(!Wt)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Wt}const Yt={createShader:(e,t)=>Xt().createShader(e,t),releaseShader(e){e>0&&Xt().releaseShader(e)},create(e){const t=Ht++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??$t.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 Vt.set(t,s),t},get:e=>Vt.get(e),setUniform(e,t,s){const n=Vt.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0,Ot?.invalidateMaterialCache(e))},getUniform(e,t){const s=Vt.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Vt.get(e);s&&(s.blendMode=t,Ot?.invalidateMaterialCache(e))},getBlendMode(e){const t=Vt.get(e);return t?.blendMode??$t.Normal},setDepthTest(e,t){const s=Vt.get(e);s&&(s.depthTest=t,Ot?.invalidateMaterialCache(e))},getShader(e){const t=Vt.get(e);return t?.shader??0},release(e){Vt.delete(e),Ot?.invalidateMaterialCache(e)},isValid:e=>Vt.has(e),releaseAll(){Vt.clear(),Ot?.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??$t.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Vt.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Ht++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Vt.set(s,n),s},toAssetData(e,t){const s=Vt.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=Vt.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let qt=!1,Gt=0;const Kt=16384,Jt=new Map;let Qt=null;function Zt(e){const t=(0===Gt&&Ot&&(Gt=Ot._malloc(Kt)),Gt);if(0===t||!Ot)return{ptr:0,count:0};let s=0,n=0;const i=Ot.HEAPU8,o=Ot.HEAPU32,r=Ot.HEAPF32;for(const[a,l]of e){if(Dt(l))continue;let e=Jt.get(a);e||(Qt||(Qt=new TextEncoder),e=Qt.encode(a),Jt.set(a,e));const c=e.length,u=4*Math.ceil(c/4);if(s+(4+u+4+16)>Kt){console.warn(`[ESEngine] Material uniform buffer full (${s}/${Kt} bytes), skipping remaining uniforms`);break}o[t+s>>2]=c,s+=4,i.set(e,t+s),s+=u;let h=0,d=[0,0,0,0];if("number"==typeof l)h=0,d[0]=l;else if(Array.isArray(l)){h=Math.min(l.length-1,3);for(let e=0;e<Math.min(l.length,4);e++)d[e]=l[e]}else"w"in l?(h=3,d=[l.x,l.y,l.z,l.w]):"z"in l?(h=2,d=[l.x,l.y,l.z,0]):"y"in l&&(h=1,d=[l.x,l.y,0,0]);o[t+s>>2]=h,s+=4;for(let e=0;e<4;e++)r[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function es(){if(!Ot||qt)return;Ot.materialDataProvider=(e,t,s,n,i)=>{const o=Vt.get(e);if(!o)return Ot.HEAPU32[t>>2]=0,Ot.HEAPU32[s>>2]=0,Ot.HEAPU32[n>>2]=0,void(Ot.HEAPU32[i>>2]=0);Ot.HEAPU32[t>>2]=o.shader,Ot.HEAPU32[s>>2]=o.blendMode;const{ptr:r,count:a}=Zt(o.uniforms);Ot.HEAPU32[n>>2]=r,Ot.HEAPU32[i>>2]=a},qt=!0}const ts={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 ss{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(e,t,s=F.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()+F.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 ns{constructor(e,t=""){this.cache_=new ss,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&&(Yt.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Yt.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await c(t))throw new Error(`Material file not found: ${t}`);const s=await l(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),o=await this.shaderLoader_.load(i);return{handle:Yt.createFromAsset(n,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 s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function is(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function os(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 rs=new Map;function as(e){rs.set(e.name,e)}function ls(e){rs.delete(e)}function cs(e){return rs.get(e)}function us(){rs.clear()}const hs=K("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function ds(e,t){const s=e.getEntitiesWithComponents([hs]);for(const n of s){const s=e.get(n,hs);if(!s.enabled||!s.playing||!s.clip)continue;const i=rs.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,fe)){const t=i.frames[s.currentFrame],o=e.get(n,fe);o.texture=t.texture,t.uvOffset&&(o.uvOffset=t.uvOffset,o.uvScale=t.uvScale),e.insert(n,fe,o)}a&&e.insert(n,hs,s)}}class fs{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}}}}fs.mixer_=null,fs.bufferCache_=new Map,fs.bgmHandle_=null,fs.bgmVolume_=1,fs.fadeAnimId_=0,fs.disposed_=!1;const ps=new Map,ms=new Map;function gs(e,t,s){ps.set(e,{width:t,height:s})}function _s(e){return ps.get(e)}function ys(){ps.clear()}function ws(e,t){ms.set(e,t)}function xs(e){return ms.get(e)}function vs(){ms.clear()}let bs=null;function Ss(e){bs=e}function Ms(){bs=null}const Ps={initLayer(e,t,s,n,i){bs?.tilemap_initLayer(e,t,s,n,i)},destroyLayer(e){bs?.tilemap_destroyLayer(e)},setTile(e,t,s,n){bs?.tilemap_setTile(e,t,s,n)},getTile:(e,t,s)=>bs?bs.tilemap_getTile(e,t,s):0,fillRect(e,t,s,n,i,o){bs?.tilemap_fillRect(e,t,s,n,i,o)},setTiles(e,t){if(!bs)return;const s=t.byteLength,n=bs._malloc(s);new Uint16Array(bs.HEAPU8.buffer,n,t.length).set(t),bs.tilemap_setTiles(e,n,t.length),bs._free(n)},hasLayer:e=>!!bs&&bs.tilemap_hasLayer(e),submitLayer(e,t,s,n,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w){bs?.tilemap_submitLayer(e,t,s,n,i,o,r,a,l,c,u,h,d,f,p,m,g,_,y,w)}},Ts=K("Tilemap",{source:""}),Es=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 Rs(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 As(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 Is(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]=As(r[t],e)}const u="number"==typeof e.opacity?e.opacity:1,h=Rs(e.tintcolor),d="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:n,height:i,visible:o,tiles:l,opacity:u,tintColor:h,parallaxX:d,parallaxY:f})}const u=[],h=[];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&&h.push(e.id+t)}}return{width:t,height:s,tileWidth:n,tileHeight:i,layers:c,tilesets:r,objectGroups:u,collisionTileIds:h}}function ks(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("/")}async function Fs(e,t){const s=bs;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}}const Bs=Math.PI/180;function zs(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,h=o+(u-t.row*c)-.5*n,d=e.spawn();e.insert(d,ue,{position:{x:r,y:h,z:0}}),e.insert(d,Re,{bodyType:Fe.Static}),e.insert(d,Ae,{halfExtents:{x:.5*s,y:.5*n}}),a.push(d)}return a}function Us(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,ue,{});const l=o?s.get(o.image)??0:0,c=o?.columns??1;e.insert(a,Es,{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,h=-t.rotation*Bs;if(e.insert(r,ue,{position:{x:c,y:u,z:0}}),e.insert(r,Re,{bodyType:Fe.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(r,Ie,{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,Ae,{halfExtents:{x:.5*a,y:.5*l},offset:{x:c,y:-u}})}else e.insert(r,Ae,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==h){const t=.5*h;e.insert(r,ue,{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=zs(e,s,t,a,0,0);i.push(...n)}return i}const Ls=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){Ls.set(e,t)}function Ds(e){const t=Ls.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 Os(e){return Ls.get(e)?.fields??[]}function Ws(e){return Ls.get(e)?.spine??null}const Hs=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function Vs(e,t){Hs.set(e,t)}function js(e){return Hs.get(e)}function Ns(e,t){const s=Hs.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 Xs(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,Pe,{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)Ns(i,s),Ks(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 Ys(e,t){return Xs(e,t)}async function qs(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 Gs.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=Ls.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=[...Gs.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=Ls.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=Xs(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 Gs=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),gs(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=is(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);as(os(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 fs.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=Is(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=ks(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),gs(o.handle,o.width,o.height)}catch(e){console.warn(`Failed to load tileset texture: ${i}`,e)}o.push({textureHandle:a,columns:r.columns})}ws(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 Ks(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=oe(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 Js(e,t){const s=e.getEntitiesWithComponents([pe]);for(const n of s){const s=e.get(n,pe);s&&(s.aspectRatio=t,e.insert(n,pe,s))}}function Qs(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);if(s&&s.value===t)return n}return null}const Zs=[{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}],en={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"},tn=new Map,sn=new Set;for(const e of Zs)for(const t of e.extensions)tn.set(t,e),sn.add(t);function nn(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function on(e){return tn.get(nn(e))}function rn(e){return on(e)?.editorType??"unknown"}function an(e){return on(e)?.addressableType??null}function ln(e){for(const t of Zs)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function cn(e){return sn.has(e.toLowerCase())}function un(){return sn}function hn(e){return"string"==typeof e&&(!!e.includes("/")&&cn(nn(e)))}function dn(){const e=[];for(const t of Zs)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function fn(){return dn().map(e=>({type:"suffix",value:e}))}function pn(e){return en[e.toLowerCase()]}function mn(e){const t=on(e);return t?.wechatPackInclude??!1}function gn(e){const t=on(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}function _n(e,t){for(const s of Zs)s.editorType===e&&(s.buildTransform=t)}function yn(e){return on(e)?.buildTransform}class wn{constructor(e){this.textureCache_=new ss,this.shaderCache_=new ss,this.jsonCache_=new ss,this.textCache_=new ss,this.binaryCache_=new ss,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ss,this.prefabCache_=new ss,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.assetRefResolver_=null,this.module_=e,this.canvas_=h(F.textCanvasSize,F.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new ns(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(),Yt.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"===on(e)?.contentType,h=u?new Uint8Array(await this.fetchBinary(c)):await this.fetchText(c);if(!this.writeToVirtualFS(e,h))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(h,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=on(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 Ds(e.type)){const n=e.data[s];if("string"==typeof n&&n){const i=t(n);i&&(e.data[s]=i)}}const s=Ws(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 qs(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 Yt.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await c(t))throw new Error(`Shader file not found: ${e}`);const n=await l(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:o}=this.parseEsShader(n);if(!i||!o)throw new Error(`Invalid shader format: ${e}`);return Yt.createShader(i,o)}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(gn(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 l(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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 l(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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 a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await r(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 xn=ze(null,"Assets");class vn{build(e){const t=e.wasmModule;t?e.insertResource(xn,new wn(t)):console.warn("AssetPlugin: No WASM module available")}}const bn=new vn;class Sn{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}}}function Mn(e,t){const s=e.getResource(xn);s&&s.registerEmbeddedAssets(t)}async function Pn(e,t,s){const{entities:n,rootId:i}=await En(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 qs(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 Tn=10;async function En(e,t,s,n,i,o=0){if(o>Tn)throw new Error(`Prefab nesting depth exceeded ${Tn}. 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 En(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,h={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};Cn(h.components,r),Rn(h,t),l.push(h)}const c=r.get(e.rootEntityId);if(void 0===c)throw new Error("Failed to resolve prefab root entity");return{entities:l,rootId:c,nextId:a}}function Cn(e,t){for(const s of e){const e=js(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 Rn(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 An{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 Pn(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const In=ze(null,"Prefabs");class kn{constructor(){this.name="PrefabsPlugin",this.dependencies=[xn]}build(e){const t=e.getResource(xn);e.insertResource(In,new An(e.world,t))}}const Fn=new kn;let Bn=null,zn=0,Un=0,Ln=0;const $n=new Float32Array(256);function Dn(e){Bn=e,zn=Bn._malloc(64),Un=Bn._malloc(64),Ln=Bn._malloc(1024)}function On(){Bn&&(zn&&(Bn._free(zn),zn=0),Un&&(Bn._free(Un),Un=0),Ln&&(Bn._free(Ln),Ln=0)),Bn=null}function Wn(){if(!Bn)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Bn}const Hn={r:1,g:1,b:1,a:1},Vn={begin(e){const t=Wn();try{t.HEAPF32.set(e,zn/4),t.draw_begin(zn)}catch(e){qe(e,"Draw.begin")}},end(){try{Wn().draw_end()}catch(e){qe(e,"Draw.end")}},line(e,t,s,n=1){try{Wn().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){qe(e,"Draw.line")}},rect(e,t,s,n=!0){try{Wn().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){qe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Wn().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){qe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,i=32){try{Wn().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){qe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,i=32){try{Wn().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,i)}catch(e){qe(e,"Draw.circleOutline")}},texture(e,t,s,n=Hn){try{Wn().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){qe(e,"Draw.texture")}},textureRotated(e,t,s,n,i=Hn){try{Wn().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,i.r,i.g,i.b,i.a)}catch(e){qe(e,"Draw.textureRotated")}},setLayer(e){Wn().draw_setLayer(e)},setDepth(e){Wn().draw_setDepth(e)},getDrawCallCount:()=>Bn?Bn.draw_getDrawCallCount():0,getPrimitiveCount:()=>Bn?Bn.draw_getPrimitiveCount():0,setBlendMode(e){Wn().draw_setBlendMode(e)},setDepthTest(e){Wn().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Wn();n.HEAPF32.set(s,Un/4),n.draw_mesh(e,t,Un)}catch(s){qe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Wn(),i=Yt.get(t);if(!i)return;if(Vn.setBlendMode(i.blendMode),Vn.setDepthTest(i.depthTest),0===i.uniforms.size)return void Vn.drawMesh(e,i.shader,s);let o;if(n.HEAPF32.set(s,Un/4),!i.dirty_&&i.cachedBuffer_)o=i.cachedIdx_;else{o=0;let e=0;for(const[t,s]of i.uniforms){const n=Xn(t);if(!(n<0)){if(Dt(s))$n[o++]=10,$n[o++]=n,$n[o++]=s.slot??e++,$n[o++]=s.textureId;else if("number"==typeof s)$n[o++]=1,$n[o++]=n,$n[o++]=s;else if(Array.isArray(s)){$n[o++]=s.length,$n[o++]=n;for(let e=0;e<s.length;e++)$n[o++]=s[e]}else"w"in s?($n[o++]=4,$n[o++]=n,$n[o++]=s.x,$n[o++]=s.y,$n[o++]=s.z,$n[o++]=s.w):"z"in s?($n[o++]=3,$n[o++]=n,$n[o++]=s.x,$n[o++]=s.y,$n[o++]=s.z):($n[o++]=2,$n[o++]=n,$n[o++]=s.x,$n[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($n.subarray(0,o)),i.cachedIdx_=o,i.dirty_=!1}if(0===o)return void n.draw_mesh(e,i.shader,Un);n.HEAPF32.set(i.cachedBuffer_.subarray(0,o),Ln/4),n.draw_meshWithUniforms(e,i.shader,Un,Ln,o)}catch(s){qe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},jn={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},Nn=new Set;function Xn(e){const t=jn[e];return void 0!==t?t:(Nn.has(e)||(Nn.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(jn).join(", ")}`)),-1)}const Yn=new Map;function qn(e,t,s){Yn.set(e,{fn:t,scene:s??""})}function Gn(e){Yn.delete(e)}function Kn(){Yn.clear()}var Jn;!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"}(Jn||(Jn={}));let Qn=null,Zn=0,ei=0,ti=0;function si(e){Qn=e,Zn=Qn._malloc(262144),ei=Qn._malloc(65536),ti=Qn._malloc(256)}function ni(){Qn&&(Zn&&Qn._free(Zn),ei&&Qn._free(ei),ti&&Qn._free(ti),Zn=0,ei=0,ti=0),Qn=null}function ii(){if(!Qn)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Qn}const oi={create(e){const t=ii(),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,Zn/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,ti,i).set(o),t.geometry_init(s,Zn,n,ti,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,ei,n).set(e.indices),t.geometry_setIndices16(s,ei,n)}else{new Uint32Array(t.HEAPU8.buffer,ei,n).set(e.indices),t.geometry_setIndices32(s,ei,n)}}return s},updateVertices(e,t,s=0){const n=ii(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Zn/4),n.geometry_updateVertices(e,Zn,i,s)},release(e){e>0&&ii().geometry_release(e)},isValid:e=>!(!Qn||e<=0)&&Qn.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return oi.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:Jn.Float2},{name:"a_texCoord",type:Jn.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 oi.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Jn.Float2},{name:"a_texCoord",type:Jn.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 oi.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Jn.Float2},{name:"a_texCoord",type:Jn.Float2}],indices:new Uint16Array(r)})}};let ri=1;const ai=new Map,li=new Map;function ci(){return ai}function ui(){return li}class hi{constructor(){this.passes_=[],this.destroyed_=!1,this.id=ri++,ai.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 li)t===this&&li.delete(e);ai.delete(this.id)}}}const di="#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 fi=null;function pi(e){fi=e}function mi(){for(const e of ci().values())e.destroy();ci().clear(),ui().clear(),fi&&_i.isInitialized()&&_i.shutdown(),fi=null}function gi(){if(!fi)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return fi}const _i={createStack:()=>new hi,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");ui().set(e,t)},unbind(e){ui().delete(e)},getStack:e=>ui().get(e)??null,init(e,t){try{return gi().postprocess_init(e,t)}catch(s){return qe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{gi().postprocess_shutdown()}catch(e){qe(e,"PostProcess.shutdown")}},resize(e,t){try{gi().postprocess_resize(e,t)}catch(s){qe(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!fi)return!1;try{return fi.postprocess_isInitialized()}catch(e){return qe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{gi().postprocess_setBypass(e)}catch(e){qe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{gi().postprocess_setOutputViewport(e,t,s,n)}catch(e){qe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=ui().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(_i.isInitialized()||_i.init(1,1),_i.setBypass(!1),function(e){const t=gi();try{t.postprocess_clearPasses()}catch(e){return void qe(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){qe(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){qe(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){qe(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):_i.setBypass(!0)},_resetAfterCamera(){try{gi().postprocess_clearPasses(),gi().postprocess_setBypass(!0)}catch(e){qe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of ui().keys())e(t)||ui().delete(t)},screenStack:null,setScreenStack(e){_i.screenStack=e},_beginScreenCapture(){try{gi().postprocess_beginScreenCapture()}catch(e){qe(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{gi().postprocess_endScreenCapture()}catch(e){qe(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=_i.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=gi();try{t.postprocess_clearScreenPasses()}catch(e){return void qe(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){qe(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){qe(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){qe(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{gi().postprocess_executeScreenPasses()}catch(e){qe(e,"PostProcess._executeScreenPasses")}},createBlur:()=>Yt.createShader(di,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform vec2 u_resolution;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec2 texelSize = 1.0 / u_resolution;\n float offset = u_intensity;\n\n vec4 color = vec4(0.0);\n color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord) * 0.25;\n color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;\n color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;\n color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;\n\n fragColor = color;\n}\n"),createVignette:()=>Yt.createShader(di,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nuniform float u_softness;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);\n fragColor = vec4(color.rgb * vignette, color.a);\n}\n"),createGrayscale:()=>Yt.createShader(di,"#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:()=>Yt.createShader(di,"#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:()=>Yt.createShader(di,"#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")},yi=new Map;function wi(e){yi.set(e.type,e)}function xi(e){return yi.get(e)}function vi(){return Array.from(yi.keys())}function bi(){return Array.from(yi.values())}wi({type:"blur",label:"Blur",factory:()=>_i.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),wi({type:"bloom",label:"Bloom",factory:()=>_i.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}]}),wi({type:"vignette",label:"Vignette",factory:()=>_i.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}]}),wi({type:"grayscale",label:"Grayscale",factory:()=>_i.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),wi({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>_i.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const Si=new Map,Mi=new Map;function Pi(e,t){let s=Si.get(e),n=Mi.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=_i.createStack(),Si.set(e,s)),n||(n=new Map,Mi.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=xi(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)}}_i.bind(e,s)}else if(s&&(_i.unbind(e),s.destroy(),Si.delete(e)),n){for(const e of n.values())Yt.releaseShader(e);Mi.delete(e)}}function Ti(e){const t=Si.get(e);t&&(_i.unbind(e),t.destroy(),Si.delete(e));const s=Mi.get(e);if(s){for(const e of s.values())Yt.releaseShader(e);Mi.delete(e)}}function Ei(){for(const e of Si.keys())Ti(e)}const Ci=ze({enabled:!0},"PostProcessVolumeConfig"),Ri=new Map,Ai=new Map;function Ii(e){const t=Ai.get(e);if(void 0!==t)return t;const s=xi(e);if(!s)return null;const n=s.factory();return Ai.set(e,n),n}function ki(e,t){if(0===t.size){const t=Ri.get(e);return void(t&&(_i.unbind(e),t.destroy(),Ri.delete(e)))}let s=Ri.get(e);for(s||(s=_i.createStack(),Ri.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=Ii(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?_i.bind(e,s):_i.unbind(e)}const Fi=Et([ut(Ee,ue)],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 Ri)ki(t,e)}},{name:"PostProcessVolumeSystem"});class Bi{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(Ci,{enabled:!0}),e.addSystemToSchedule(Mt.PostUpdate,Fi)}cleanup(){Ei(),function(){for(const[e,t]of Ri)_i.unbind(e),t.destroy();Ri.clear();for(const e of Ai.values())Yt.releaseShader(e);Ai.clear()}(),_i.setScreenStack(null)}}const zi=new Bi;var Ui;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ui||(Ui={}));let Li=null,$i=0;function Di(e){Li=e,$i=Li._malloc(64)}function Oi(){Li&&$i&&(Li._free($i),$i=0),Li=null}const Wi={init(e,t){Li?.renderer_init(e,t)},resize(e,t){Li?.renderer_resize(e,t)},begin(e,t){if(Li&&$i)try{Li.HEAPF32.set(e,$i/4),Li.renderer_begin($i,t??0)}catch(e){qe(e,"Renderer.begin")}},flush(){try{Li?.renderer_flush()}catch(e){qe(e,"Renderer.flush")}},end(){try{Li?.renderer_end()}catch(e){qe(e,"Renderer.end")}},submitSprites(e){if(Li)try{Li.renderer_submitSprites(e._cpp)}catch(e){qe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Li)try{Li.renderer_submitBitmapText(e._cpp)}catch(e){qe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Li)try{Li.renderer_submitSpine?.(e._cpp)}catch(e){qe(e,"Renderer.submitSpine")}},submitParticles(e){if(Li)try{Li.renderer_submitParticles?.(e._cpp)}catch(e){qe(e,"Renderer.submitParticles")}},setStage(e){Li?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Li?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Li?.renderer_releaseTarget(e)},getTargetTexture:e=>Li?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Li?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Li?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Li?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){Li?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){Li?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Li?Li.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Li?{drawCalls:Li.renderer_getDrawCalls(),triangles:Li.renderer_getTriangles(),sprites:Li.renderer_getSprites(),text:Li.renderer_getText(),spine:Li.renderer_getSpine?.()??0,meshes:Li.renderer_getMeshes(),culled:Li.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Hi=null;function Vi(e){Hi=e}function ji(){Hi=null}const Ni={enable(){Hi?.gl_enableErrorCheck(!0)},disable(){Hi?.gl_enableErrorCheck(!1)},check:e=>Hi?.gl_checkErrors(e)??0,diagnose(){Hi?.renderer_diagnose()}};class Xi{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(){_i.screenStack&&_i.screenStack.enabledPassCount>0&&(_i.isInitialized()||_i.init(1,1),_i._applyScreenStack(),_i._beginScreenCapture())}endScreenCapture(){_i.screenStack&&_i.screenStack.enabledPassCount>0&&(_i._endScreenCapture(),_i._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Wi.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Wi.setViewport(0,0,n,i),Wi.clearBuffers(3),Wi.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Wi.submitSprites(t),Wi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wi.submitSpine(t),Wi.submitParticles(t),Wi.flush(),this.executeDrawCallbacks(s,o),Wi.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==_i.getStack(r);a&&(_i._applyForCamera(r),_i.resize(n.w,n.h),_i.setOutputViewport(n.x,n.y,n.w,n.h)),Wi.setViewport(n.x,n.y,n.w,n.h),Wi.setScissor(n.x,n.y,n.w,n.h,!0),Wi.clearBuffers(i),Wi.setScissor(0,0,0,0,!1),Wi.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Wi.submitSprites(t),Wi.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Wi.submitSpine(t),Wi.submitParticles(t),Wi.flush(),this.executeDrawCallbacks(s,o),Wi.end(),a&&_i._resetAfterCamera()}executeDrawCallbacks(e,t){const s=Yn;if(s.size>0){Vn.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)}Vn.end();for(const e of n)Gn(e)}}}const Yi="__scene_transition_overlay__";class qi{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 Gi{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,Te,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),qn(e,t,this.instance_.config.name)}bindPostProcess(e,t){_i.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){_i.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,Te)){const s=this.app_.world.get(e,Te);s.persistent=t,this.app_.world.insert(e,Te,s)}}}class Ki{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())Gn(t);for(const t of e.postProcessBindings.keys())_i.unbind(t)}this.transition_&&(Gn(Yi),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??F.sceneTransitionDuration,i=t.color??{...F.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},qn(Yi,()=>{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;Vn.setLayer(9999),Vn.setDepth(9999),Vn.rect({x:0,y:0},{x:2e4,y:2e4},{r:i.r,g:i.g,b:i.b,a: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,Gn(Yi),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Gn(Yi),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 qi(t);this.scenes_.set(e,s);const n=new Gi(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(xn)?this.app_.getResource(xn):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 qi(t);this.scenes_.set(e,s);const n=new Gi(s,this.app_);this.contexts_.set(e,n);const i=(async()=>{let i=t.data;if(!i&&t.path){const e=this.app_.hasResource(xn)?this.app_.getResource(xn):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,Te)){if(this.app_.world.get(e,Te).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Gn(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())_i.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(xn)&&(i.assetServer=this.app_.getResource(xn));const o=await qs(this.app_.world,n,i);e.loadedAssets=s;for(const s of o.values())e.entities.add(s),this.app_.world.insert(s,Te,{scene:t,persistent:!1})}if(s.systems)for(const{schedule:e,system:n}of s.systems){const s=Qi(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(xn)?this.app_.getResource(xn):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)Yt.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,fe)){const t=s.get(e,fe);n.sprite=t.color.a,t.color.a=0,s.insert(e,fe,t),i=!0}if(s.has(e,xe)){const t=s.get(e,xe);n.spine=t.color.a,t.color.a=0,s.insert(e,xe,t),i=!0}if(s.has(e,we)){const t=s.get(e,we);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,we,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,fe)){const t=s.get(e,fe);t.color.a=n.sprite,s.insert(e,fe,t)}if(void 0!==n.spine&&s.has(e,xe)){const t=s.get(e,xe);t.color.a=n.spine,s.insert(e,xe,t)}if(void 0!==n.bitmapText&&s.has(e,we)){const t=s.get(e,we);t.color.a=n.bitmapText,s.insert(e,we,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 Ji=ze(null,"SceneManager");function Qi(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ji).getSceneStatus(t)&&s._fn(...n)}}}const Zi=Et([Le(Ji),Ue(Oe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),eo={name:"SceneManager",build(e){const t=new Ki(e);e.insertResource(Ji,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ji),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Mt.Startup,s),e.addSystemToSchedule(Mt.Last,Zi)}};class to{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=[],this.installedPluginSet_=new Set,this.installedPluginNames_=new Set,this.pluginsFinished_=!1,this.eventRegistry_=new wt,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.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=d(),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(Mt.Last);else{this.runSchedule(Mt.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Mt.FixedPreUpdate),this.runSchedule(Mt.FixedUpdate),this.runSchedule(Mt.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Mt.PreUpdate),this.runSchedule(Mt.Update),this.runSchedule(Mt.PostUpdate),this.runSchedule(Mt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new tt,this.resources_=new De;for(const e of Object.values(Mt))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new to}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(Mt.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Mt.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 Ye(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(Ji).register(e),this}setInitialScene(e){return this.getResource(Ji).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new kt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Oe)||this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Mt.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(Mt.Last);else{this.runSchedule(Mt.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Mt.FixedPreUpdate),this.runSchedule(Mt.FixedUpdate),this.runSchedule(Mt.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(Mt.PreUpdate),this.runSchedule(Mt.Update),this.runSchedule(Mt.PostUpdate),this.runSchedule(Mt.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new kt(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Oe,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(Mt.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Kn();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=[ji,Oi,mi,ni,Nt,On];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(Mt[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(Oe);t.delta=e,t.elapsed+=e,t.frameCount++}}function so(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 no=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function io(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case ce.FixedWidth:return o;case ce.FixedHeight:return r;case ce.Expand:return Math.max(o,r);case ce.Shrink:return Math.min(o,r);case ce.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const oo=[];function ro(e){if(e<oo.length)return oo[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 oo.push(t),t}function ao(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,Te);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,h=0;if(i.projectionType===ae.Orthographic){if(h=i.orthoSize,l){h=io(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=h*r,a=co(-u,u,-h,h,-i.farPlane,i.farPlane)}else a=ho(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const d=po(o.position.x,o.position.y,o.position.z),f=ro(c.length);f.entity=e,f.viewProjection.set(go(a,d)),f.viewportRect.x=i.viewportX,f.viewportRect.y=i.viewportY,f.viewportRect.w=i.viewportW,f.viewportRect.h=i.viewportH,f.clearFlags=i.clearFlags,f.priority=i.priority,f.halfW=u,f.halfH=h,f.cameraX=o.position.x,f.cameraY=o.position.y,c.push(f)}return c.sort((e,t)=>e.priority-t.priority),c}const lo=new Float32Array(16);function co(e,t,s,n,i,o){const r=lo;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 uo=new Float32Array(16);function ho(e,t,s,n){const i=uo;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 fo=new Float32Array(16);function po(e,t,s){const n=fo;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 mo=new Float32Array(16);function go(e,t){const s=mo;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 _o={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function yo(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,h=o.bottom+e.y*l,d=o.bottom+t.y*l;let f,p,m,g;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=u+n.x),e.y===t.y?(p=h+s.y-i.y*r.y,g=p+i.y):(p=h+s.y,g=d+n.y);const _=Math.max(0,m-f),y=Math.max(0,g-p);return{originX:f+r.x*_,originY:p+r.y*y,width:_,height:y,rect:{left:f,bottom:p,right:m,top:g}}}const wo=re("UIRect",{anchorMin:{x:.5,y:.5},anchorMax:{x:.5,y:.5},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:100,y:100},pivot:{x:.5,y:.5}});let xo=null,vo=null;function bo(e,t){e.has(t,fe)||e.insert(t,fe,{texture:$,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0})}function So(e,t){switch(e){case _o.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case _o.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case _o.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 Mo(e,t){switch(e){case _o.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case _o.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case _o.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 Po(e,t,s,n){switch(e){case _o.BottomToTop:case _o.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function To(e,t,s,n){if(!e.has(t,wo))return;const i=e.get(t,wo),o=So(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,wo,i)}function Eo(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function Co(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function Ro(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(Co(r.charCodeAt(0))&&n.length>0&&Co(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!Co(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 Ao(e){let t=1;for(;t<e;)t*=2;return t}function Io(e,t){let s=0,n=t;for(;e.has(n,_e);){const t=e.get(n,_e).entity;if(!e.valid(t))break;s++,n=t}return s}function ko(e,t){if(xo&&vo){const e=xo.getUIRectComputedWidth(vo,t);if(e>0)return e}return e.size.x}function Fo(e,t){if(xo&&vo){const e=xo.getUIRectComputedHeight(vo,t);if(e>0)return e}return e.size.y}function Bo(e,t,s,n,i,o){if(!e.has(t,fe))return;const r=e.get(t,fe);let a,l;switch(s){case _o.BottomToTop:case _o.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,fe,r))}function zo(e,t,s){let n=t;for(;e.has(n,_e);){const t=e.get(n,_e).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function Uo(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Lo(e,t,s,n,i){if(!e.has(t,wo))return;const o=e.get(t,wo),r=yo(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,fe)){const s=e.get(t,fe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,fe,s))}if(e.has(t,ue)){const s=e.get(t,ue);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,ue,s)}}function $o(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 Do=.1,Oo=30,Wo={r:.3,g:.5,b:.8,a:1},Ho={Left:0,Center:1,Right:2},Vo={Top:0,Middle:1,Bottom:2},jo={Visible:0,Clip:1,Ellipsis:2},No=K("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Ho.Left,verticalAlign:Vo.Top,wordWrap:!0,overflow:jo.Visible,lineHeight:1.2});class Xo{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=h(F.textCanvasSize,F.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}beginFrame(){const e=this.canvas;this.frameMaxW_>0&&(e.width<this.frameMaxW_||e.height<this.frameMaxH_?(e.width=Math.max(e.width,Ao(this.frameMaxW_)),e.height=Math.max(e.height,Ao(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=Ao(this.frameMaxW_),e.height=Ao(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=Ro(s,e.content,a?o:0);const c=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),h=Math.ceil(this.measureWidth(l)),d=Math.ceil(l.length*c),f=i?Math.ceil(o):h+2*u,p=i?Math.ceil(r):d+2*u;if(i&&e.overflow===jo.Ellipsis&&d>r){const e=Math.floor(r/c);if(e>0&&l.length>e){l=l.slice(0,e);const t=l[e-1];l[e-1]=this.truncateWithEllipsis(t,o)}}this.frameMaxW_=Math.max(this.frameMaxW_,f),this.frameMaxH_=Math.max(this.frameMaxH_,p),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,Ao(f)),n.height=Math.max(n.height,Ao(p)));const m=Math.round(255*e.color.r),g=Math.round(255*e.color.g),_=Math.round(255*e.color.b),y=e.color.a;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===jo.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=l.length*c;let x;if(i){switch(e.verticalAlign){case Vo.Top:x=u;break;case Vo.Middle:x=u+(p-2*u-w)/2;break;case Vo.Bottom:x=p-w-u;break;default:x=u}x<0&&(x=0)}else x=u;let v=x;for(const t of l){let n;switch(e.align){case Ho.Left:n=u;break;case Ho.Center:n=f/2;break;case Ho.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===jo.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(S.length);this.module.HEAPU8.set(S,P);const T=M.createTexture(f,p,P,S.length,1,!0);return this.module._free(P),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let 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 Ho.Left:return"left";case Ho.Center:return"center";case Ho.Right:return"right"}}}const Yo=$o({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?ko(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?Fo(e.uiRect,e.entity):0});class qo{build(e){ie("Text",No);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Xo(t),n=e.world,i=new Map;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,No));for(const e of i.keys())if(!n.valid(e)||!n.has(e,No)){if(n.valid(e)&&n.has(e,fe)){const t=n.get(e,fe);n.insert(e,fe,{texture:$,color:{r:t.color.r,g:t.color.g,b:t.color.b,a:t.color.a},size:{x:t.size.x,y:t.size.y},uvOffset:{x:t.uvOffset.x,y:t.uvOffset.y},uvScale:{x:t.uvScale.x,y:t.uvScale.y},layer:t.layer,flipX:t.flipX,flipY:t.flipY,material:t.material,enabled:t.enabled})}i.delete(e)}const e=n.getEntitiesWithComponents([No]);for(const t of e){const e=n.get(t,No),o=n.has(t,wo)?n.get(t,wo):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!Yo.changed(a,r)){if(n.has(t,fe)&&n.get(t,fe).texture!==$)continue}bo(n,t);const l=o?{size:{x:ko(o,t),y:Fo(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,fe);n.insert(t,fe,{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,Yo.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Go=new qo,Ko=0,Jo=1,Qo=re("UIMask",{enabled:!0,mode:Ko});function Zo(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 er(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],h=e[8],d=e[9],f=e[10],p=e[11],m=e[12],g=e[13],_=e[14],y=e[15],w=n*l-i*a,x=n*c-o*a,v=n*u-r*a,b=i*c-o*l,S=i*u-r*l,M=o*u-r*c,P=h*g-d*m,T=h*_-f*m,E=h*y-p*m,C=d*_-f*g,R=d*y-p*g,A=f*y-p*_;let I=w*A-x*R+v*C+b*E-S*T+M*P;return 0===I||(I=1/I,s[0]=(l*A-c*R+u*C)*I,s[1]=(o*R-i*A-r*C)*I,s[2]=(g*M-_*S+y*b)*I,s[3]=(f*S-d*M-p*b)*I,s[4]=(c*E-a*A-u*T)*I,s[5]=(n*A-o*E+r*T)*I,s[6]=(_*v-m*M-y*x)*I,s[7]=(h*M-f*v+p*x)*I,s[8]=(a*R-l*E+u*P)*I,s[9]=(i*E-n*R-r*P)*I,s[10]=(m*S-g*v+y*w)*I,s[11]=(d*v-h*S-p*w)*I,s[12]=(l*T-a*C-c*P)*I,s[13]=(n*C-i*T+o*P)*I,s[14]=(g*x-m*b-_*w)*I,s[15]=(h*b-d*x+f*w)*I),s}function tr(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],h=s[3]*a+s[7]*l+s[15];return{x:c/h,y:u/h}}function sr(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)}function nr(e,t){return 2*Math.atan2(e,t)}function ir(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 or(e,t,s,n,i,o,r,a,l,c){const u=nr(l,c),h=Math.sin(-u),d=Math.cos(-u),f=e-s,p=t-n,m=f*d-p*h+s,g=f*h+p*d+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)}function rr(e,t,s,n,i,o,r){if(!e.has(t,wo)||!e.has(t,ue))return null;const a=e.get(t,wo),l=e.get(t,ue),c=ko(a,t)*l.worldScale.x,u=Fo(a,t)*l.worldScale.y,h=l.worldPosition.x,d=l.worldPosition.y,f=a.pivot.x,p=a.pivot.y,m=-c*f,g=c*(1-f),_=-u*p,y=u*(1-p),w=nr(l.worldRotation.z,l.worldRotation.w),x=Math.cos(w),v=Math.sin(w),b=[[h+m*x-_*v,d+m*v+_*x],[h+g*x-_*v,d+g*v+_*x],[h+g*x-y*v,d+g*v+y*x],[h+m*x-y*v,d+m*v+y*x]];let S=1/0,M=1/0,P=-1/0,T=-1/0;for(const[e,t]of b){const[a,l]=ir(e,t,s,n,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 ar(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Qo]);if(0===l.length)return;const c=[],u=[],h=new Set,d=new Set;for(const e of l){const s=t.get(e,Qo);s.enabled&&(h.add(e),s.mode===Jo?(u.push(e),d.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;zo(t,e,e=>{if(i.has(e)){if(t.get(e,Qo).mode===Ko)return s=!1,!0}return!1}),s&&u.push(e)}function h(n,u){const d=e.getChildEntities(s,n);for(const s of d){let n=u;if(i.has(s)){if(t.get(s,Qo).mode===Ko){const e=rr(t,s,o,r,a,l,c);e&&(n=Zo(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),h(s,n)}}for(const e of u){const s=rr(t,e,o,r,a,l,c);s&&h(e,s)}}(e,t,s,c,h,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;zo(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,d)}catch(t){console.error("Mask processing error:",t),e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks()}}}class lr{build(e){if(ie("UIMask",Qo),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(ar(e.wasmModule,e.world))}}const cr=new lr,ur=re("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),hr=re("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),dr={Normal:0,Hovered:1,Pressed:2,Disabled:3},fr=K("Button",{state:dr.Normal,transition:null});class pr{constructor(){this.events_=[]}emit(e,t,s){const n=s??e;this.events_.push({entity:e,type:t,target:n,currentTarget:e})}drain(){const e=this.events_;return this.events_=[],e}query(e){return this.events_.filter(t=>t.type===e)}hasEvent(e,t){return this.events_.some(s=>s.entity===e&&s.type===t)}}const mr=ze(new pr,"UIEvents");class gr{build(e){ie("UIRect",wo);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){xo=e,vo=t}(s,n);e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Lt)],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(Mt.PostUpdate,Et([Ue(Lt)],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(Mt.PostUpdate,Et([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const _r=new gr;let yr=!1,wr=!1;function xr(e){yr=e}function vr(){return yr}function br(){return!yr}function Sr(e){wr=e}function Mr(){return wr}const Pr=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&&(er(t,e),s=!1),e)}}();function Tr(e,t,s,n){t.emit(s,n,s),zo(e,s,i=>{if(!e.has(i,ur))return!1;const o=e.get(i,ur);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class Er{build(e){ie("Interactable",ur),ie("Button",fr);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new pr;e.insertResource(mr,i);let o=null,r=null;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Bt),Ue(Lt)],(e,a)=>{if(i.drain(),vr()&&!Mr())return;const l=t.getEntitiesWithComponents([hr]);for(const e of l){const s=t.get(e,hr);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,hr,s))}if(!a.valid)return;const c=f(),u=e.mouseX*c,h=a.screenH-e.mouseY*c;Pr.update(a.viewProjection);const d=tr(u,h,Pr.getInverse(a.viewProjection),a.vpX,a.vpY,a.vpW,a.vpH);a.worldMouseX=d.x,a.worldMouseY=d.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,d.x,d.y,p,m,g);const _=s.uiHitTest_getHitEntity(),y=4294967295===_?null:_;if(null===o||t.valid(o)||(o=null),o!==y){if(null!==o&&t.valid(o)&&t.has(o,hr)){const e=t.get(o,hr);e.hovered=!1,t.insert(o,hr,e),i.emit(o,"hover_exit")}if(null!==y){Uo(t,y,hr);const e=t.get(y,hr);e.hovered=!0,t.insert(y,hr,e),i.emit(y,"hover_enter")}o=y}if(m&&null!==y){const e=t.get(y,hr);e.pressed=!0,e.justPressed=!0,t.insert(y,hr,e),r=y,Tr(t,i,y,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,hr)){const e=t.get(r,hr);e.pressed=!1,e.justReleased=!0,t.insert(r,hr,e),Tr(t,i,r,"release"),r===o&&Tr(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const a=new Set;e.addSystemToSchedule(Mt.Update,Et([],()=>{const e=t.getEntitiesWithComponents([fr]);for(const s of e){if(Uo(t,s,ur,{enabled:!0}),!t.has(s,hr))continue;const e=t.get(s,hr),n=t.get(s,fr),i=t.get(s,ur),o=!a.has(s),r=n.state;if(i.enabled?e.pressed?n.state=dr.Pressed:e.hovered?n.state=dr.Hovered:n.state=dr.Normal:n.state=dr.Disabled,o&&a.add(s),(o||r!==n.state)&&n.transition&&t.has(s,fe)){const o=t.get(s,fe);o.color=Eo(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,fe,o)}}},{name:"ButtonSystem"}))}}const Cr=new Er,Rr=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}),Ar=K("Focusable",{tabIndex:0,isFocused:!1});class Ir{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 kr=ze(new Ir,"FocusManager");class Fr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(ie("TextInput",Rr),vr()&&!Mr())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=h(F.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,c=!0,u=0,d=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(kr);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,Rr)?n:null}const g=()=>{l||null===m()||v()},_=()=>{l=!0},y=()=>{l=!1,v()},w=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void b();const i=s.get(n,Rr);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(mr).emit(n,"submit"),void b()}let o=i.cursorPos;"ArrowLeft"===t.key?o=Math.max(0,i.cursorPos-1):"ArrowRight"===t.key?o=Math.min(i.value.length,i.cursorPos+1):"Home"===t.key?o=0:"End"===t.key&&(o=i.value.length),o!==i.cursorPos&&(i.cursorPos=o,p.selectionStart=o,p.selectionEnd=o,i.dirty=!0,S())},x=()=>{const t=m();if(null!==t){const n=s.get(t,Rr);n.focused=!1,n.dirty=!0;e.getResource(kr).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,Rr);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(mr).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,S()}function b(){const t=m();if(null!==t){const e=s.get(t,Rr);e.focused=!1,e.dirty=!0}e.getResource(kr).blur(),p.blur()}function S(){c=!0,u=0}p.addEventListener("input",g),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",y),p.addEventListener("keydown",w),p.addEventListener("blur",x),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",y),p.removeEventListener("keydown",w),p.removeEventListener("blur",x),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,u,h){(i.width<u||i.height<h)&&(i.width=Ao(Math.max(i.width,u)),i.height=Ao(Math.max(i.height,h))),o.clearRect(0,0,i.width,i.height);const d=l.backgroundColor;o.fillStyle=`rgba(${Math.round(255*d.r)}, ${Math.round(255*d.g)}, ${Math.round(255*d.b)}, ${d.a})`,o.fillRect(0,0,u,h),o.save(),o.beginPath(),o.rect(l.padding,0,u-2*l.padding,h),o.clip(),o.font=`${l.fontSize}px ${l.fontFamily}`,o.textBaseline="top",o.textAlign="left";const f=0===l.value.length,p=f?l.placeholder:l.password?"●".repeat(l.value.length):l.value,m=f?l.placeholderColor:l.color;o.fillStyle=`rgba(${Math.round(255*m.r)}, ${Math.round(255*m.g)}, ${Math.round(255*m.b)}, ${m.a})`;const g=Math.ceil(1.2*l.fontSize),_=l.padding;if(l.multiline){const e=Ro(o,p,u-2*_);let t=_;for(const s of e)o.fillText(s,_,t),t+=g}else{const e=(h-l.fontSize)/2;o.fillText(p,_,e)}if(l.focused&&c){const e=l.password?"●".repeat(l.cursorPos):l.value.substring(0,l.cursorPos);let t,s,n;if(l.multiline){const e=Ro(o,l.value,u-2*_);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 c=r<e.length?e[r].substring(0,a):"";t=_+o.measureText(c).width,s=_+r*g,n=g}else t=_+o.measureText(e).width,s=(h-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 y=o.getImageData(0,0,u,h),w=new Uint8Array(y.data.buffer),x=t.getResourceManager();w.length>a&&(0!==r&&t._free(r),r=t._malloc(w.length),a=w.length),t.HEAPU8.set(w,r);const v=n.get(e);void 0!==v&&x.releaseTexture(v);const b=x.createTexture(u,h,r,w.length,1,!0);n.set(e,b);const S=s.get(e,fe);S.texture=b,S.size.x=u,S.size.y=h,S.uvOffset.x=0,S.uvOffset.y=0,S.uvScale.x=1,S.uvScale.y=1,S.color={r:1,g:1,b:1,a:1},s.insert(e,fe,S)}e.addSystemToSchedule(Mt.Update,Et([Ue(kr)],e=>{const t=s.getEntitiesWithComponents([Rr]);for(const e of t)Uo(s,e,Ar,{tabIndex:0,isFocused:!1}),Uo(s,e,ur,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,Rr)){const e=s.get(M,Rr);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,Rr);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),S())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now();let i=0===d?0:(e-d)/1e3;d=e,i=Math.min(i,.1);const o=m();if(null!==o&&(u+=i,u>=.5)){u-=.5,c=!c;s.get(o,Rr).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,Rr)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([Rr,wo]);for(const e of a){const t=s.get(e,Rr);if(!t.dirty)continue;const n=s.get(e,wo),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(bo(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const Br=new Fr,zr={Simple:0,Sliced:1,Tiled:2,Filled:3},Ur={Horizontal:0,Vertical:1},Lr={Left:0,Right:1,Bottom:2,Top:3},$r=K("Image",{texture:$,color:{r:1,g:1,b:1,a:1},imageType:zr.Simple,fillMethod:Ur.Horizontal,fillOrigin:Lr.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),Dr=$o({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?ko(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?Fo(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class Or{build(e){ie("Image",$r);const t=e.world,s=new Map;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,$r)||s.delete(e);const e=t.getEntitiesWithComponents([$r]);for(const n of e){const e=t.get(n,$r),i=t.has(n,wo)?t.get(n,wo):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!Dr.changed(r,o))continue;bo(t,n);const a=t.get(n,fe);if(e.enabled){if(a.texture=e.texture,a.color.r=e.color.r,a.color.g=e.color.g,a.color.b=e.color.b,a.color.a=e.color.a,a.layer=e.layer,a.material=e.material,i&&(a.size.x=ko(i,n),a.size.y=Fo(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===zr.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===Ur.Horizontal?e.fillOrigin===Lr.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===Lr.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===zr.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,fe,a),s.set(n,Dr.take(o))}else a.color.a=0,t.insert(n,fe,a),s.set(n,Dr.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const Wr=new Or,Hr=K("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Vr=K("ToggleGroup",{allowSwitchOff:!1});class jr{build(e){ie("Toggle",Hr),ie("ToggleGroup",Vr);const t=e.world,s=new Set;e.addSystemToSchedule(Mt.Update,Et([Ue(mr)],e=>{const n=t.getEntitiesWithComponents([Hr]);if(!vr()||Mr()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,Hr);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,Hr,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,Hr);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(Uo(t,s,ur,{enabled:!0}),!t.has(s,hr))continue;const n=t.get(s,hr),i=t.get(s,Hr),r=t.get(s,ur);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Vr);if(i.isOn&&r){if(!t.get(n,Vr).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,Hr,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,Hr);i.isOn&&(i.isOn=!1,t.insert(n,Hr,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,fe)){const e=t.get(s,fe);e.color=Eo(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,fe,e)}}}for(const e of n){const s=t.get(e,Hr);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,fe)){const e=t.get(s.graphicEntity,fe);e.enabled=s.isOn,t.insert(s.graphicEntity,fe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Nr=new jr,Xr=_o,Yr=K("ProgressBar",{value:0,fillEntity:0,direction:_o.LeftToRight});function qr(e,t,s,n){if(!e.has(t,wo))return;const i=e.get(t,wo),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=yo(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,fe)){const s=e.get(t,fe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,fe,s))}if(e.has(t,ue)){const s=e.get(t,ue),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,ue,s))}}class Gr{build(e){ie("ProgressBar",Yr);const t=e.world;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{const e=t.getEntitiesWithComponents([Yr,wo]);for(const s of e){const e=t.get(s,Yr);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,wo),i=Math.max(0,Math.min(1,e.value));To(t,e.fillEntity,e.direction,i);const o=ko(n,s),r=Fo(n,s);qr(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Kr=new Gr,Jr=K("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Qr=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 Zr{build(e){ie("Draggable",Jr),ie("DragState",Qr);const t=e.world,s=e.getResource(mr);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Bt),Ue(Lt)],(e,r)=>{if(vr()&&!Mr())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Jr,hr]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Jr).enabled)continue;if(t.get(n,hr).hovered){let e=0;t.has(n,fe)&&(e=t.get(n,fe).layer);const i=Io(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,Qr)||t.insert(s,Qr);const e=t.get(s,Qr),o=t.get(s,ue);e.startWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.currentWorldPos={x:o.worldPosition.x,y:o.worldPosition.y},e.pointerStartWorld={x:a.x,y:a.y},e.deltaWorld={x:0,y:0},e.totalDeltaWorld={x:0,y:0},e.isDragging=!1}}if(null!==n&&!e.isMouseButtonDown(0)){if(t.valid(n)&&t.has(n,Qr)){t.get(n,Qr).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,Jr);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Qr).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Qr))return void(o=null);const n=t.get(o,Qr),i=t.get(o,Jr),r=a.x-n.pointerStartWorld.x,l=a.y-n.pointerStartWorld.y;let c=n.startWorldPos.x+r,u=n.startWorldPos.y+l;const h=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=h.x,u=h.y;const d=n.currentWorldPos.x,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-d,y:u-f},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,ue)){const e=function(e,t,s,n){if(!e.has(t,_e))return{x:s,y:n};const i=e.get(t,_e).entity;if(!e.valid(i)||!e.has(i,ue))return{x:s,y:n};const o=e.get(i,ue),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=nr(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,ue);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,ue,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const ea=new Zr,ta=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 sa(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 na(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 ia{build(e){ie("ScrollView",ta);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(Mt.PostUpdate,Et([Ue(Bt),Ue(Lt),Ue(Oe)],(e,i,o)=>{const r=vr()&&!Mr(),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([ta,wo]);for(const o of l){Uo(t,o,Qo,{enabled:!0,mode:Ko});const l=t.get(o,ta),c=t.get(o,wo);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 h=ko(c,o),d=Fo(c,o);let f=l.contentWidth,p=l.contentHeight;if((0===f||0===p)&&0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ye)){const e=t.get(l.contentEntity,ye).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,ue))continue;const e=t.get(r,ue);let a=0,l=0,c=.5,u=.5;if(t.has(r,wo)){const e=t.get(r,wo);a=ko(e,r)||e.size.x,l=Fo(e,r)||e.size.y,c=e.pivot.x,u=e.pivot.y}else if(t.has(r,fe)){const e=t.get(r,fe);a=e.size.x,l=e.size.y}const h=e.position.x-a*c,d=e.position.x+a*(1-c),f=e.position.y-l*u,p=e.position.y+l*(1-u);h<s&&(s=h),d>n&&(n=d),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-h),g=Math.max(0,p-d);if(!r&&i.valid){Uo(t,o,ur,{enabled:!0,blockRaycast:!0});const s=t.has(o,hr)?t.get(o,hr):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=sa(l.scrollX,0,m,h);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=sa(l.scrollY,0,g,d);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*h,t=5*d;u.velocityX=Math.max(-e,Math.min(u.velocityX,e)),u.velocityY=Math.max(-t,Math.min(u.velocityY,t))}if(s?.hovered){const t=e.getScrollDelta();if(l.verticalEnabled&&0!==t.y){const e=sa(l.scrollY,0,g,d);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=sa(l.scrollX,0,m,h);l.scrollX+=t.x*l.wheelSensitivity*e,u.velocityX=0}}}if(!u.isDragging&&a>0){const e=l.scrollX<0||l.scrollX>m,t=l.scrollY<0||l.scrollY>g;if(l.elastic&&e){const e=l.scrollX<0?0:m,t=na(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)<Do&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Do?(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=na(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)<Do&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Do?(u.velocityY*=Math.pow(l.decelerationRate,a),l.scrollY+=u.velocityY*a):u.velocityY=0);if(!l.elastic){const e=l.scrollX,t=l.scrollY;l.scrollX=Math.max(0,Math.min(l.scrollX,m)),l.scrollY=Math.max(0,Math.min(l.scrollY,g)),l.scrollX!==e&&(u.velocityX=0),l.scrollY!==t&&(u.velocityY=0)}}if(l.elastic){const e=.5*h,t=.5*d;l.scrollX=Math.max(-e,Math.min(l.scrollX,m+e)),l.scrollY=Math.max(-t,Math.min(l.scrollY,g+t))}if(0!==l.contentEntity&&t.valid(l.contentEntity)&&t.has(l.contentEntity,ue)){const e=t.get(l.contentEntity,ue),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,ue,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const oa=new ia,ra=_o,aa=K("Slider",{value:0,minValue:0,maxValue:1,direction:_o.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function la(e,t,s,n,i,o){const r=ko(n,i)*s.worldScale.x,a=Fo(n,i)*s.worldScale.y,l=nr(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),h=e-s.worldPosition.x,d=t-s.worldPosition.y,f=h*u-d*c,p=h*c+d*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case _o.LeftToRight:return r>0?(f-m)/r:0;case _o.RightToLeft:return r>0?1-(f-m)/r:0;case _o.BottomToTop:return a>0?(p-g)/a:0;case _o.TopToBottom:return a>0?1-(p-g)/a:0}}function ca(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case _o.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case _o.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case _o.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case _o.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class ua{build(e){ie("Slider",aa);const t=e.world;let s=null;e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Bt),Ue(Lt),Ue(mr)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([aa,wo]);for(const r of o){const o=t.get(r,aa),a=t.get(r,wo);if(!vr()||Mr()){if(t.has(r,ue)){Uo(t,r,ur,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&Uo(t,o.handleEntity,ur,{enabled:!0,blockRaycast:!1});const l=t.get(r,ue),c=t.has(r,hr)?t.get(r,hr):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,hr)&&(u=t.get(o.handleEntity,hr).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=la(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,aa,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=ko(a,r),h=Fo(a,r),d={left:-u/2,bottom:-h/2,right:u/2,top:h/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(To(t,o.fillEntity,o.direction,c),Lo(t,o.fillEntity,d,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,wo)){const e=t.get(o.handleEntity,wo);ca(e,o.direction,c),t.insert(o.handleEntity,wo,e),Lo(t,o.handleEntity,d,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const ha=new ua;class da{build(e){ie("Focusable",Ar);const t=e.world,s=new Ir;e.insertResource(kr,s),e.addSystemToSchedule(Mt.Update,Et([Ue(Bt),Ue(mr)],(e,n)=>{if(vr()&&!Mr())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([Ar]);for(const e of i){if(!t.has(e,hr))continue;t.get(e,hr).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,ur)){if(!t.get(s,ur).enabled)continue}const n=t.get(s,Ar);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,Ar)){t.get(i,Ar).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,Ar).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const fa=new da,pa=K("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function ma(){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: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 ga{build(e){ie("SafeArea",pa);const t=e.world;let s=ma(),n=!0,o=0,r=0;if(i()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=ma(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=ma(),n=!0});e.addSystemToSchedule(Mt.PreUpdate,Et([Ue(Lt)],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,n=!0),!n)return;n=!1;const l=f(),c=i()?a/e.screenH:l*a/e.screenH,u=t.getEntitiesWithComponents([pa,wo]);for(const e of u){const n=t.get(e,pa),i=t.get(e,wo),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.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,wo,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const _a=new ga,ya=K("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let wa=null;function xa(e,t){if(!wa)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=wa.get(e);s?s.renderer=t:wa.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class va{build(e){ie("ListView",ya);const t=e.world,s=new Map;wa=s,e.addSystemToSchedule(Mt.PostUpdate,Et([Ue(Bt)],e=>{const n=vr()&&!Mr();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([ya,wo]);for(const o of i){Uo(t,o,ur,{enabled:!0,blockRaycast:!0}),Uo(t,o,Qo,{enabled:!0,mode:Ko});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,ya),a=t.get(o,wo),l=Fo(a,o),c=ko(a,o);if(!n){const s=t.has(o,hr)?t.get(o,hr):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 h=Math.max(0,Math.floor(r.scrollY/r.itemHeight)-r.overscan),d=Math.min(r.itemCount,Math.ceil((r.scrollY+l)/r.itemHeight)+r.overscan);for(const[e,s]of i.itemEntities)(e<h||e>=d)&&(t.valid(s)&&t.despawn(s),i.itemEntities.delete(e));for(let e=h;e<d;e++){let s=i.itemEntities.get(e);if(s&&t.valid(s)||(s=t.spawn(),t.insert(s,Pe,{value:`ListItem_${e}`}),t.insert(s,wo,{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,ue)){const n=t.get(s,ue);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,ue,n)}}i.visibleStart=h,i.visibleEnd=d}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const ba=new va,Sa=K("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class Ma{build(e){ie("Dropdown",Sa);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,ue))return;const s=t.get(e,ue);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,ue,{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,fe)){const s=t.get(e,fe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,fe,{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,fe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Oo;t.insert(i,wo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:0},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:l},pivot:{x:.5,y:.5}}),t.insert(i,ue,{position:{x:0,y:-(a+l)/2,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(i,fe,{texture:$,color:{r:1,g:1,b:1,a:1},size:{x:r,y:l},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0});for(let e=0;e<s.options.length;e++){const o=t.spawn(),a=l/2-(e+.5)*Oo;t.insert(o,Pe,{value:`Option_${e}`}),t.insert(o,wo,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Oo},offsetMax:{x:0,y:0},size:{x:r,y:Oo},pivot:{x:.5,y:.5}}),t.insert(o,ue,{position:{x:0,y:a,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(o,fe,{texture:$,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Oo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,ur,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,ue,{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),t.insert(c,No,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Ho.Left,verticalAlign:Vo.Middle,wordWrap:!1,overflow:jo.Clip,lineHeight:1.2}),t.insert(c,wo,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Oo},pivot:{x:.5,y:.5}}),t.setParent(c,o),n.textEntities.push(c)}h(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,No))return;const n=t.get(s,No);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,No,{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,ur)&&t.insert(e,ur,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,fe))){const n=t.get(e,fe);t.insert(e,fe,{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 h(e){for(let s=0;s<e.optionEntities.length;s++){const n=e.optionEntities[s];if(!t.valid(n)||!t.has(n,fe))continue;const i=s===e.highlightIndex?{...Wo}:{r:.95,g:.95,b:.95,a:1};t.insert(n,fe,{texture:$,color:i,size:{x:e.ddWidth,y:Oo},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0})}}function d(e){for(const s of e.optionEntities){if(!t.valid(s)||!t.has(s,hr))continue;if(t.get(s,hr).hovered)return!0}return!1}e.addSystemToSchedule(Mt.Update,Et([Ue(Bt),Ue(mr)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=vr()&&!Mr(),p=t.getEntitiesWithComponents([Sa]);for(const m of p){const p=t.get(m,Sa);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;Uo(t,m,ur,{enabled:!0,blockRaycast:!0});const _=t.has(m,hr)?t.get(m,hr):null;if(_?.justPressed&&(p.isOpen?r(m,p,g):o(m,p,g)),p.isOpen){for(let e=0;e<g.optionEntities.length;e++){const s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,hr))continue;if(t.get(s,hr).justPressed){a(m,p,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,hr))continue;if(t.get(n,hr).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,h(g)),e.isKeyPressed("ArrowDown")?(g.highlightIndex>=p.options.length-1?g.highlightIndex=0:g.highlightIndex++,h(g)):e.isKeyPressed("ArrowUp")?(g.highlightIndex<=0?g.highlightIndex=p.options.length-1:g.highlightIndex--,h(g)):e.isKeyPressed("Enter")&&g.highlightIndex>=0?a(m,p,g,g.highlightIndex,c):e.isKeyPressed("Escape")&&r(m,p,g),e.isMouseButtonPressed(0)&&(_?.hovered||d(g)||r(m,p,g))}}},{name:"DropdownSystem"}),{runAfter:["UIInteractionSystem"]})}}const Pa=new Ma,Ta=0,Ea=0,Ca=2,Ra=K("LayoutGroup",{direction:Ta,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:Ea,reverseOrder:!1});class Aa{build(e){ie("LayoutGroup",Ra);const t=e.world;e.addSystemToSchedule(Mt.PreUpdate,Et([],()=>{const e=t.getEntitiesWithComponents([Ra,wo,ye]);for(const s of e){const e=t.get(s,Ra),n=t.get(s,wo),i=t.get(s,ye);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,wo)&&t.has(e,ue)&&o.push({entity:e,rect:t.get(e,wo)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=ko(n,s),a=Fo(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,h=e.direction===Ta;let d=0;for(let s=0;s<o.length;s++){const n=o[s],i=ko(n.rect,n.entity),f=Fo(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let g,_;h?(g=-l*r+u.left+d+p*i,_=e.childAlignment===Ea?(1-c)*a-u.top-(1-m)*f:e.childAlignment===Ca?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,d+=i,s<o.length-1&&(d+=e.spacing)):(g=e.childAlignment===Ea?-l*r+u.left+p*i:e.childAlignment===Ca?(1-l)*r-u.right-(1-p)*i:(.5-l)*r+.5*(u.left-u.right)+(p-.5)*i,_=(1-c)*a-u.top-d-(1-m)*f,d+=f,s<o.length-1&&(d+=e.spacing));const y=t.get(n.entity,ue);y.position.x=g,y.position.y=_,t.insert(n.entity,ue,y)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const Ia=new Aa;class ka{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(Mt.PostUpdate,Et([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const Fa=new ka;async function Ba(e,t,s){const n=e.getResource(Ji);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function za(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 Ua=ze({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),La={r:.2,g:.4,b:1,a:.7},$a={r:.2,g:1,b:.2,a:.7},Da={r:.2,g:1,b:1,a:.7},Oa={r:1,g:1,b:.2,a:.5},Wa={r:1,g:.2,b:.2,a:.8},Ha={r:1,g:.2,b:.2,a:1},Va=1.5,ja=16;function Na(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Xa(e){switch(e){case Fe.Static:return La;case Fe.Kinematic:return Da;default:return $a}}function Ya(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++)Vn.line(l[e],l[(e+1)%4],o,Va)}function qa(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),h=l(-s,-n),d=l(s,-n);Vn.line(c,h,o,Va),Vn.line(u,d,o,Va);for(let e=0;e<ja;e++){const t=e/ja*Math.PI,i=(e+1)/ja*Math.PI,r=l(-s*Math.cos(t),n+s*Math.sin(t)),a=l(-s*Math.cos(i),n+s*Math.sin(i));Vn.line(r,a,o,Va)}for(let e=0;e<ja;e++){const t=Math.PI+e/ja*Math.PI,i=Math.PI+(e+1)/ja*Math.PI,r=l(-s*Math.cos(t),-n+s*Math.sin(t)),a=l(-s*Math.cos(i),-n+s*Math.sin(i));Vn.line(r,a,o,Va)}}function Ga(e,t,s,n){const i=e+.5*s,o=t+.5*n;Vn.line({x:e,y:t},{x:i,y:o},Wa,Va);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)),h=o-6*(l*Math.sin(a)+c*Math.cos(a)),d=i-6*(l*Math.cos(a)+c*Math.sin(a)),f=o-6*(-l*Math.sin(a)+c*Math.cos(a));Vn.line({x:i,y:o},{x:u,y:h},Wa,Va),Vn.line({x:i,y:o},{x:d,y:f},Wa,Va)}function Ka(e,t,s){const n=e.getResource(Ua);if(!n||!n.enabled)return;const i=function(e){const t=e.world.getEntitiesWithComponents([me]);for(const s of t){const t=e.world.get(s,me);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=e.world.getEntitiesWithComponents([Re,ue]);let r=null;n.showVelocity&&e.hasResource(t)&&(r=e.getResource(t));for(const t of o){const s=e.world.get(t,Re);if(!s.enabled)continue;const o=e.world.get(t,ue),a=o.worldPosition.x,l=o.worldPosition.y,c=Na(o.worldRotation);if(n.showColliders){if(e.world.has(t,Ae)){const n=e.world.get(t,Ae),o=n.isSensor?Oa:Xa(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c);Ya(a+r*h-u*d,l+r*d+u*h,n.halfExtents.x*i,n.halfExtents.y*i,c,o)}if(e.world.has(t,Ie)){const n=e.world.get(t,Ie),o=n.isSensor?Oa:Xa(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c),f=a+r*h-u*d,p=l+r*d+u*h;Vn.circleOutline({x:f,y:p},n.radius*i,o,Va,32)}if(e.world.has(t,ke)){const n=e.world.get(t,ke),o=n.isSensor?Oa:Xa(s.bodyType),r=n.offset.x*i,u=n.offset.y*i,h=Math.cos(c),d=Math.sin(c);qa(a+r*h-u*d,l+r*d+u*h,n.radius*i,n.halfHeight*i,c,o)}}if(n.showVelocity&&r&&s.bodyType===Fe.Dynamic){const e=r.getLinearVelocity(t);Ga(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)Vn.circle({x:e.contactX,y:e.contactY},3,Ha,!0,32)}}const Ja=ze({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Qa=ze(null,"PhysicsAPI");function Za(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function el(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class tl{constructor(e,t={},s){this.wasmUrl_=e,this.factory_=s,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(Ja,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=za(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([me]);for(const s of t){const t=e.world.get(s,me);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(Mt.PostUpdate,Et([Ue(Oe)],a=>{const l=r.getEntitiesWithComponents([Re,ue]),c=new Set;for(const i of l){c.add(i);const a=r.get(i,Re),l=r.get(i,ue);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=Za(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),sl(e,n,i),t.add(i),s.set(i,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===Fe.Kinematic){const e=Za(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,ue);if(!u)continue;let h=a,d=l,f=c;if(e.world.has(r,_e)){const t=e.world.get(r,_e);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,ue)){const s=e.world.get(t.entity,ue),n=Za(s.worldRotation),i=a-s.worldPosition.x,o=l-s.worldPosition.y,r=Math.cos(-n),u=Math.sin(-n);h=(i*r-o*u)/(0!==s.worldScale.x?s.worldScale.x:1),d=(i*u+o*r)/(0!==s.worldScale.y?s.worldScale.y:1),f=c-n}}u.position.x=h,u.position.y=d;const p=el(f);u.rotation.w=p.w,u.rotation.x=p.x,u.rotation.y=p.y,u.rotation.z=p.z,e.world.insert(r,ue,u)}}(e,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(Ja,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:c})}(e,n,i)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Qa,nl._fromModule(n)),function(e,t,s){e.insertResource(Ua,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),qn("physics-debug-draw",()=>{Ka(e,t,s)})}(e,Qa,Ja),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=n}}function sl(e,t,s){const n=e.world;if(n.has(s,Ae)){const e=n.get(s,Ae);return void t._physics_addBoxShape(s,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,Ie)){const e=n.get(s,Ie);return void t._physics_addCircleShape(s,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(n.has(s,ke)){const e=n.get(s,ke);t._physics_addCapsuleShape(s,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class nl{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(nl.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(Ua);s&&(s.enabled=t,e.insertResource(Ua,s))}static setDebugDrawConfig(e,t){const s=e.getResource(Ua);s&&e.insertResource(Ua,{...s,...t})}}const il={nearest:0,linear:1},ol={repeat:0,clamp:1,mirror:2};function rl(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=il[n.filterMode??"linear"]??1,a=ol[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 al(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 ll(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,h=a+a,d=l+l,f=c+c,p=a*h,m=a*d,g=a*f,_=l*d,y=l*f,w=c*f,x=u*h,v=u*d,b=u*f;return new Float32Array([(1-(_+w))*i,(m+b)*i,(g-v)*i,0,(m-b)*o,(1-(p+w))*o,(y+x)*o,0,(g+v)*r,(y-x)*r,(1-(p+_))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function cl(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=Os(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]=rl(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 h={},d=null;if(o&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(o),h=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=Ws(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"===on(c)?.contentType;let h,d;if(r){const e=await i.readBinary(a);d=e.length,h=t._malloc(d),t.HEAPU8.set(e,h)}else{const e=await i.readText(a),s=(new TextEncoder).encode(e);d=s.length,h=t._malloc(d+1),t.HEAPU8.set(s,h),t.HEAPU8[h+d]=0}const f=s.loadSkeleton(h,d,n,n.length,r);if(t._free(h),f<0)continue;o[a]=f;const p=al(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=rl(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(s,o,d,n,i)),r){const e={gravity:a?.gravity??{...A},fixedTimestep:a?.fixedTimestep??I,subStepCount:a?.subStepCount??4};new tl("",e,()=>Promise.resolve(r)).build(t)}const f=await async function(e,t,s){const n={};for(const i of t.entities)for(const t of i.components){const i=Os(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=on(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=rl(e,c,!1),h=e.getResourceManager();n[o]=h.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(s,n,i),p=await async function(e,t){const s={},n={};for(const i of e.entities)for(const e of i.components){if(!e.data)continue;const i=Os(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=Yt.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=Yt.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=Os(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=is(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,rl(e,n))}catch{r.set(t,0)}as(os(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=Os(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=Is(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=ks(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=rl(e,t),gs(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}ws(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=Os(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 fs.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await fs.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=Os(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,f,p);const m=Ys(t.world,n);if(c&&t.hasResource(Ji))for(const e of m.values())t.world.insert(e,Te,{scene:c,persistent:!1});if(o&&d){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=Ws(t.type);if(!r||!t.data)continue;const a=s[t.data[r.skeletonField]];if(void 0===a)continue;const l=e.createInstance(a);if(l<0)continue;const c=n.get(o.id);void 0!==c&&(i[c]=l),t.data.animation&&e.playAnimation(l,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(l,t.data.skin)}return i}(d,n,h,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=R);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,xe)?c.get(o,xe):null,u=!1!==a?.playing,h=a?.timeScale??1;u&&n.update(r,l*h);let d=0;if(c.has(o,ue)){const e=ll(c.get(o,ue),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;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),h=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(r,e,c,u,h,f);const p=s.HEAPU32[h>>2],m=s.HEAPU32[f>>2],g=new Float32Array(s.HEAPF32.buffer,c,8*i),_=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),w=t._malloc(l);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,w,o).set(_),t.renderer_submitTriangles(y,i,w,o,p,m,d),t._free(y),t._free(w),s._free(c),s._free(u),s._free(h),s._free(f)}d&&t._free(d)}})}(t,s,o,d,e)}if(l){const e=t.getResource(xn);e&&e.setAddressableManifest(l)}}function ul(e,t,s){return{name:e,async setup(){await cl({...s,sceneData:t,sceneName:e})}}}async function hl(e){const{app:t,firstScene:s,aspectRatio:n}=e;so(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(Ji);for(const t of e.scenes)o.register(ul(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&Js(t.world,n)}class dl{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=Ws(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===on(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=Os(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=on(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 fl="__preview__";class pl{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(Ji);t.register({name:fl,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(fl),this.loadPromise_=t.load(fl).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(),s=new dl(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await cl({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:fl})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([pe]);for(const n of s){if(e.get(n,pe).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([me]);for(const i of n){const n=e.get(i,me);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(Ji).getScene(fl),o=i?i.spawn():e.spawn(),r={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1},worldPosition:{x:0,y:0,z:10},worldRotation:{x:0,y:0,z:0,w:1},worldScale:{x:1,y:1,z:1}};e.insert(o,ue,r);const a={isActive:!0,projectionType:ae.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:le.ColorAndDepth};e.insert(o,pe,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(Ji);await e.switchTo(fl),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 ml={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Wi.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Wi.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Wi.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Wi.releaseRenderTarget(e._handle),ml.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Wi.begin(t,e._handle)},end(){Wi.end()},getDepthTexture:e=>Wi.getTargetDepthTexture(e._handle)};var gl;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(gl||(gl={}));class _l{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${gl[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case gl.Debug:console.debug(t,s);break;case gl.Info:console.log(t,s);break;case gl.Warn:console.warn(t,s);break;case gl.Error:console.error(t,s)}}}class yl{constructor(){this.handlers_=[],this.minLevel_=gl.Info,this.addHandler(new _l)}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(gl.Debug,e,t,s)}info(e,t,s){this.log(gl.Info,e,t,s)}warn(e,t,s){this.log(gl.Warn,e,t,s)}error(e,t,s){this.log(gl.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 wl=new yl;function xl(){return wl}function vl(e){wl.setMinLevel(e)}function bl(e,t,s){wl.debug(e,t,s)}function Sl(e,t,s){wl.info(e,t,s)}function Ml(e,t,s){wl.warn(e,t,s)}function Pl(e,t,s){wl.error(e,t,s)}const Tl={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},El={Running:0,Paused:1,Completed:2,Cancelled:3},Cl={None:0,Restart:1,PingPong:2};const Rl=1.70158,Al=2.70158,Il=2.5949095;const kl=2*Math.PI/3,Fl=2*Math.PI/4.5;const Bl=7.5625,zl=2.75;const Ul=1e-6;function Ll(e,t,s){switch(e){case Tl.Linear:return t;case Tl.EaseInQuad:return function(e){return e*e}(t);case Tl.EaseOutQuad:return function(e){return e*(2-e)}(t);case Tl.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Tl.EaseInCubic:return function(e){return e*e*e}(t);case Tl.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Tl.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Tl.EaseInBack:return function(e){return Al*e*e*e-Rl*e*e}(t);case Tl.EaseOutBack:return function(e){const t=e-1;return 1+Al*t*t*t+Rl*t*t}(t);case Tl.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-Il)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+Il)+2)/2}(t);case Tl.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*kl)}(t);case Tl.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*kl)+1}(t);case Tl.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*Fl)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*Fl)/2+1}(t);case Tl.EaseOutBounce:return function(e){return e<1/zl?Bl*e*e:e<2/zl?Bl*(e-=1.5/zl)*e+.75:e<2.5/zl?Bl*(e-=2.25/zl)*e+.9375:Bl*(e-=2.625/zl)*e+.984375}(t);case Tl.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)<Ul)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)<Ul)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 Tl.Step:return function(e){return e<1?0:1}(t);default:return t}}const $l=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??Tl.Linear,bezierPoints:null,state:El.Running,loop:i?.loop??Cl.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)===El.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==El.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=Ll(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==Cl.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Cl.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=El.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===El.Running&&(t.state=El.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===El.Paused&&(t.state=El.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=El.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:El.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 Dl{constructor(e){this.id=e}get state(){return $l.getState(this.id)}bezier(e,t,s,n){return $l.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Dl?$l.setSequenceNext(this.id,e.id):$l.setSequenceNextExternal(this.id,e),this}pause(){$l.pause(this.id)}resume(){$l.resume(this.id)}cancel(){$l.cancel(this.id)}}const Ol={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 Wl{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 Dl?($l.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 Hl=null,Vl=null;function jl(e,t){Hl=e,Vl=t,$l.init(e,t)}function Nl(){$l.shutdown(),Hl=null,Vl=null}function Xl(){if(!Hl)throw new Error("Tween API not initialized");return Hl}function Yl(){if(!Vl)throw new Error("Tween API not initialized");return Vl}const ql={to(e,t,s,n,i,o){const r=Xl(),a=Yl(),l=o?.easing??Tl.Linear,c=o?.delay??0,u=o?.loop??Cl.None,h=o?.loopCount??0,d=r._anim_createTween(a,e,t,s,n,i,l,c,u,h);return new Wl(r,a,d)},value(e,t,s,n,i){const o=$l.create(e,t,s,n,i);return new Dl(o)},cancel(e){Xl()._anim_cancelTween(Yl(),e.entity)},cancelAll(e){Xl()._anim_cancelAllTweens(Yl(),e)},update(e){Xl()._anim_updateTweens(Yl(),e),$l.update(e)}};class Gl{constructor(){this.name="AnimationPlugin"}build(e){jl(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(Mt.Update,Et([Ue(Oe)],e=>{ql.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(Mt.Update,Et([Ue(Oe)],e=>{ds(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){Nl()}}const Kl=new Gl;var Jl;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(Jl||(Jl={}));const Ql={model:Jl.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function Zl(e,t=Ql){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case Jl.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case Jl.Inverse:a=n/Math.max(r,n);break;case Jl.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function ec(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const tc=K("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:Jl.Inverse,rolloff:1,priority:0,enabled:!0}),sc=K("AudioListener",{enabled:!0});class nc{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;fs.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(Mt.PreUpdate,Et([Ue(Oe)],t=>{if(!(!vr()||Mr()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,h=!1;const d=n.getEntitiesWithComponents([sc,de]);for(const e of d){if(n.get(e,sc).enabled){const t=n.get(e,de);i=t.position.x,u=t.position.y,h=!0;break}}const f=n.getEntitiesWithComponents([tc]);a.clear();for(const e of f){const t=n.get(e,tc);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=fs.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}h||l||(console.warn("[AudioPlugin] spatial audio used but no AudioListener entity found"),l=!0);const r=n.tryGet?.(e,de),a=r?.position.x??0,d=r?.position.y??0,f=a-i,p=d-u,m=Zl(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=ec(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(),fs.dispose()}}const ic=new nc;let oc=null,rc=null;function ac(e,t){oc=e,rc=t}function lc(){oc=null,rc=null}const cc={update(e){oc&&rc&&oc.particle_update?.(rc,e)},play(e){oc&&rc&&oc.particle_play?.(rc,e)},stop(e){oc&&rc&&oc.particle_stop?.(rc,e)},reset(e){oc&&rc&&oc.particle_reset?.(rc,e)},getAliveCount:e=>oc?oc.particle_getAliveCount?.(e)??0:0};class uc{constructor(){this.name="ParticlePlugin"}build(e){ac(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(Mt.Update,Et([Ue(Oe)],e=>{cc.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){lc()}}const hc=new uc,dc=1e6;class fc{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){Ss(e.wasmModule);const t=e.world,s=this.initializedLayers_,n=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const i=e.getResource(Lt),o=i?.valid?i.worldLeft:-1e6,r=i?.valid?i.worldBottom:-1e6,a=i?.valid?i.worldRight:dc,l=i?.valid?i.worldTop:dc,c=t.getEntitiesWithComponents([Es,ue]);for(const e of c){const n=t.tryGet(e,Es),i=t.tryGet(e,ue);if(!n||!i)continue;if(!n.visible)continue;const c=n.texture;if(!c)continue;const u=_s(c);if(!u)continue;if(!s.has(e)){if(Ps.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];Ps.setTiles(e,t)}s.add(e)}const h=n.tileWidth/u.width,d=n.tileHeight/u.height,f=n.tint,p=n.parallaxFactor;Ps.submitLayer(e,c,n.layer,0,n.tilesetColumns,h,d,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,n.opacity,p.x,p.y)}const u=t.getEntitiesWithComponents([Ts,ue]);for(const e of u){if(t.tryGet(e,Es))continue;const i=t.tryGet(e,Ts),c=t.tryGet(e,ue);if(!i?.source||!c)continue;const u=xs(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];Ps.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&Ps.setTiles(i,o.tiles),t.push(i),s.add(i)}n.set(e,t)}const h=n.get(e);for(let e=0;e<u.layers.length&&e<h.length;e++){const t=h[e],s=u.tilesets[0];if(!s)continue;const n=_s(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,d=u.tileHeight/n.height;Ps.submitLayer(t,s.textureHandle,e,0,s.columns,i,d,c.worldPosition.x,c.worldPosition.y,o,r,a,l,1,1,1,1,1,1,1)}}})}cleanup(){for(const e of this.initializedLayers_)Ps.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),ys(),Ms()}}const pc=new fc;function mc(e,t){return e.toFixed(t)}function gc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class _c{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">${mc(e.fps,1)}</span> Frame: <span style="color:#d19a66">${mc(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>${gc(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${mc(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 yc(){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 wc=ze(yc(),"Stats");class xc{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}}const vc="StatsCollect";class bc{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 Sc{constructor(e){this.name="Stats",this.collector_=new bc,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(wc,yc());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new _c(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=Et([Ue(Oe),{_type:"get_world"}],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(wc);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(vc),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Wi.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:vc});e.addSystemToSchedule(Mt.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Mc=new Sc;class Pc{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 Tc(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}}async function Ec(e){const{app:t,module:s,assets:n,scenes:i,firstScene:o}=e,r=t.getResource(xn);r&&(r.registerEmbeddedAssets(n),r.setEmbeddedOnly(!0));const a=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Tc(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 Tc(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,c=new Pc(n);await hl({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()}const Cc=[Go,cr,_r,Wr,Kr,Cr,ea,oa,ha,Nr,Br,fa,_a,ba,Pa,Ia,Fa],Rc=[...Cc,Kl,ic,hc,pc,zi];function Ac(e,t){return function(e,t){const s=to.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Dn(e),jt(e),si(e),pi(e),Di(e),Vi(e);const i=new Xi;s.setPipeline(i);let o=d();const r=t?.getViewportSize??(()=>{const e=f();return{width:window.innerWidth*e,height:window.innerHeight*e}});function a(t,i,o){o||(o=ao(e,n,t,i));const r=s.getResource(Lt);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(Lt,{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(n);if(c>=0){const e=n.getCanvas(c).backgroundColor;Wi.setClearColor(e.x,e.y,e.z,e.w)}const u=(d()-o)/1e3;let h;if(Wi.resize(t,l),s.hasResource(Ji)){const e=s.getResource(Ji).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=ao(e,n,t,l,s.world,h);if(a(t,l,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:no,width:t,height:l,elapsed:u});else{i.beginScreenCapture();for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),r=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:r,w:a,h:c},clearFlags:e.clearFlags,elapsed:u,cameraEntity:e.entity})}i.endScreenCapture(),Wi.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(Mt.First,l),s.addSystemToSchedule(Mt.Last,c),s.addPlugin(bn),s.addPlugin(Fn),s.addPlugin(Ut),s.addPlugin(eo),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Rc,...t})}e=w;export{it as Added,Gl as AnimationPlugin,to as App,vn as AssetPlugin,Sn as AssetRefCounter,wn as AssetServer,xn as Assets,ss as AsyncCache,Jl as AttenuationModel,fs as Audio,p as AudioBus,sc as AudioListener,m as AudioMixer,nc as AudioPlugin,g as AudioPool,tc as AudioSource,we as BitmapText,$t as BlendMode,Fe as BodyType,Ae as BoxCollider,fr as Button,dr as ButtonState,pe as Camera,me as Canvas,ke as CapsuleCollider,ot as Changed,ye as Children,Ie as CircleCollider,le as ClearFlags,pt as Commands,gt as CommandsInstance,v as DEFAULT_DESIGN_HEIGHT,x as DEFAULT_DESIGN_WIDTH,R as DEFAULT_FALLBACK_DT,I as DEFAULT_FIXED_TIMESTEP,P as DEFAULT_FONT_FAMILY,T as DEFAULT_FONT_SIZE,A as DEFAULT_GRAVITY,E as DEFAULT_LINE_HEIGHT,C as DEFAULT_MAX_DELTA_TIME,b as DEFAULT_PIXELS_PER_UNIT,k as DEFAULT_SPINE_SKIN,M as DEFAULT_SPRITE_SIZE,S as DEFAULT_TEXT_CANVAS_SIZE,Jn as DataType,Zr as DragPlugin,Qr as DragState,Jr as Draggable,Vn as Draw,Sa as Dropdown,Ma as DropdownPlugin,Tl as EasingType,ve as EmitterShape,mt as EntityCommands,vt as EventReader,St as EventReaderInstance,wt as EventRegistry,xt as EventWriter,bt as EventWriterInstance,_o as FillDirection,Ur as FillMethod,Lr as FillOrigin,kr as FocusManager,Ir as FocusManagerState,da as FocusPlugin,Ar as Focusable,xc as FrameHistory,Ni as GLDebug,oi as Geometry,Pt as GetWorld,L as INVALID_ENTITY,D as INVALID_FONT,O as INVALID_MATERIAL,$ as INVALID_TEXTURE,$r as Image,Or as ImagePlugin,zr as ImageType,Bt as Input,zt as InputPlugin,Ft as InputState,ur as Interactable,Aa as LayoutGroupPlugin,ya as ListView,va as ListViewPlugin,he as LocalTransform,gl as LogLevel,yl as Logger,Cl as LoopMode,Yt as Material,ns as MaterialLoader,st as Mut,Pe as Name,_e as Parent,cc as Particle,Se as ParticleEasing,Me as ParticleEmitter,uc as ParticlePlugin,nl as Physics,Ja as PhysicsEvents,tl as PhysicsPlugin,_i as PostProcess,Bi as PostProcessPlugin,hi as PostProcessStack,Ee as PostProcessVolume,An as PrefabServer,In as Prefabs,kn as PrefabsPlugin,pl as PreviewPlugin,Yr as ProgressBar,Xr as ProgressBarDirection,Gr as ProgressBarPlugin,ae as ProjectionType,ut as Query,ht as QueryInstance,dt as Removed,ft as RemovedQueryInstance,Xi as RenderPipeline,Ui as RenderStage,ml as RenderTexture,Wi as Renderer,Ue as Res,Le as ResMut,Re as RigidBody,F as RuntimeConfig,pa as SafeArea,ga as SafeAreaPlugin,ce as ScaleMode,Ji as SceneManager,Ki as SceneManagerState,Te as SceneOwner,Mt as Schedule,ta as ScrollView,ia as ScrollViewPlugin,ts as ShaderSources,be as SimulationSpace,aa as Slider,ra as SliderDirection,ua as SliderPlugin,xe as SpineAnimation,fe as Sprite,hs as SpriteAnimator,wc as Stats,bc as StatsCollector,_c as StatsOverlay,Sc as StatsPlugin,He as Storage,kt as SystemRunner,No as Text,Ho as TextAlign,Rr as TextInput,Fr as TextInputPlugin,jo as TextOverflow,qo as TextPlugin,Xo as TextRenderer,Vo as TextVerticalAlign,Ts as Tilemap,Ps as TilemapAPI,Es as TilemapLayer,fc as TilemapPlugin,Oe as Time,Hr as Toggle,jr as TogglePlugin,ue as Transform,ql as Tween,Wl as TweenHandle,El as TweenState,Ol as TweenTarget,Lt as UICameraInfo,pr as UIEventQueue,mr as UIEvents,hr as UIInteraction,Er as UIInteractionPlugin,gr as UILayoutPlugin,Qo as UIMask,lr as UIMaskPlugin,wo as UIRect,ka as UIRenderOrderPlugin,ge as Velocity,dl as WebAssetProvider,tt as World,de as WorldTransform,At as addStartupSystem,Rt as addSystem,It as addSystemToSchedule,Kl as animationPlugin,U as applyBuildRuntimeConfig,To as applyDirectionalFill,B as applyRuntimeConfig,bn as assetPlugin,ic as audioPlugin,Zl as calculateAttenuation,ec as calculatePanning,Ei as cleanupAllPostProcessVolumes,Ti as cleanupPostProcessVolume,us as clearAnimClips,Kn as clearDrawCallbacks,ys as clearTextureDimensionsCache,vs as clearTilemapSourceCache,Z as clearUserComponents,j as color,So as computeFillAnchors,Po as computeFillSize,Mo as computeHandleAnchors,yo as computeUIRectLayout,ar as createMaskProcessor,ul as createRuntimeSceneConfig,Ac as createWebApp,bl as debug,yc as defaultFrameStats,K as defineComponent,_t as defineEvent,ze as defineResource,Et as defineSystem,J as defineTag,ea as dragPlugin,Pa as dropdownPlugin,Pl as error,is as extractAnimClipTexturePaths,Qs as findEntityByName,so as flushPendingSystems,fa as focusPlugin,an as getAddressableType,ln as getAddressableTypeByEditorType,un as getAllAssetExtensions,bi as getAllEffectDefs,cs as getAnimClip,yn as getAssetBuildTransform,pn as getAssetMimeType,on as getAssetTypeEntry,oe as getComponent,Os as getComponentAssetFieldDescriptors,Ds as getComponentAssetFields,Ce as getComponentDefaults,js as getComponentEntityFields,Ws as getComponentSpineFieldDescriptor,dn as getCustomExtensions,rn as getEditorType,xi as getEffectDef,vi as getEffectTypes,xl as getLogger,t as getPlatform,n as getPlatformType,_s as getTextureDimensions,xs as getTilemapSource,Q as getUserComponent,fn as getWeChatPackOptions,Wr as imagePlugin,Sl as info,Dn as initDrawAPI,Vi as initGLDebugAPI,si as initGeometryAPI,jt as initMaterialAPI,ac as initParticleAPI,Ec as initPlayableRuntime,pi as initPostProcessAPI,Di as initRendererAPI,hl as initRuntime,Ss as initTilemapAPI,jl as initTweenAPI,Ut as inputPlugin,Pn as instantiatePrefab,Zo as intersectRects,er as invertMatrix4,se as isBuiltinComponent,mn as isCustomExtension,vr as isEditor,cn as isKnownAssetExtension,s as isPlatformInitialized,Mr as isPlayMode,br as isRuntime,Dt as isTextureRef,i as isWeChat,o as isWeb,Ia as layoutGroupPlugin,ba as listViewPlugin,Ks as loadComponent,za as loadPhysicsModule,cl as loadRuntimeScene,Ys as loadSceneData,qs as loadSceneWithAssets,Us as loadTiledMap,hn as looksLikeAssetPath,os as parseAnimClipData,Fs as parseTiledMap,Is as parseTmjJson,hc as particlePlugin,r as platformFetch,c as platformFileExists,u as platformInstantiateWasm,a as platformReadFile,l as platformReadTextFile,or as pointInOBB,sr as pointInWorldRect,zi as postProcessPlugin,Fn as prefabsPlugin,Kr as progressBarPlugin,N as quat,as as registerAnimClip,_n as registerAssetBuildTransform,ie as registerComponent,$s as registerComponentAssetFields,Vs as registerComponentEntityFields,qn as registerDrawCallback,Mn as registerEmbeddedAssets,es as registerMaterialCallback,gs as registerTextureDimensions,ws as registerTilemapSource,Ns as remapEntityFields,ks as resolveRelativePath,_a as safeAreaPlugin,eo as sceneManagerPlugin,tr as screenToWorld,oa as scrollViewPlugin,xr as setEditorMode,xa as setListViewRenderer,vl as setLogLevel,Sr as setPlayMode,Ye as setWasmErrorHandler,On as shutdownDrawAPI,ji as shutdownGLDebugAPI,ni as shutdownGeometryAPI,Nt as shutdownMaterialAPI,lc as shutdownParticleAPI,mi as shutdownPostProcessAPI,Oi as shutdownRendererAPI,Ms as shutdownTilemapAPI,Nl as shutdownTweenAPI,ha as sliderPlugin,ds as spriteAnimatorSystemUpdate,Mc as statsPlugin,Bo as syncFillSpriteSize,Pi as syncPostProcessVolume,Br as textInputPlugin,Go as textPlugin,pc as tilemapPlugin,gn as toBuildPath,Nr as togglePlugin,Ba as transitionTo,Cr as uiInteractionPlugin,_r as uiLayoutPlugin,cr as uiMaskPlugin,Cc as uiPlugins,Fa as uiRenderOrderPlugin,ls as unregisterAnimClip,ee as unregisterComponent,Gn as unregisterDrawCallback,Js as updateCameraAspectRatio,W as vec2,H as vec3,V as vec4,Ml as warn,Qi as wrapSceneSystem};
+import{g as t,A as s,a as n,b as i,p as o,c as r,d as a,e as c,i as u,u as p,w as m,f as y,h as x,j as w,k as v,m as b,n as E,r as T,o as A,q as z,s as k,t as F,v as D,x as H,y as q,T as G,z as ee,B as te,C as se,D as ne,E as ie,F as oe,G as re,H as le}from"./shared/SpineModuleLoader.js";export{I as AssetPlugin,J as AssetServer,K as AsyncCache,M as MaterialLoader,S as SpriteAnimator,L as clearAnimClips,N as clearTilemapSourceCache,O as findEntityByName,P as getAddressableType,Q as getAddressableTypeByEditorType,R as getAllAssetExtensions,U as getAnimClip,V as getAssetBuildTransform,W as getAssetMimeType,X as getComponentAssetFields,Y as getCustomExtensions,Z as getEditorType,_ as getPlatformType,$ as getWeChatPackOptions,a0 as isCustomExtension,a1 as isKnownAssetExtension,a2 as isPlatformInitialized,a3 as isWeb,a4 as loadComponent,a5 as loadTiledMap,a6 as looksLikeAssetPath,a7 as parseTiledMap,a8 as platformFileExists,a9 as platformInstantiateWasm,aa as platformReadFile,ab as platformReadTextFile,ac as registerAssetBuildTransform,ad as registerComponentAssetFields,ae as registerComponentEntityFields,af as remapEntityFields,ag as toBuildPath,ah as unregisterAnimClip}from"./shared/SpineModuleLoader.js";import{d as ce,S as ue,i as de,M as he,j as fe,Q as pe,T as me,P as ge,R as ye,k as _e,c as xe,a as we,l as ve,m as Se,n as be,o as Me,E as Pe,W as Ee,p as Te,q as Ce,s as Re,r as Ae,t as Ie,u as ze,v as ke,w as Fe,x as Be,y as Le,b as Ue,z as We,A as Oe,N as De,D as He,F as Ye,G as $e,H as Xe,h as Ne,J as Ve,K as je,L as qe,O as Ge,U as Ke,V as Je,X as Qe}from"./shared/material.js";export{Y as Added,Z as BlendMode,B as BodyType,f as BoxCollider,_ as CapsuleCollider,$ as Changed,C as CircleCollider,a0 as Commands,a1 as CommandsInstance,a2 as DEFAULT_FONT_FAMILY,a3 as DEFAULT_FONT_SIZE,a4 as DEFAULT_LINE_HEIGHT,a5 as DEFAULT_SPINE_SKIN,a6 as DEFAULT_SPRITE_SIZE,a7 as DEFAULT_TEXT_CANVAS_SIZE,a8 as EmitterShape,a9 as EntityCommands,aa as EventReader,ab as EventReaderInstance,ac as EventWriter,ad as EventWriterInstance,I as INVALID_ENTITY,ae as INVALID_FONT,af as INVALID_MATERIAL,ag as LocalTransform,ah as Mut,ai as ParticleEasing,aj as ParticleEmitter,ak as QueryInstance,al as Removed,am as RemovedQueryInstance,e as RigidBody,an as ShaderSources,ao as SimulationSpace,ap as Velocity,aq as addStartupSystem,ar as addSystem,as as addSystemToSchedule,at as applyBuildRuntimeConfig,au as applyRuntimeConfig,av as clearUserComponents,aw as color,ax as defineEvent,ay as defineTag,g as getComponent,az as getComponentDefaults,aA as getUserComponent,aB as isBuiltinComponent,aC as isTextureRef,aD as quat,aE as registerMaterialCallback,aF as unregisterComponent,aG as vec2,aH as vec3,aI as vec4}from"./shared/material.js";import{D as Ze,u as et,g as tt,r as st,c as nt,s as it,i as ot,a as rt,b as lt,P as ct}from"./shared/index.js";export{d as Physics,e as PhysicsEvents,f as isRuntime,l as loadPhysicsModule,h as setEditorMode,j as setPlayMode}from"./shared/index.js";class ut{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 ut?this.gainNode_.connect(e.node):this.gainNode_.connect(e)}addChild(e){e.connect(this),this.children_.push(e)}}class dt{constructor(e,t={}){this.buses_=new Map,this.context_=e,this.master=new ut(e,{name:"master",volume:t.masterVolume??1}),this.master.connect(e.destination),this.music=new ut(e,{name:"music",volume:t.musicVolume??.8}),this.master.addChild(this.music),this.sfx=new ut(e,{name:"sfx",volume:t.sfxVolume??1}),this.master.addChild(this.sfx),this.ui=new ut(e,{name:"ui",volume:t.uiVolume??1}),this.master.addChild(this.ui),this.voice=new ut(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 ut(this.context_,e),s=e.parent?this.buses_.get(e.parent):this.master;return s&&s.addChild(t),this.buses_.set(e.name,t),t}}class ht{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 ft{constructor(e,t,s,n,i,o,r){this.playing_=!0,this.stopped_=!1,this.pausedAt_=0,this.id=e,this.source_=t,this.buffer_=s,this.poolNode_=n,this.pool_=i,this.context_=o,this.startOffset_=r,this.startedAt_=o.currentTime,this.playbackRate_=t.playbackRate.value,this.loop_=t.loop,this.bindOnEnded_(t)}bindOnEnded_(e){e.onended=()=>{this.stopped_||this.loop_||(this.playing_=!1,this.stopped_=!0,this.pool_.release(this.poolNode_),this.onEnd?.())}}stop(){this.stopped_||(this.stopped_=!0,this.playing_=!1,this.source_.onended=null,this.pool_.release(this.poolNode_))}pause(){if(!this.playing_||this.stopped_)return;this.playing_=!1;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;this.pausedAt_=this.startOffset_+e,this.loop_&&this.buffer_.duration>0&&(this.pausedAt_=this.pausedAt_%this.buffer_.duration),this.source_.onended=null;try{this.source_.stop()}catch(e){}this.source_.disconnect()}resume(){if(this.playing_||this.stopped_)return;this.playing_=!0;const e=this.context_.createBufferSource();e.buffer=this.buffer_,e.loop=this.loop_,e.playbackRate.value=this.playbackRate_,e.connect(this.poolNode_.gain),this.source_=e,this.poolNode_.source=e,this.startOffset_=this.pausedAt_,this.startedAt_=this.context_.currentTime,this.bindOnEnded_(e),e.start(0,this.pausedAt_)}setVolume(e){this.poolNode_.gain.gain.value=e}setPan(e){this.poolNode_.panner.pan.value=e}setLoop(e){this.loop_=e,this.source_.loop=e}setPlaybackRate(e){this.playbackRate_=e,this.playing_&&(this.source_.playbackRate.value=e)}get isPlaying(){return this.playing_}get currentTime(){if(this.stopped_)return 0;if(!this.playing_)return this.pausedAt_;const e=(this.context_.currentTime-this.startedAt_)*this.playbackRate_;return this.startOffset_+e}get duration(){return this.buffer_.duration}}class pt{constructor(){this.name="WebAudio",this.context_=null,this.mixer_=null,this.pool_=null,this.buffers_=new Map,this.urlToId_=new Map,this.loadingUrls_=new Map,this.nextBufferId_=0,this.nextHandleId_=0,this.resumeHandler_=null}get mixer(){return this.mixer_}get isReady(){return"running"===this.context_?.state}async initialize(e={}){if(this.context_=new AudioContext,this.mixer_=new dt(this.context_,e.mixerConfig),this.pool_=new ht(this.context_,e.initialPoolSize),"suspended"===this.context_.state){const e=()=>{this.context_.resume(),document.removeEventListener("touchstart",e),document.removeEventListener("mousedown",e),document.removeEventListener("keydown",e),this.resumeHandler_=null};document.addEventListener("touchstart",e),document.addEventListener("mousedown",e),document.addEventListener("keydown",e),this.resumeHandler_=e}}async ensureResumed(){this.context_&&"suspended"===this.context_.state&&await this.context_.resume()}async loadBuffer(e){if(!this.context_)throw new Error("AudioContext not initialized");const t=this.urlToId_.get(e);if(void 0!==t&&this.buffers_.has(t)){return{id:t,duration:this.buffers_.get(t).duration}}const s=this.loadingUrls_.get(e);if(s)return s;const n=this.doLoadBuffer_(e);this.loadingUrls_.set(e,n);try{return await n}finally{this.loadingUrls_.delete(e)}}async loadBufferFromData(e,t){if(!this.context_)throw new Error("AudioContext not initialized");const s=this.urlToId_.get(e);if(void 0!==s&&this.buffers_.has(s)){return{id:s,duration:this.buffers_.get(s).duration}}let n;try{n=await this.context_.decodeAudioData(t)}catch(t){throw new Error(`Failed to decode audio ${e}: ${t.message}`)}const i=++this.nextBufferId_;return this.buffers_.set(i,n),this.urlToId_.set(e,i),{id:i,duration:n.duration}}async doLoadBuffer_(e){const s=await t().readFile(e);return this.loadBufferFromData(e,s)}unloadBuffer(e){this.buffers_.delete(e.id)}play(e,t){if(!this.context_||!this.pool_||!this.mixer_)throw new Error("Audio system not initialized");const s=this.buffers_.get(e.id);if(!s)throw new Error(`Buffer ${e.id} not found`);const n=this.pool_.acquire(),i=this.context_.createBufferSource();i.buffer=s,i.loop=t.loop??!1,i.playbackRate.value=t.playbackRate??1,i.connect(n.gain),n.source=i,n.gain.gain.value=t.volume??1,n.panner.pan.value=t.pan??0;const o=t.bus??"sfx",r=this.mixer_.getBus(o)??this.mixer_.sfx;n.panner.connect(r.node);const a=t.startOffset??0;i.start(0,a);const l=++this.nextHandleId_;return new ft(l,i,s,n,this.pool_,this.context_,a)}suspend(){this.context_?.suspend()}resume(){this.context_?.resume()}dispose(){this.resumeHandler_&&(document.removeEventListener("touchstart",this.resumeHandler_),document.removeEventListener("mousedown",this.resumeHandler_),document.removeEventListener("keydown",this.resumeHandler_),this.resumeHandler_=null),this.pool_=null,this.mixer_=null,this.buffers_.clear(),this.urlToId_.clear(),this.loadingUrls_.clear(),this.context_?.close(),this.context_=null}}const mt=new class{constructor(){this.name="web",this.inputCleanup_=null}async fetch(e,t){const s=await globalThis.fetch(e,{method:t?.method??"GET",headers:t?.headers,body:t?.body}),n={};return s.headers.forEach((e,t)=>{n[t]=e}),{ok:s.ok,status:s.status,statusText:s.statusText,headers:n,json:()=>s.json(),text:()=>s.text(),arrayBuffer:()=>s.arrayBuffer()}}async readFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.arrayBuffer()}async readTextFile(e){const t=await this.fetch(e);if(!t.ok)throw new Error(`Failed to read file: ${e} (${t.status})`);return t.text()}async fileExists(e){try{return(await globalThis.fetch(e,{method:"HEAD"})).ok}catch{return!1}}async loadImagePixels(e){const t=this.createImage();await new Promise((s,n)=>{t.crossOrigin="anonymous",t.onload=()=>s(),t.onerror=()=>n(new Error(`Failed to load image: ${e}`)),t.src=e});const s=this.createCanvas(t.width,t.height).getContext("2d");s.drawImage(t,0,0);const n=s.getImageData(0,0,t.width,t.height);return{width:t.width,height:t.height,pixels:new Uint8Array(n.data.buffer)}}async instantiateWasm(e,t){let s;s="string"==typeof e?await this.readFile(e):e;const n=await WebAssembly.instantiate(s,t);return{instance:n.instance,module:n.module}}createImage(){return new Image}createCanvas(e,t){let s;return s="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(e,t):document.createElement("canvas"),s.width=e,s.height=t,s}now(){return performance.now()}bindInputEvents(e,t){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null);const s=t??document.querySelector("canvas")??document.body,n=t=>e.onKeyDown(t.code),i=t=>e.onKeyUp(t.code),o=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},r=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},u=()=>{e.onPointerUp(0)},d=t=>{const s=t;let n=s.deltaX,i=s.deltaY;1===s.deltaMode?(n*=16,i*=16):2===s.deltaMode&&(n*=window.innerWidth,i*=window.innerHeight),e.onWheel(n,i)};document.addEventListener("keydown",n),document.addEventListener("keyup",i),s.addEventListener("mousemove",o),s.addEventListener("mousedown",r),document.addEventListener("mouseup",a),s.addEventListener("touchstart",l),s.addEventListener("touchmove",c),s.addEventListener("touchend",u),s.addEventListener("wheel",d),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",i),s.removeEventListener("mousemove",o),s.removeEventListener("mousedown",r),document.removeEventListener("mouseup",a),s.removeEventListener("touchstart",l),s.removeEventListener("touchmove",c),s.removeEventListener("touchend",u),s.removeEventListener("wheel",d)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}createAudioBackend(){return new pt}getStorageItem(e){return localStorage.getItem(e)}setStorageItem(e,t){localStorage.setItem(e,t)}removeStorageItem(e){localStorage.removeItem(e)}clearStorage(e){const t=[];for(let s=0;s<localStorage.length;s++){const n=localStorage.key(s);null!==n&&n.startsWith(e)&&t.push(n)}for(const e of t)localStorage.removeItem(e)}},gt="esengine:",yt={getString(e,s){const n=t().getStorageItem(gt+e);return null!==n?n:s},setString(e,s){t().setStorageItem(gt+e,s)},getNumber(e,s){const n=t().getStorageItem(gt+e);if(null===n)return s;const i=Number(n);return Number.isNaN(i)?s:i},setNumber(e,s){t().setStorageItem(gt+e,String(s))},getBoolean(e,s){const n=t().getStorageItem(gt+e);return null===n?s:"true"===n},setBoolean(e,s){t().setStorageItem(gt+e,String(s))},getJSON(e,s){const n=t().getStorageItem(gt+e);if(null===n)return s;try{return JSON.parse(n)}catch{return s}},setJSON(e,s){t().setStorageItem(gt+e,JSON.stringify(s))},remove(e){t().removeStorageItem(gt+e)},has:e=>null!==t().getStorageItem(gt+e),clear(){t().clearStorage(gt)}};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=ce(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(ue.Last,de([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const vt=new wt,St=ce({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");class bt{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}}}function Mt(e,t){const n=e.getResource(s);n&&n.registerEmbeddedAssets(t)}async function Pt(e,t,s){const{entities:i,rootId:o}=await Tt(t,s?.overrides??[],s,void 0,new Set),r={version:t.version,name:t.name,entities:i.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},a=await n(e,r,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),l=a.get(o);return void 0!==s?.parent&&e.setParent(l,s.parent),{root:l,entities:a}}const Et=10;async function Tt(e,t,s,n,i,o=0){if(o>Et)throw new Error(`Prefab nesting depth exceeded ${Et}. 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 Tt(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};Ct(d.components,r),Rt(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 Ct(e,t){for(const s of e){const e=i(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 Rt(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class At{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 Pt(this.world_,i,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const It=ce(null,"Prefabs");class zt{constructor(){this.name="PrefabsPlugin",this.dependencies=[s]}build(e){const t=e.getResource(s);e.insertResource(It,new At(e.world,t))}}const kt=new zt;var Ft;!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"}(Ft||(Ft={}));let Bt=null,Lt=0,Ut=0,Wt=0;function Ot(e){Bt=e,Lt=Bt._malloc(262144),Ut=Bt._malloc(65536),Wt=Bt._malloc(256)}function Dt(){Bt&&(Lt&&Bt._free(Lt),Ut&&Bt._free(Ut),Wt&&Bt._free(Wt),Lt=0,Ut=0,Wt=0),Bt=null}function Ht(){if(!Bt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Bt}const Yt={create(e){const t=Ht(),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,Lt/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,Wt,i).set(o),t.geometry_init(s,Lt,n,Wt,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,Ut,n).set(e.indices),t.geometry_setIndices16(s,Ut,n)}else{new Uint32Array(t.HEAPU8.buffer,Ut,n).set(e.indices),t.geometry_setIndices32(s,Ut,n)}}return s},updateVertices(e,t,s=0){const n=Ht(),i=t.length;if(4*i>262144)throw new Error(`Vertex data too large: ${i} floats (max 65536)`);n.HEAPF32.set(t,Lt/4),n.geometry_updateVertices(e,Lt,i,s)},release(e){e>0&&Ht().geometry_release(e)},isValid:e=>!(!Bt||e<=0)&&Bt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Yt.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:Ft.Float2},{name:"a_texCoord",type:Ft.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 Yt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Ft.Float2},{name:"a_texCoord",type:Ft.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 Yt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:Ft.Float2},{name:"a_texCoord",type:Ft.Float2}],indices:new Uint16Array(r)})}};let $t=1;const Xt=new Map,Nt=new Map;function Vt(){return Xt}function jt(){return Nt}class qt{constructor(){this.passes_=[],this.destroyed_=!1,this.id=$t++,Xt.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 Nt)t===this&&Nt.delete(e);Xt.delete(this.id)}}}const Gt="#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 Kt=null;function Jt(e){Kt=e}function Qt(){for(const e of Vt().values())e.destroy();Vt().clear(),jt().clear(),Kt&&es.isInitialized()&&es.shutdown(),Kt=null}function Zt(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const es={createStack:()=>new qt,bind(e,t){if(t.isDestroyed)throw new Error("Cannot bind a destroyed PostProcessStack");jt().set(e,t)},unbind(e){jt().delete(e)},getStack:e=>jt().get(e)??null,init(e,t){try{return Zt().postprocess_init(e,t)}catch(s){return fe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Zt().postprocess_shutdown()}catch(e){fe(e,"PostProcess.shutdown")}},resize(e,t){try{Zt().postprocess_resize(e,t)}catch(s){fe(s,`PostProcess.resize(${e}x${t})`)}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return fe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Zt().postprocess_setBypass(e)}catch(e){fe(e,"PostProcess.setBypass")}},setOutputViewport(e,t,s,n){try{Zt().postprocess_setOutputViewport(e,t,s,n)}catch(e){fe(e,"PostProcess.setOutputViewport")}},_applyForCamera(e){const t=jt().get(e);t&&!t.isDestroyed&&0!==t.enabledPassCount?(es.isInitialized()||es.init(1,1),es.setBypass(!1),function(e){const t=Zt();try{t.postprocess_clearPasses()}catch(e){return void fe(e,"PostProcess._applyForCamera:clearPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addPass(s.name,s.shader)}catch(e){fe(e,`PostProcess._applyForCamera:addPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setUniformFloat(s.name,e,n)}catch(t){fe(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){fe(t,`PostProcess._applyForCamera:setUniformVec4("${s.name}", "${e}")`)}}}(t)):es.setBypass(!0)},_resetAfterCamera(){try{Zt().postprocess_clearPasses(),Zt().postprocess_setBypass(!0)}catch(e){fe(e,"PostProcess._resetAfterCamera")}},_cleanupDestroyedCameras(e){for(const t of jt().keys())e(t)||jt().delete(t)},screenStack:null,setScreenStack(e){es.screenStack=e},_beginScreenCapture(){try{Zt().postprocess_beginScreenCapture()}catch(e){fe(e,"PostProcess._beginScreenCapture")}},_endScreenCapture(){try{Zt().postprocess_endScreenCapture()}catch(e){fe(e,"PostProcess._endScreenCapture")}},_applyScreenStack(){const e=es.screenStack;if(!e||e.isDestroyed||0===e.enabledPassCount)return;const t=Zt();try{t.postprocess_clearScreenPasses()}catch(e){return void fe(e,"PostProcess._applyScreenStack:clearScreenPasses")}for(const s of e.passes)if(s.enabled){try{t.postprocess_addScreenPass(s.name,s.shader)}catch(e){fe(e,`PostProcess._applyScreenStack:addScreenPass("${s.name}")`);continue}for(const[e,n]of s.floatUniforms)try{t.postprocess_setScreenUniformFloat(s.name,e,n)}catch(t){fe(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){fe(t,`PostProcess._applyScreenStack:setScreenUniformVec4("${s.name}", "${e}")`)}}},_executeScreenPasses(){try{Zt().postprocess_executeScreenPasses()}catch(e){fe(e,"PostProcess._executeScreenPasses")}},createBlur:()=>he.createShader(Gt,"#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:()=>he.createShader(Gt,"#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:()=>he.createShader(Gt,"#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:()=>he.createShader(Gt,"#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:()=>he.createShader(Gt,"#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")},ts=new Map;function ss(e){ts.set(e.type,e)}function ns(e){return ts.get(e)}function is(){return Array.from(ts.keys())}function os(){return Array.from(ts.values())}ss({type:"blur",label:"Blur",factory:()=>es.createBlur(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:2}]}),ss({type:"bloom",label:"Bloom",factory:()=>es.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}]}),ss({type:"vignette",label:"Vignette",factory:()=>es.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}]}),ss({type:"grayscale",label:"Grayscale",factory:()=>es.createGrayscale(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:1,step:.01,defaultValue:1}]}),ss({type:"chromaticAberration",label:"Chromatic Aberration",factory:()=>es.createChromaticAberration(),uniforms:[{name:"u_intensity",label:"Intensity",min:0,max:20,step:.1,defaultValue:3}]});const rs=new Map,ls=new Map;function cs(e,t){let s=rs.get(e),n=ls.get(e);const i=t.effects.filter(e=>e.enabled);if(0!==i.length){for(s||(s=es.createStack(),rs.set(e,s)),n||(n=new Map,ls.set(e,n));s.passCount>0;){const e=s.passes;s.removePass(e[e.length-1].name)}for(const e of i){const t=ns(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)}}es.bind(e,s)}else if(s&&(es.unbind(e),s.destroy(),rs.delete(e)),n){for(const e of n.values())he.releaseShader(e);ls.delete(e)}}function us(e){const t=rs.get(e);t&&(es.unbind(e),t.destroy(),rs.delete(e));const s=ls.get(e);if(s){for(const e of s.values())he.releaseShader(e);ls.delete(e)}}function ds(){for(const e of rs.keys())us(e)}const hs=ce({enabled:!0},"PostProcessVolumeConfig"),fs=new Map,ps=new Map;function ms(e){const t=ps.get(e);if(void 0!==t)return t;const s=ns(e);if(!s)return null;const n=s.factory();return ps.set(e,n),n}function gs(e,t){if(0===t.size){const t=fs.get(e);return void(t&&(es.unbind(e),t.destroy(),fs.delete(e)))}let s=fs.get(e);for(s||(s=es.createStack(),fs.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=ms(e);if(null!==t){s.addPass(e,t);for(const[t,i]of n.uniforms)s.setUniform(e,t,i)}}s.enabledPassCount>0?es.bind(e,s):es.unbind(e)}const ys=de([pe(ge,me)],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 fs)gs(t,e)}},{name:"PostProcessVolumeSystem"});class _s{constructor(){this.name="PostProcessPlugin"}build(e){e.insertResource(hs,{enabled:!0}),e.addSystemToSchedule(ue.PostUpdate,ys)}cleanup(){ds(),function(){for(const[e,t]of fs)es.unbind(e),t.destroy();fs.clear();for(const e of ps.values())he.releaseShader(e);ps.clear()}(),es.setScreenStack(null)}}const xs=new _s;var ws;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(ws||(ws={}));let vs=null,Ss=0;function bs(e){vs=e,Ss=vs._malloc(64)}function Ms(){vs&&Ss&&(vs._free(Ss),Ss=0),vs=null}const Ps={init(e,t){vs?.renderer_init(e,t)},resize(e,t){vs?.renderer_resize(e,t)},begin(e,t){if(vs&&Ss)try{vs.HEAPF32.set(e,Ss/4),vs.renderer_begin(Ss,t??0)}catch(e){fe(e,"Renderer.begin")}},flush(){try{vs?.renderer_flush()}catch(e){fe(e,"Renderer.flush")}},end(){try{vs?.renderer_end()}catch(e){fe(e,"Renderer.end")}},submitSprites(e){if(vs)try{vs.renderer_submitSprites(e._cpp)}catch(e){fe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(vs)try{vs.renderer_submitBitmapText(e._cpp)}catch(e){fe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(vs)try{vs.renderer_submitSpine?.(e._cpp)}catch(e){fe(e,"Renderer.submitSpine")}},submitParticles(e){if(vs)try{vs.renderer_submitParticles?.(e._cpp)}catch(e){fe(e,"Renderer.submitParticles")}},setStage(e){vs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>vs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){vs?.renderer_releaseTarget(e)},getTargetTexture:e=>vs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>vs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){vs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){vs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,i){vs?.renderer_setScissor(e,t,s,n,i)},clearBuffers(e){vs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>vs?vs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>vs?{drawCalls:vs.renderer_getDrawCalls(),triangles:vs.renderer_getTriangles(),sprites:vs.renderer_getSprites(),text:vs.renderer_getText(),spine:vs.renderer_getSpine?.()??0,meshes:vs.renderer_getMeshes(),culled:vs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let Es=null;function Ts(e){Es=e}function Cs(){Es=null}const Rs={enable(){Es?.gl_enableErrorCheck(!0)},disable(){Es?.gl_enableErrorCheck(!1)},check:e=>Es?.gl_checkErrors(e)??0,diagnose(){Es?.renderer_diagnose()}};class As{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(){es.screenStack&&es.screenStack.enabledPassCount>0&&(es.isInitialized()||es.init(1,1),es._applyScreenStack(),es._beginScreenCapture())}endScreenCapture(){es.screenStack&&es.screenStack.enabledPassCount>0&&(es._endScreenCapture(),es._executeScreenPasses())}render(e){const{registry:t,viewProjection:s,width:n,height:i,elapsed:o}=e;n===this.lastWidth_&&i===this.lastHeight_||(Ps.resize(n,i),this.lastWidth_=n,this.lastHeight_=i),Ps.setViewport(0,0,n,i),Ps.clearBuffers(3),Ps.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,i),this.tilemapRenderer_&&this.tilemapRenderer_(),Ps.submitSprites(t),Ps.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ps.submitSpine(t),Ps.submitParticles(t),Ps.flush(),this.executeDrawCallbacks(s,o),Ps.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:i,elapsed:o,cameraEntity:r}=e,a=void 0!==r&&null!==es.getStack(r);a&&(es._applyForCamera(r),es.resize(n.w,n.h),es.setOutputViewport(n.x,n.y,n.w,n.h)),Ps.setViewport(n.x,n.y,n.w,n.h),Ps.setScissor(n.x,n.y,n.w,n.h,!0),Ps.clearBuffers(i),Ps.setScissor(0,0,0,0,!1),Ps.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),this.tilemapRenderer_&&this.tilemapRenderer_(),Ps.submitSprites(t),Ps.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):Ps.submitSpine(t),Ps.submitParticles(t),Ps.flush(),this.executeDrawCallbacks(s,o),Ps.end(),a&&es._resetAfterCamera()}executeDrawCallbacks(e,t){const s=tt();if(s.size>0){Ze.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)}Ze.end();for(const e of n)et(e)}}}const Is="__scene_transition_overlay__";class zs{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 ks{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,_e,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),st(e,t,this.instance_.config.name)}bindPostProcess(e,t){es.bind(e,t),this.instance_.postProcessBindings.set(e,t)}unbindPostProcess(e){es.unbind(e),this.instance_.postProcessBindings.delete(e)}setPersistent(e,t){if(this.app_.world.has(e,_e)){const s=this.app_.world.get(e,_e);s.persistent=t,this.app_.world.insert(e,_e,s)}}}class Fs{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())et(t);for(const t of e.postProcessBindings.keys())es.unbind(t)}this.transition_&&(et(Is),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??ye.sceneTransitionDuration,i=t.color??{...ye.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:i,targetScene:e,options:t,resolve:s},st(Is,()=>{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;Ze.setLayer(9999),Ze.setDepth(9999),Ze.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,et(Is),t()}})()}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,et(Is),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 zs(t);this.scenes_.set(e,n);const i=new ks(n,this.app_);this.contexts_.set(e,i);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(s)?this.app_.getResource(s):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}return await this.loadSceneData_(n,e,t,o),n.status="running",this.activeScene_=e,this.loadOrder_.push(e),i})();this.loadPromises_.set(e,o);try{return await o}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 zs(t);this.scenes_.set(e,n);const i=new ks(n,this.app_);this.contexts_.set(e,i);const o=(async()=>{let o=t.data;if(!o&&t.path){const e=this.app_.hasResource(s)?this.app_.getResource(s):null;if(e)o=await e.loadJson(t.path);else{const e=await fetch(t.path);o=await e.json()}}return await this.loadSceneData_(n,e,t,o),n.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),i})();this.loadPromises_.set(e,o);try{return await o}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const i=t?.keepPersistent??!0;for(const e of s.entities){if(i&&this.app_.world.valid(e)&&this.app_.world.has(e,_e)){if(this.app_.world.get(e,_e).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())et(e);s.drawCallbacks.clear();for(const e of s.postProcessBindings.keys())es.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,i,o){if(o){const i={textureUrls:new Set,materialHandles:new Set,fontPaths:new Set,spineKeys:new Set},r={collectAssets:i};this.app_.hasResource(s)&&(r.assetServer=this.app_.getResource(s));const a=await n(this.app_.world,o,r);e.loadedAssets=i;for(const s of a.values())e.entities.add(s),this.app_.world.insert(s,_e,{scene:t,persistent:!1})}if(i.systems)for(const{schedule:e,system:s}of i.systems){const n=Ls(this.app_,t,s);this.app_.addSystemToSchedule(e,n)}const r=this.contexts_.get(t);i.setup&&await i.setup(r)}releaseSceneAssets_(e){const t=e.loadedAssets;if(!t)return;const n=this.app_.hasResource(s)?this.app_.getResource(s):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)he.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,xe)){const t=s.get(e,xe);n.sprite=t.color.a,t.color.a=0,s.insert(e,xe,t),i=!0}if(s.has(e,we)){const t=s.get(e,we);n.spine=t.color.a,t.color.a=0,s.insert(e,we,t),i=!0}if(s.has(e,ve)){const t=s.get(e,ve);n.bitmapText=t.color.a,t.color.a=0,s.insert(e,ve,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,xe)){const t=s.get(e,xe);t.color.a=n.sprite,s.insert(e,xe,t)}if(void 0!==n.spine&&s.has(e,we)){const t=s.get(e,we);t.color.a=n.spine,s.insert(e,we,t)}if(void 0!==n.bitmapText&&s.has(e,ve)){const t=s.get(e,ve);t.color.a=n.bitmapText,s.insert(e,ve,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 Bs=ce(null,"SceneManager");function Ls(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Bs).getSceneStatus(t)&&s._fn(...n)}}}const Us=de([Se(Bs),be(Me)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Ws={name:"SceneManager",build(e){const t=new Fs(e);e.insertResource(Bs,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Bs),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(ue.Startup,s),e.addSystemToSchedule(ue.Last,Us)}};class Os{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 Pe,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=o(),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(ue.Last);else{this.runSchedule(ue.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ue.FixedPreUpdate),this.runSchedule(ue.FixedUpdate),this.runSchedule(ue.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ue.PreUpdate),this.runSchedule(ue.Update),this.runSchedule(ue.PostUpdate),this.runSchedule(ue.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2),requestAnimationFrame(this.mainLoop)},this.world_=new Ee,this.resources_=new Te;for(const e of Object.values(ue))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Os}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(ue.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(ue.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 ke(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(Bs).register(e),this}setInitialScene(e){return this.getResource(Bs).setInitial(e),this}tick(e){if(this.runner_||(this.runner_=new Ce(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.has(Me)||this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ue.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(ue.Last);else{this.runSchedule(ue.First),this.fixedAccumulator_+=e;let t=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&t<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(ue.FixedPreUpdate),this.runSchedule(ue.FixedUpdate),this.runSchedule(ue.FixedPostUpdate),t++;t>=this.maxFixedSteps_&&(this.fixedAccumulator_=this.fixedTimestep_),this.runSchedule(ue.PreUpdate),this.runSchedule(ue.Update),this.runSchedule(ue.PostUpdate),this.runSchedule(ue.Last),this.step_pending_&&(this.step_pending_=!1)}this.world_.cleanRemovedBuffer(this.world_.getWorldTick()-2)}run(){this.running_||(this.running_=!0,this.runner_=new Ce(this.world_,this.resources_,this.eventRegistry_),this.statsEnabled_&&this.runner_.setTimingEnabled(!0),this.resources_.insert(Me,{delta:0,elapsed:0,frameCount:0}),this.finishPlugins_(),this.runSchedule(ue.Startup),this.lastTime_=o(),this.mainLoop())}quit(){this.running_=!1,nt();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=[Cs,Ms,Qt,Dt,Re,it];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(ue[e],performance.now()-n)}updateTime(e){const t=this.resources_.get(Me);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ds(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 Hs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ys(e,t,s,n,i){const o=e*t/s,r=e;switch(n){case ze.FixedWidth:return o;case ze.FixedHeight:return r;case ze.Expand:return Math.max(o,r);case ze.Shrink:return Math.min(o,r);case ze.Match:{const e=i;return Math.pow(o,1-e)*Math.pow(r,e)}default:return r}}const $s=[];function Xs(e){if(e<$s.length)return $s[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 $s.push(t),t}function Ns(e,t,s,n,i,o){if(0===s||0===n)return[];const r=e.registry_getCameraEntities(t);if(0===r.length)return[];const a=o&&i?r.filter(e=>{const t=i.tryGet(e,_e);return!t||""===t.scene||o.has(t.scene)}):r;if(0===a.length)return[];const l=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),c=[];for(const e of a){const i=t.getCamera(e),o=t.getTransform(e),r=i.viewportW*s/(i.viewportH*n);let a,u=0,d=0;if(i.projectionType===Ie.Orthographic){if(d=i.orthoSize,l){d=Ys(l.designResolution.y/2,l.designResolution.x/l.designResolution.y,r,l.scaleMode,l.matchWidthOrHeight)}u=d*r,a=js(-u,u,-d,d,-i.farPlane,i.farPlane)}else a=Gs(i.fov*Math.PI/180,r,i.nearPlane,i.farPlane);const h=Js(o.position.x,o.position.y,o.position.z),f=Xs(c.length);f.entity=e,f.viewProjection.set(Zs(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 Vs=new Float32Array(16);function js(e,t,s,n,i,o){const r=Vs;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 qs=new Float32Array(16);function Gs(e,t,s,n){const i=qs;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 Ks=new Float32Array(16);function Js(e,t,s){const n=Ks;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 Qs=new Float32Array(16);function Zs(e,t){const s=Qs;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 en={LeftToRight:0,RightToLeft:1,BottomToTop:2,TopToBottom:3};function tn(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 f,p,m,g;e.x===t.x?(f=c+s.x-i.x*r.x,m=f+i.x):(f=c+s.x,m=u+n.x),e.y===t.y?(p=d+s.y-i.y*r.y,g=p+i.y):(p=d+s.y,g=h+n.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 sn=Fe("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 nn=null,on=null;function rn(e,t){e.has(t,xe)||e.insert(t,xe,{texture:Le,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 ln(e,t){switch(e){case en.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case en.BottomToTop:return{anchorMin:{x:0,y:0},anchorMax:{x:1,y:t},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};case en.TopToBottom:return{anchorMin:{x:0,y:1-t},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}};default:return{anchorMin:{x:0,y:0},anchorMax:{x:t,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0}}}}function cn(e,t){switch(e){case en.RightToLeft:return{anchorMin:{x:1-t,y:0},anchorMax:{x:1-t,y:1}};case en.BottomToTop:return{anchorMin:{x:0,y:t},anchorMax:{x:1,y:t}};case en.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 un(e,t,s,n){switch(e){case en.BottomToTop:case en.TopToBottom:return{x:s,y:n*t};default:return{x:s*t,y:n}}}function dn(e,t,s,n){if(!e.has(t,sn))return;const i=e.get(t,sn),o=ln(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,sn,i)}function hn(e,t,s,n){return t?s?{...e.pressedColor}:n?{...e.hoveredColor}:{...e.normalColor}:{...e.disabledColor}}function fn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||95===e}function pn(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(fn(r.charCodeAt(0))&&n.length>0&&fn(n.charCodeAt(n.length-1))){let e=-1;for(let t=n.length-1;t>=0;t--)if(!fn(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 mn(e){let t=1;for(;t<e;)t*=2;return t}function gn(e,t){let s=0,n=t;for(;e.has(n,Be);){const t=e.get(n,Be).entity;if(!e.valid(t))break;s++,n=t}return s}function yn(e,t){if(nn&&on){const e=nn.getUIRectComputedWidth(on,t);if(e>0)return e}return e.size.x}function _n(e,t){if(nn&&on){const e=nn.getUIRectComputedHeight(on,t);if(e>0)return e}return e.size.y}function xn(e,t,s,n,i,o){if(!e.has(t,xe))return;const r=e.get(t,xe);let a,l;switch(s){case en.BottomToTop:case en.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,xe,r))}function wn(e,t,s){let n=t;for(;e.has(n,Be);){const t=e.get(n,Be).entity;if(!e.valid(t))break;if(s(t))return;n=t}}function vn(e,t,s,n){e.has(t,s)||e.insert(t,s,n)}function Sn(e,t,s,n,i){if(!e.has(t,sn))return;const o=e.get(t,sn),r=tn(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,xe)){const s=e.get(t,xe);s.size.x===a&&s.size.y===l||(s.size.x=a,s.size.y=l,e.insert(t,xe,s))}if(e.has(t,me)){const s=e.get(t,me);s.position.x=r.originX-n,s.position.y=r.originY-i,e.insert(t,me,s)}}function bn(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 Mn=.1,Pn=30,En={r:.3,g:.5,b:.8,a:1},Tn={Left:0,Center:1,Right:2},Cn={Top:0,Middle:1,Bottom:2},Rn={Visible:0,Clip:1,Ellipsis:2},An=Ue("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:Tn.Left,verticalAlign:Cn.Top,wordWrap:!0,overflow:Rn.Visible,lineHeight:1.2});class In{constructor(e){this.cache=new Map,this.shrinkCounter_=0,this.frameMaxW_=0,this.frameMaxH_=0,this.module=e,this.canvas=c(ye.textCanvasSize,ye.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,mn(this.frameMaxW_)),e.height=Math.max(e.height,mn(this.frameMaxH_)),this.shrinkCounter_=0):e.width>4*this.frameMaxW_||e.height>4*this.frameMaxH_?(this.shrinkCounter_++,this.shrinkCounter_>=60&&(e.width=mn(this.frameMaxW_),e.height=mn(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=pn(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),f=i?Math.ceil(o):d+2*u,p=i?Math.ceil(r):h+2*u;if(i&&e.overflow===Rn.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),(n.width<f||n.height<p)&&(n.width=Math.max(n.width,mn(f)),n.height=Math.max(n.height,mn(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;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===Rn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const x=l.length*c;let w;if(i){switch(e.verticalAlign){case Cn.Top:w=u;break;case Cn.Middle:w=u+(p-2*u-x)/2;break;case Cn.Bottom:w=p-x-u;break;default:w=u}w<0&&(w=0)}else w=u;let v=w;for(const t of l){let n;switch(e.align){case Tn.Left:n=u;break;case Tn.Center:n=f/2;break;case Tn.Right:n=f-u;break;default:n=u}s.fillText(t,n,v),v+=c}i&&e.overflow===Rn.Clip&&s.restore();const S=s.getImageData(0,0,f,p),b=new Uint8Array(S.data.buffer),M=this.module.getResourceManager(),P=this.module._malloc(b.length);this.module.HEAPU8.set(b,P);const E=M.createTexture(f,p,P,b.length,1,!0);return this.module._free(P),{textureHandle:E,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const 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 Tn.Left:return"left";case Tn.Center:return"center";case Tn.Right:return"right"}}}const zn=bn({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?yn(e.uiRect,e.entity):0,containerHeight:e=>e.uiRect?_n(e.uiRect,e.entity):0});class kn{build(e){We("Text",An);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new In(t),n=e.world,i=new Map;e.addSystemToSchedule(ue.PreUpdate,de([],()=>{s.beginFrame(),s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,An));for(const e of i.keys())if(!n.valid(e)||!n.has(e,An)){if(n.valid(e)&&n.has(e,xe)){const t=n.get(e,xe);n.insert(e,xe,{texture:Le,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([An]);for(const t of e){const e=n.get(t,An),o=n.has(t,sn)?n.get(t,sn):null,r={text:e,uiRect:o,entity:t},a=i.get(t);if(a&&!zn.changed(a,r)){if(n.has(t,xe)&&n.get(t,xe).texture!==Le)continue}rn(n,t);const l=o?{size:{x:yn(o,t),y:_n(o,t)}}:null,c=s.renderForEntity(t,e,l),u=n.get(t,xe);n.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,zn.take(r))}},{name:"TextSystem"}),{runAfter:["UILayoutSystem"]})}}const Fn=new kn,Bn=0,Ln=1,Un=Fe("UIMask",{enabled:!0,mode:Bn});function Wn(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 On(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],f=e[10],p=e[11],m=e[12],g=e[13],y=e[14],_=e[15],x=n*l-i*a,w=n*c-o*a,v=n*u-r*a,S=i*c-o*l,b=i*u-r*l,M=o*u-r*c,P=d*g-h*m,E=d*y-f*m,T=d*_-p*m,C=h*y-f*g,R=h*_-p*g,A=f*_-p*y;let I=x*A-w*R+v*C+S*T-b*E+M*P;return 0===I||(I=1/I,s[0]=(l*A-c*R+u*C)*I,s[1]=(o*R-i*A-r*C)*I,s[2]=(g*M-y*b+_*S)*I,s[3]=(f*b-h*M-p*S)*I,s[4]=(c*T-a*A-u*E)*I,s[5]=(n*A-o*T+r*E)*I,s[6]=(y*v-m*M-_*w)*I,s[7]=(d*M-f*v+p*w)*I,s[8]=(a*R-l*T+u*P)*I,s[9]=(i*T-n*R-r*P)*I,s[10]=(m*b-g*v+_*x)*I,s[11]=(h*v-d*b-p*x)*I,s[12]=(l*E-a*C-c*P)*I,s[13]=(n*C-i*E+o*P)*I,s[14]=(g*w-m*S-y*x)*I,s[15]=(d*S-h*w+f*x)*I),s}function Dn(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 Hn(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)}function Yn(e,t){return 2*Math.atan2(e,t)}function $n(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 Xn(e,t,s,n,i,o,r,a,l,c){const u=Yn(l,c),d=Math.sin(-u),h=Math.cos(-u),f=e-s,p=t-n,m=f*h-p*d+s,g=f*d+p*h+n;return m>=s-i*r&&m<=s+i*(1-r)&&g>=n-o*a&&g<=n+o*(1-a)}function Nn(e,t,s,n,i,o,r){if(!e.has(t,sn)||!e.has(t,me))return null;const a=e.get(t,sn),l=e.get(t,me),c=yn(a,t)*l.worldScale.x,u=_n(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),x=Yn(l.worldRotation.z,l.worldRotation.w),w=Math.cos(x),v=Math.sin(x),S=[[d+m*w-y*v,h+m*v+y*w],[d+g*w-y*v,h+g*v+y*w],[d+g*w-_*v,h+g*v+_*w],[d+m*w-_*v,h+m*v+_*w]];let b=1/0,M=1/0,P=-1/0,E=-1/0;for(const[e,t]of S){const[a,l]=$n(e,t,s,n,i,o,r);b=Math.min(b,a),M=Math.min(M,l),P=Math.max(P,a),E=Math.max(E,l)}return{x:Math.round(b),y:Math.round(M),w:Math.round(P-b),h:Math.round(E-M)}}function Vn(e,t){return(s,n,i,o,r,a)=>{e.renderer_clearAllClipRects(),e.renderer_clearAllStencilMasks();const l=t.getEntitiesWithComponents([Un]);if(0===l.length)return;const c=[],u=[],d=new Set,h=new Set;for(const e of l){const s=t.get(e,Un);s.enabled&&(d.add(e),s.mode===Ln?(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;wn(t,e,e=>{if(i.has(e)){if(t.get(e,Un).mode===Bn)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,Un).mode===Bn){const e=Nn(t,s,o,r,a,l,c);e&&(n=Wn(u,e))}}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Nn(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;wn(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 jn{build(e){if(We("UIMask",Un),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Vn(e.wasmModule,e.world))}}const qn=new jn,Gn=Fe("Interactable",{enabled:!0,blockRaycast:!0,raycastTarget:!0}),Kn=Fe("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1}),Jn={Normal:0,Hovered:1,Pressed:2,Disabled:3},Qn=Ue("Button",{state:Jn.Normal,transition:null});class Zn{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 ei=ce(new Zn,"UIEvents");class ti{build(e){We("UIRect",sn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry();!function(e,t){nn=e,on=t}(s,n);e.addSystemToSchedule(ue.PreUpdate,de([be(St)],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(ue.PostUpdate,de([be(St)],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(ue.PostUpdate,de([],()=>{s.transform_update(n)},{name:"UITransformFinalSystem"}),{runAfter:["ScrollViewSystem","ListViewSystem"],runBefore:["UIRenderOrderSystem"]})}}const si=new ti,ni=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&&(On(t,e),s=!1),e)}}();function ii(e,t,s,n){t.emit(s,n,s),wn(e,s,i=>{if(!e.has(i,Gn))return!1;const o=e.get(i,Gn);return o.enabled&&t.emit(i,n,s),o.blockRaycast})}class oi{build(e){We("Interactable",Gn),We("Button",Qn);const t=e.world,s=e.wasmModule,n=t.getCppRegistry(),i=new Zn;e.insertResource(ei,i);let o=null,r=null;e.addSystemToSchedule(ue.PreUpdate,de([be(xt),be(St)],(e,l)=>{if(i.drain(),rt()&&!lt())return;const c=t.getEntitiesWithComponents([Kn]);for(const e of c){const s=t.get(e,Kn);(s.justPressed||s.justReleased)&&(s.justPressed=!1,s.justReleased=!1,t.insert(e,Kn,s))}if(!l.valid)return;const u=a(),d=e.mouseX*u,h=l.screenH-e.mouseY*u;ni.update(l.viewProjection);const f=Dn(d,h,ni.getInverse(l.viewProjection),l.vpX,l.vpY,l.vpW,l.vpH);l.worldMouseX=f.x,l.worldMouseY=f.y;const p=e.isMouseButtonDown(0),m=e.isMouseButtonPressed(0),g=e.isMouseButtonReleased(0);s.uiHitTest_update(n,f.x,f.y,p,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,Kn)){const e=t.get(o,Kn);e.hovered=!1,t.insert(o,Kn,e),i.emit(o,"hover_exit")}if(null!==_){vn(t,_,Kn);const e=t.get(_,Kn);e.hovered=!0,t.insert(_,Kn,e),i.emit(_,"hover_enter")}o=_}if(m&&null!==_){const e=t.get(_,Kn);e.pressed=!0,e.justPressed=!0,t.insert(_,Kn,e),r=_,ii(t,i,_,"press")}if(g&&null!==r){if(t.valid(r)&&t.has(r,Kn)){const e=t.get(r,Kn);e.pressed=!1,e.justReleased=!0,t.insert(r,Kn,e),ii(t,i,r,"release"),r===o&&ii(t,i,r,"click")}r=null}},{name:"UIInteractionSystem"}),{runAfter:["UILayoutSystem"]});const l=new Set;e.addSystemToSchedule(ue.Update,de([],()=>{const e=t.getEntitiesWithComponents([Qn]);for(const s of e){if(vn(t,s,Gn,{enabled:!0}),!t.has(s,Kn))continue;const e=t.get(s,Kn),n=t.get(s,Qn),i=t.get(s,Gn),o=!l.has(s),r=n.state;if(i.enabled?e.pressed?n.state=Jn.Pressed:e.hovered?n.state=Jn.Hovered:n.state=Jn.Normal:n.state=Jn.Disabled,o&&l.add(s),(o||r!==n.state)&&n.transition&&t.has(s,xe)){const o=t.get(s,xe);o.color=hn(n.transition,i.enabled,e.pressed,e.hovered),t.insert(s,xe,o)}}},{name:"ButtonSystem"}))}}const ri=new oi,li=Ue("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}),ci=Ue("Focusable",{tabIndex:0,isFocused:!1});class ui{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 di=ce(new ui,"FocusManager");class hi{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){if(We("TextInput",li),rt()&&!lt())return;const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,i=c(ye.textCanvasSize,64),o=i.getContext("2d",{willReadFrequently:!0});let r=0,a=0,l=!1,u=!0,d=0,h=0;const f=function(){if("undefined"==typeof document||!document.body)return null;const e=document.createElement("textarea");return e.style.position="fixed",e.style.left="-9999px",e.style.top="-9999px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.zIndex="-1",e.autocomplete="off",e.setAttribute("autocorrect","off"),e.setAttribute("autocapitalize","off"),e.setAttribute("spellcheck","false"),document.body.appendChild(e),e}();if(!f)return;const p=f;function m(){const t=e.getResource(di);if(!t||null===t.focusedEntity)return null;const n=t.focusedEntity;return s.valid(n)&&s.has(n,li)?n:null}const g=()=>{l||null===m()||v()},y=()=>{l=!0},_=()=>{l=!1,v()},x=t=>{const n=m();if(null===n)return;if("Escape"===t.key)return void S();const i=s.get(n,li);if("Enter"===t.key&&!i.multiline){t.preventDefault();return e.getResource(ei).emit(n,"submit"),void S()}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,b())},w=()=>{const t=m();if(null!==t){const n=s.get(t,li);n.focused=!1,n.dirty=!0;e.getResource(di).blur()}};function v(){const t=m();if(null===t)return;const n=s.get(t,li);if(n.readOnly)return;let i=p.value;if(n.maxLength>0&&i.length>n.maxLength&&(i=i.substring(0,n.maxLength),p.value=i),i!==n.value){n.value=i;e.getResource(ei).emit(t,"change")}n.cursorPos=p.selectionStart??i.length,n.dirty=!0,b()}function S(){const t=m();if(null!==t){const e=s.get(t,li);e.focused=!1,e.dirty=!0}e.getResource(di).blur(),p.blur()}function b(){u=!0,d=0}p.addEventListener("input",g),p.addEventListener("compositionstart",y),p.addEventListener("compositionend",_),p.addEventListener("keydown",x),p.addEventListener("blur",w),this.cleanupListeners_=()=>{p.removeEventListener("input",g),p.removeEventListener("compositionstart",y),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",x),p.removeEventListener("blur",w),p.remove();const e=t.getResourceManager();for(const t of n.values())e.releaseTexture(t);n.clear(),0!==r&&(t._free(r),r=0,a=0)};let M=null;function P(e,l,c,d){(i.width<c||i.height<d)&&(i.width=mn(Math.max(i.width,c)),i.height=mn(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 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=pn(o,p,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(p,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=pn(o,l.value,c-2*y);let i=0,r=0,a=0;for(let t=0;t<e.length;t++){const s=e[t].length;if(i+s>=l.cursorPos){r=t,a=l.cursorPos-i;break}i+=s,t<e.length-1&&i<l.value.length&&"\n"===l.value[i]&&i++,r=t+1,a=0}const u=r<e.length?e[r].substring(0,a):"";t=y+o.measureText(u).width,s=y+r*g,n=g}else t=y+o.measureText(e).width,s=(d-l.fontSize)/2,n=l.fontSize;o.fillStyle=`rgba(${Math.round(255*l.color.r)}, ${Math.round(255*l.color.g)}, ${Math.round(255*l.color.b)}, ${l.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,c,d),x=new Uint8Array(_.data.buffer),w=t.getResourceManager();x.length>a&&(0!==r&&t._free(r),r=t._malloc(x.length),a=x.length),t.HEAPU8.set(x,r);const v=n.get(e);void 0!==v&&w.releaseTexture(v);const S=w.createTexture(c,d,r,x.length,1,!0);n.set(e,S);const b=s.get(e,xe);b.texture=S,b.size.x=c,b.size.y=d,b.uvOffset.x=0,b.uvOffset.y=0,b.uvScale.x=1,b.uvScale.y=1,b.color={r:1,g:1,b:1,a:1},s.insert(e,xe,b)}e.addSystemToSchedule(ue.Update,de([be(di)],e=>{const t=s.getEntitiesWithComponents([li]);for(const e of t)vn(s,e,ci,{tabIndex:0,isFocused:!1}),vn(s,e,Gn,{enabled:!0,blockRaycast:!0});const n=m();if(n!==M){if(null!==M&&s.valid(M)&&s.has(M,li)){const e=s.get(M,li);e.focused=!1,e.dirty=!0,p.blur()}null!==n&&function(e){const t=s.get(e,li);t.readOnly||(t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}(n),M=n}},{name:"TextInputFocusSystem"}),{runAfter:["FocusSystem"]}),e.addSystemToSchedule(ue.PreUpdate,de([],()=>{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,li).dirty=!0}const r=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,li)||(r.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([li,sn]);for(const e of a){const t=s.get(e,li);if(!t.dirty)continue;const n=s.get(e,sn),i=Math.ceil(n.size.x),o=Math.ceil(n.size.y);i<=0||o<=0||(rn(s,e),P(e,t,i,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}const fi=new hi,pi={Simple:0,Sliced:1,Tiled:2,Filled:3},mi={Horizontal:0,Vertical:1},gi={Left:0,Right:1,Bottom:2,Top:3},yi=Ue("Image",{texture:Le,color:{r:1,g:1,b:1,a:1},imageType:pi.Simple,fillMethod:mi.Horizontal,fillOrigin:gi.Left,fillAmount:1,preserveAspect:!1,tileSize:{x:32,y:32},layer:0,material:0,enabled:!0}),_i=bn({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?yn(e.uiRect,e.entity):0,rectHeight:e=>e.uiRect?_n(e.uiRect,e.entity):0,enabled:e=>e.image.enabled});class xi{build(e){We("Image",yi);const t=e.world,s=new Map;e.addSystemToSchedule(ue.PreUpdate,de([],()=>{for(const e of s.keys())t.valid(e)&&t.has(e,yi)||s.delete(e);const e=t.getEntitiesWithComponents([yi]);for(const n of e){const e=t.get(n,yi),i=t.has(n,sn)?t.get(n,sn):null,o={image:e,uiRect:i,entity:n},r=s.get(n);if(r&&!_i.changed(r,o))continue;rn(t,n);const a=t.get(n,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=yn(i,n),a.size.y=_n(i,n)),a.uvOffset.x=0,a.uvOffset.y=0,a.uvScale.x=1,a.uvScale.y=1,e.imageType===pi.Filled){const t=Math.max(0,Math.min(1,e.fillAmount)),s=a.size.x,n=a.size.y;e.fillMethod===mi.Horizontal?e.fillOrigin===gi.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===gi.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===pi.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,xe,a),s.set(n,_i.take(o))}else a.color.a=0,t.insert(n,xe,a),s.set(n,_i.take(o))}},{name:"ImageSystem"}),{runAfter:["UILayoutSystem"]})}}const wi=new xi,vi=Ue("Toggle",{isOn:!0,graphicEntity:0,group:0,transition:null}),Si=Ue("ToggleGroup",{allowSwitchOff:!1});class bi{build(e){We("Toggle",vi),We("ToggleGroup",Si);const t=e.world,s=new Set;e.addSystemToSchedule(ue.Update,de([be(ei)],e=>{const n=t.getEntitiesWithComponents([vi]);if(!rt()||lt()){const i=new Map;for(const e of n){if(s.has(e))continue;s.add(e);const n=t.get(e,vi);n.isOn&&0!==n.group&&t.valid(n.group)&&(i.has(n.group)?(n.isOn=!1,t.insert(e,vi,n)):i.set(n.group,e))}const o=new Map;for(const e of n){const s=t.get(e,vi);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(vn(t,s,Gn,{enabled:!0}),!t.has(s,Kn))continue;const n=t.get(s,Kn),i=t.get(s,vi),r=t.get(s,Gn);if(n.justPressed&&r.enabled){const n=i.group,r=0!==n&&t.valid(n)&&t.has(n,Si);if(i.isOn&&r){if(!t.get(n,Si).allowSwitchOff)continue}if(i.isOn=!i.isOn,t.insert(s,vi,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,vi);i.isOn&&(i.isOn=!1,t.insert(n,vi,i),e.emit(n,"change"))}}e.emit(s,"change")}if(i.transition&&t.has(s,xe)){const e=t.get(s,xe);e.color=hn(i.transition,r.enabled,n.pressed,n.hovered),t.insert(s,xe,e)}}}for(const e of n){const s=t.get(e,vi);if(s.graphicEntity&&t.valid(s.graphicEntity)&&t.has(s.graphicEntity,xe)){const e=t.get(s.graphicEntity,xe);e.enabled=s.isOn,t.insert(s.graphicEntity,xe,e)}}},{name:"ToggleSystem"}),{runAfter:["UIInteractionSystem"]})}}const Mi=new bi,Pi=en,Ei=Ue("ProgressBar",{value:0,fillEntity:0,direction:en.LeftToRight});function Ti(e,t,s,n){if(!e.has(t,sn))return;const i=e.get(t,sn),o=s/2,r=n/2,a={left:-o,bottom:-r,right:o,top:r},l=tn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,a,i.pivot);if(e.has(t,xe)){const s=e.get(t,xe);s.size.x===l.width&&s.size.y===l.height||(s.size.x=l.width,s.size.y=l.height,e.insert(t,xe,s))}if(e.has(t,me)){const s=e.get(t,me),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,me,s))}}class Ci{build(e){We("ProgressBar",Ei);const t=e.world;e.addSystemToSchedule(ue.PreUpdate,de([],()=>{const e=t.getEntitiesWithComponents([Ei,sn]);for(const s of e){const e=t.get(s,Ei);if(!e.fillEntity||!t.valid(e.fillEntity))continue;const n=t.get(s,sn),i=Math.max(0,Math.min(1,e.value));dn(t,e.fillEntity,e.direction,i);const o=yn(n,s),r=_n(n,s);Ti(t,e.fillEntity,o,r)}},{name:"ProgressBarSystem"}),{runAfter:["UILayoutSystem"]})}}const Ri=new Ci,Ai=Ue("Draggable",{enabled:!0,dragThreshold:5,lockX:!1,lockY:!1,constraintMin:null,constraintMax:null}),Ii=Ue("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 zi{build(e){We("Draggable",Ai),We("DragState",Ii);const t=e.world,s=e.getResource(ei);let n=null,i={x:0,y:0},o=null;e.addSystemToSchedule(ue.PreUpdate,de([be(xt),be(St)],(e,r)=>{if(rt()&&!lt())return;if(!r.valid)return;const a={x:r.worldMouseX,y:r.worldMouseY};if(e.isMouseButtonPressed(0)){const e=t.getEntitiesWithComponents([Ai,Kn]);let s=null,o=-1/0,r=-1;for(const n of e){if(!t.get(n,Ai).enabled)continue;if(t.get(n,Kn).hovered){let e=0;t.has(n,xe)&&(e=t.get(n,xe).layer);const i=gn(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,Ii)||t.insert(s,Ii);const e=t.get(s,Ii),o=t.get(s,me);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,Ii)){t.get(n,Ii).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,Ai);if(c*(r.vpW/(r.worldRight-r.worldLeft))>=u.dragThreshold){o=n,n=null;t.get(o,Ii).isDragging=!0,s.emit(o,"drag_start")}}if(null!==o){if(!t.valid(o)||!t.has(o,Ii))return void(o=null);const n=t.get(o,Ii),i=t.get(o,Ai),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,f=n.currentWorldPos.y;if(n.deltaWorld={x:c-h,y:u-f},n.currentWorldPos={x:c,y:u},n.totalDeltaWorld={x:c-n.startWorldPos.x,y:u-n.startWorldPos.y},t.has(o,me)){const e=function(e,t,s,n){if(!e.has(t,Be))return{x:s,y:n};const i=e.get(t,Be).entity;if(!e.valid(i)||!e.has(i,me))return{x:s,y:n};const o=e.get(i,me),r=0!==o.worldScale.x?o.worldScale.x:1,a=0!==o.worldScale.y?o.worldScale.y:1,l=Yn(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,me);s.position.x+=e.x,s.position.y+=e.y,t.insert(o,me,s)}s.emit(o,"drag_move"),e.isMouseButtonReleased(0)&&(n.isDragging=!1,s.emit(o,"drag_end"),o=null)}},{name:"DragSystem"}))}}const ki=new zi,Fi=Ue("ScrollView",{contentEntity:0,horizontalEnabled:!1,verticalEnabled:!0,contentWidth:0,contentHeight:0,scrollX:0,scrollY:0,inertia:!0,decelerationRate:.135,elastic:!0,wheelSensitivity:.1});function Bi(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 Li(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 Ui{build(e){We("ScrollView",Fi);const t=e.world,s=new Map,n={x:0,y:0};e.addSystemToSchedule(ue.PostUpdate,de([be(xt),be(St),be(Me)],(e,i,o)=>{const r=rt()&&!lt(),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([Fi,sn]);for(const o of l){vn(t,o,Un,{enabled:!0,mode:Bn});const l=t.get(o,Fi),c=t.get(o,sn);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=yn(c,o),h=_n(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,Oe)){const e=t.get(l.contentEntity,Oe).entities;let s=0,n=0,i=0,o=0;for(const r of e){if(!t.valid(r)||!t.has(r,me))continue;const e=t.get(r,me);let a=0,l=0,c=.5,u=.5;if(t.has(r,sn)){const e=t.get(r,sn);a=yn(e,r)||e.size.x,l=_n(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<s&&(s=d),h>n&&(n=h),f<i&&(i=f),p>o&&(o=p)}0===f&&(f=n-s),0===p&&(p=o-i)}const m=Math.max(0,f-d),g=Math.max(0,p-h);if(!r&&i.valid){vn(t,o,Gn,{enabled:!0,blockRaycast:!0});const s=t.has(o,Kn)?t.get(o,Kn):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=Bi(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=Bi(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=Bi(l.scrollY,0,g,h);l.scrollY+=t.y*l.wheelSensitivity*e,u.velocityY=0}if(l.horizontalEnabled&&0!==t.x){const e=Bi(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=Li(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)<Mn&&(l.scrollX=e,u.velocityX=0)}else l.inertia&&l.horizontalEnabled&&(Math.abs(u.velocityX)>Mn?(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=Li(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)<Mn&&(l.scrollY=e,u.velocityY=0)}else l.inertia&&l.verticalEnabled&&(Math.abs(u.velocityY)>Mn?(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,me)){const e=t.get(l.contentEntity,me),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,me,e)}}},{name:"ScrollViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const Wi=new Ui,Oi=en,Di=Ue("Slider",{value:0,minValue:0,maxValue:1,direction:en.LeftToRight,fillEntity:0,handleEntity:0,wholeNumbers:!1});function Hi(e,t,s,n,i,o){const r=yn(n,i)*s.worldScale.x,a=_n(n,i)*s.worldScale.y,l=Yn(s.worldRotation.z,s.worldRotation.w),c=Math.sin(-l),u=Math.cos(-l),d=e-s.worldPosition.x,h=t-s.worldPosition.y,f=d*u-h*c,p=d*c+h*u,m=-n.pivot.x*r,g=-n.pivot.y*a;switch(o){case en.LeftToRight:return r>0?(f-m)/r:0;case en.RightToLeft:return r>0?1-(f-m)/r:0;case en.BottomToTop:return a>0?(p-g)/a:0;case en.TopToBottom:return a>0?1-(p-g)/a:0}}function Yi(e,t,s){switch(e.offsetMin.x=0,e.offsetMin.y=0,e.offsetMax.x=0,e.offsetMax.y=0,t){case en.LeftToRight:e.anchorMin.x=s,e.anchorMin.y=0,e.anchorMax.x=s,e.anchorMax.y=1;break;case en.RightToLeft:e.anchorMin.x=1-s,e.anchorMin.y=0,e.anchorMax.x=1-s,e.anchorMax.y=1;break;case en.BottomToTop:e.anchorMin.x=0,e.anchorMin.y=s,e.anchorMax.x=1,e.anchorMax.y=s;break;case en.TopToBottom:e.anchorMin.x=0,e.anchorMin.y=1-s,e.anchorMax.x=1,e.anchorMax.y=1-s}}class $i{build(e){We("Slider",Di);const t=e.world;let s=null;e.addSystemToSchedule(ue.PreUpdate,de([be(xt),be(St),be(ei)],(e,n,i)=>{if(!n.valid)return;null===s||t.valid(s)||(s=null);const o=t.getEntitiesWithComponents([Di,sn]);for(const r of o){const o=t.get(r,Di),a=t.get(r,sn);if(!rt()||lt()){if(t.has(r,me)){vn(t,r,Gn,{enabled:!0,blockRaycast:!0}),0!==o.handleEntity&&t.valid(o.handleEntity)&&vn(t,o.handleEntity,Gn,{enabled:!0,blockRaycast:!1});const l=t.get(r,me),c=t.has(r,Kn)?t.get(r,Kn):null;let u=c?.justPressed??!1;if(!u&&0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,Kn)&&(u=t.get(o.handleEntity,Kn).justPressed),u&&(s=r),s===r&&e.isMouseButtonDown(0)){let e=Hi(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,Di,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=yn(a,r),d=_n(a,r),h={left:-u/2,bottom:-d/2,right:u/2,top:d/2};if(0!==o.fillEntity&&t.valid(o.fillEntity)&&(dn(t,o.fillEntity,o.direction,c),Sn(t,o.fillEntity,h,0,0)),0!==o.handleEntity&&t.valid(o.handleEntity)&&t.has(o.handleEntity,sn)){const e=t.get(o.handleEntity,sn);Yi(e,o.direction,c),t.insert(o.handleEntity,sn,e),Sn(t,o.handleEntity,h,0,0)}}},{name:"SliderSystem"}),{runAfter:["UIInteractionSystem"]})}}const Xi=new $i;class Ni{build(e){We("Focusable",ci);const t=e.world,s=new ui;e.insertResource(di,s),e.addSystemToSchedule(ue.Update,de([be(xt),be(ei)],(e,n)=>{if(rt()&&!lt())return;null===s.focusedEntity||t.valid(s.focusedEntity)||(s.focusedEntity=null);const i=t.getEntitiesWithComponents([ci]);for(const e of i){if(!t.has(e,Kn))continue;t.get(e,Kn).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,Gn)){if(!t.get(s,Gn).enabled)continue}const n=t.get(s,ci);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,ci)){t.get(i,ci).isFocused=!1,n.emit(i,"blur",i)}s.focus(e);t.get(e,ci).isFocused=!0,n.emit(e,"focus",e)}},{name:"FocusSystem"}))}}const Vi=new Ni,ji=Ue("SafeArea",{applyTop:!0,applyBottom:!0,applyLeft:!0,applyRight:!0});function qi(){return u()?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 Gi{build(e){We("SafeArea",ji);const t=e.world;let s=qi(),n=!0,i=0,o=0;if(u()){const e=globalThis;e.wx?.onWindowResize?.(()=>{s=qi(),n=!0})}else"undefined"!=typeof window&&window.addEventListener("resize",()=>{s=qi(),n=!0});e.addSystemToSchedule(ue.PreUpdate,de([be(St)],e=>{if(!e.valid||0===e.screenH)return;const r=e.worldTop-e.worldBottom;if(e.screenH===i&&r===o||(i=e.screenH,o=r,n=!0),!n)return;n=!1;const l=a(),c=u()?r/e.screenH:l*r/e.screenH,d=t.getEntitiesWithComponents([ji,sn]);for(const e of d){const n=t.get(e,ji),i=t.get(e,sn),o=n.applyTop?s.top*c:0,r=n.applyBottom?s.bottom*c:0,a=n.applyLeft?s.left*c:0,l=n.applyRight?s.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,sn,i)}},{name:"SafeAreaSystem"}),{runBefore:["UILayoutSystem"]})}}const Ki=new Gi,Ji=Ue("ListView",{itemHeight:40,itemCount:0,scrollY:0,overscan:2});let Qi=null;function Zi(e,t){if(!Qi)return void console.warn("setListViewRenderer: ListViewPlugin has not been initialized");const s=Qi.get(e);s?s.renderer=t:Qi.set(e,{visibleStart:0,visibleEnd:0,itemEntities:new Map,renderer:t})}class eo{build(e){We("ListView",Ji);const t=e.world,s=new Map;Qi=s,e.addSystemToSchedule(ue.PostUpdate,de([be(xt)],e=>{const n=rt()&&!lt();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([Ji,sn]);for(const o of i){vn(t,o,Gn,{enabled:!0,blockRaycast:!0}),vn(t,o,Un,{enabled:!0,mode:Bn});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,Ji),a=t.get(o,sn),l=_n(a,o),c=yn(a,o);if(!n){const s=t.has(o,Kn)?t.get(o,Kn):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,De,{value:`ListItem_${e}`}),t.insert(s,sn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:c,y: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,me)){const n=t.get(s,me);n.position.y=-(e*r.itemHeight-r.scrollY),t.insert(s,me,n)}}i.visibleStart=d,i.visibleEnd=h}},{name:"ListViewSystem"}),{runAfter:["UILayoutLateSystem"],runBefore:["UIRenderOrderSystem"]})}}const to=new eo,so=Ue("Dropdown",{options:[],selectedIndex:-1,isOpen:!1,listEntity:0,labelEntity:0});class no{build(e){We("Dropdown",so);const t=e.world,s=new Map;function n(e){if(0===e||!t.valid(e))return;if(!t.has(e,me))return;const s=t.get(e,me);0===s.scale.x&&0===s.scale.y&&0===s.scale.z&&t.insert(e,me,{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,xe)){const s=t.get(e,xe);1===s.color.r&&1===s.color.g&&1===s.color.b&&1===s.color.a&&t.insert(e,xe,{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,xe),r=o.size.x,a=o.size.y;n.ddWidth=r;const l=s.options.length*Pn;t.insert(i,sn,{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,me,{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:Le,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)*Pn;t.insert(o,De,{value:`Option_${e}`}),t.insert(o,sn,{anchorMin:{x:0,y:1},anchorMax:{x:1,y:1},offsetMin:{x:0,y:-e*Pn},offsetMax:{x:0,y:0},size:{x:r,y:Pn},pivot:{x:.5,y:.5}}),t.insert(o,me,{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:Le,color:{r:.95,g:.95,b:.95,a:1},size:{x:r,y:Pn},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),t.insert(o,Gn,{enabled:!0,blockRaycast:!0,raycastTarget:!0}),t.setParent(o,i),n.optionEntities.push(o);const c=t.spawn();t.insert(c,me,{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,An,{content:s.options[e],fontSize:16,fontFamily:"Arial",color:{r:0,g:0,b:0,a:1},align:Tn.Left,verticalAlign:Cn.Middle,wordWrap:!1,overflow:Rn.Clip,lineHeight:1.2}),t.insert(c,sn,{anchorMin:{x:0,y:0},anchorMax:{x:1,y:1},offsetMin:{x:0,y:0},offsetMax:{x:0,y:0},size:{x:r,y:Pn},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,An))return;const n=t.get(s,An);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,An,{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,Gn)&&t.insert(e,Gn,{enabled:s,blockRaycast:!0,raycastTarget:!0}),t.has(e,xe))){const n=t.get(e,xe);t.insert(e,xe,{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,xe))continue;const i=s===e.highlightIndex?{...En}:{r:.95,g:.95,b:.95,a:1};t.insert(n,xe,{texture:Le,color:i,size:{x:e.ddWidth,y:Pn},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,Kn))continue;if(t.get(s,Kn).hovered)return!0}return!1}e.addSystemToSchedule(ue.Update,de([be(xt),be(ei)],(e,c)=>{for(const[e]of s)t.valid(e)||s.delete(e);const f=rt()&&!lt(),p=t.getEntitiesWithComponents([so]);for(const m of p){const p=t.get(m,so);let g=s.get(m);if(g||(g={optionEntities:[],textEntities:[],highlightIndex:-1,ddWidth:0},s.set(m,g)),n(p.listEntity),i(m),p.isOpen||u(p.listEntity,!1),l(p),f)continue;vn(t,m,Gn,{enabled:!0,blockRaycast:!0});const y=t.has(m,Kn)?t.get(m,Kn):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 s=g.optionEntities[e];if(!t.valid(s)||!t.has(s,Kn))continue;if(t.get(s,Kn).justPressed){a(m,p,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,Kn))continue;if(t.get(n,Kn).hovered){s=e;break}}s>=0&&s!==g.highlightIndex&&(g.highlightIndex=s,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 io=new no,oo=0,ro=0,lo=2,co=Ue("LayoutGroup",{direction:oo,spacing:0,padding:{left:0,top:0,right:0,bottom:0},childAlignment:ro,reverseOrder:!1});class uo{build(e){We("LayoutGroup",co);const t=e.world;e.addSystemToSchedule(ue.PreUpdate,de([],()=>{const e=t.getEntitiesWithComponents([co,sn,Oe]);for(const s of e){const e=t.get(s,co),n=t.get(s,sn),i=t.get(s,Oe);if(!i.entities||0===i.entities.length)continue;const o=[];for(const e of i.entities)t.valid(e)&&t.has(e,sn)&&t.has(e,me)&&o.push({entity:e,rect:t.get(e,sn)});if(0===o.length)continue;e.reverseOrder&&o.reverse();const r=yn(n,s),a=_n(n,s),l=n.pivot.x,c=n.pivot.y,u=e.padding,d=e.direction===oo;let h=0;for(let s=0;s<o.length;s++){const n=o[s],i=yn(n.rect,n.entity),f=_n(n.rect,n.entity),p=n.rect.pivot.x,m=n.rect.pivot.y;let g,y;d?(g=-l*r+u.left+h+p*i,y=e.childAlignment===ro?(1-c)*a-u.top-(1-m)*f:e.childAlignment===lo?-c*a+u.bottom+m*f:(.5-c)*a+.5*(u.bottom-u.top)+(m-.5)*f,h+=i,s<o.length-1&&(h+=e.spacing)):(g=e.childAlignment===ro?-l*r+u.left+p*i:e.childAlignment===lo?(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,s<o.length-1&&(h+=e.spacing));const _=t.get(n.entity,me);_.position.x=g,_.position.y=y,t.insert(n.entity,me,_)}}},{name:"LayoutGroupSystem"}),{runAfter:["UILayoutSystem"]})}}const ho=new uo;class fo{build(e){const t=e.world,s=e.wasmModule,n=t.getCppRegistry();e.addSystemToSchedule(ue.PostUpdate,de([],()=>{s.uiRenderOrder_update(n)},{name:"UIRenderOrderSystem"}))}}const po=new fo;async function mo(e,t,s){const n=e.getResource(Bs);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}const go={nearest:0,linear:1},yo={repeat:0,clamp:1,mirror:2};function _o(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=go[n.filterMode??"linear"]??1,a=yo[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 xo(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 wo(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,f=c+c,p=a*d,m=a*h,g=a*f,y=l*h,_=l*f,x=c*f,w=u*d,v=u*h,S=u*f;return new Float32Array([(1-(y+x))*i,(m+S)*i,(g-v)*i,0,(m-S)*o,(1-(p+x))*o,(_+w)*o,0,(g+v)*r,(_-w)*r,(1-(p+y))*r,0,e.worldPosition.x,e.worldPosition.y,e.worldPosition.z,1])}async function vo(e){const{app:t,module:n,sceneData:i,provider:o,spineModule:r,physicsModule:a,physicsConfig:l,manifest:c,sceneName:u}=e,d=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=x(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]=_o(e,await s.loadPixels(o),!0,t)}catch(e){console.warn(`[loadTextures] Failed to load texture: ${o}`,e),n[o]=0}}}return n}(n,i,o);!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)}}}}(n,i,d);let h={},f=null;if(r&&(f=m(r),h=await async function(e,t,s,n,i){const o={};for(const r of n.entities)for(const n of r.components){const r=w(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"===v(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 f=s.loadSkeleton(d,h,n,n.length,r);if(t._free(d),f<0)continue;o[a]=f;const p=xo(n),m=u.substring(0,u.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=m+"/"+p[t];try{const o=i.loadPixelsRaw?await i.loadPixelsRaw(n):await i.loadPixels(n),r=_o(e,o,!1),a=e.getResourceManager().getTextureGLId(r);s.setAtlasPageTexture(f,t,a,o.width,o.height)}catch{}}}catch{}}return o}(n,r,f,i,o)),a){const e={gravity:l?.gravity??{...Ye},fixedTimestep:l?.fixedTimestep??He,subStepCount:l?.subStepCount??4};new ct("",e,()=>Promise.resolve(a)).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=x(t.type).find(e=>"font"===e.type);if(!i)continue;const o=t.data[i.field];if("string"==typeof o&&o&&void 0===n[o])try{let t,i;const r=v(o);if("bitmap-font"===r?.editorType&&"json"===r.contentType){const e=JSON.parse(await s.readText(o)),r="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!r){n[o]=0;continue}const a=o.substring(0,o.lastIndexOf("/")),l=a?`${a}/${r}`:r;t=await s.readText(l),i=l.substring(0,l.lastIndexOf("/"))}else t=await s.readText(o),i=o.substring(0,o.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[o]=0;continue}const l=i?`${i}/${a[1]}`:a[1],c=s.loadPixelsRaw?await s.loadPixelsRaw(l):await s.loadPixels(l),u=_o(e,c,!1),d=e.getResourceManager();n[o]=d.loadBitmapFont(t,u,c.width,c.height)}catch{n[o]=0}}return n}(n,i,o),g=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=x(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=he.createShader(e.vertexSource,e.fragmentSource),n[i]=r),s[o]=he.createFromAsset(e,r)}catch{s[o]=0}}return s}(i,o);await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=x(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=b(n),r=new Map;for(const t of o)try{const n=await s.loadPixels(t);r.set(t,_o(e,n))}catch{r.set(t,0)}const a=E(i,n,r);T(a)}catch(e){console.warn(`[loadAnimClips] Failed to load animation clip: ${i}`,e)}}}}}(n,i,o),await async function(e,t,s){const n=new Set;for(const i of t.entities)for(const t of i.components){const i=x(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=A(JSON.parse(t));if(!n)continue;const o=[];for(const t of n.tilesets){const n=z(i,t.image);let r=0;try{const t=await s.loadPixels(n);r=_o(e,t),k(r,t.width,t.height)}catch{}o.push({textureHandle:r,columns:t.columns})}F(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)}}}}}(n,i,o),await async function(e,t){const s=[],n=new Set;for(const t of e.entities)for(const e of t.components){const t=x(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 D.preloadFromData(e,s.buffer)}catch(t){console.warn(`[preloadAudioClips] Failed to preload audio: ${e}`,t)}})):await D.preloadAll(s).catch(e=>{console.warn("[preloadAudioClips] Failed to preload audio assets:",e)}))}(i,o),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=x(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)}}}(i,d,p,g);const _=y(t.world,i);if(u&&t.hasResource(Bs))for(const e of _.values())t.world.insert(e,_e,{scene:u,persistent:!1});if(r&&f){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=w(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}(f,i,h,_);!function(e,t,s,n,i){let o=0;e.setSpineRenderer((r,a)=>{let l=a-o;o=a,(l<=0||l>$e)&&(l=Xe);const c=e.world;for(const e in i){const o=Number(e),r=i[e],a=c.has(o,we)?c.get(o,we):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(r,l*d);let h=0;if(c.has(o,me)){const e=wo(c.get(o,me),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const f=n.getMeshBatchCount(r);for(let e=0;e<f;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),f=s._malloc(4);n.getMeshBatchData(r,e,c,u,d,f);const p=s.HEAPU32[d>>2],m=s.HEAPU32[f>>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,p,m,h),t._free(_),t._free(x),s._free(c),s._free(u),s._free(d),s._free(f)}h&&t._free(h)}})}(t,n,r,f,e)}if(c){const e=t.getResource(s);e&&e.setAddressableManifest(c)}}function So(e,t,s){return{name:e,async setup(){await vo({...s,sceneData:t,sceneName:e})}}}async function bo(e){const{app:t,firstScene:s,aspectRatio:n}=e;Ds(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(Bs);for(const t of e.scenes)o.register(So(t.name,t.data,i));s&&(o.setInitial(s),await o.load(s)),void 0!==n&&p(t.world,n)}class Mo{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=w(e.type);if(i){const n=e.data[i.skeletonField],o=e.data[i.atlasField];n&&("binary"===v(n)?.contentType?s.add(n):t.add(n)),o&&t.add(o)}const o=x(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=v(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),i=await createImageBitmap(n),o=new OffscreenCanvas(i.width,i.height).getContext("2d");o.drawImage(i,0,0);const r=o.getImageData(0,0,i.width,i.height);return i.close(),{width:r.width,height:r.height,pixels:new Uint8Array(r.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Po="__preview__";class Eo{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(Bs);t.register({name:Po,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Po),this.loadPromise_=t.load(Po).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await H(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new Mo(this.baseUrl_);await s.prefetch(t);let n=null;const i=this.app_.spineInitPromise;if(i){n=(await i).controller.raw}await vo({app:this.app_,module:this.app_.wasmModule,sceneData:t,provider:s,spineModule:n,sceneName:Po})}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Ne]);for(const n of s){if(e.get(n,Ne).isActive){t=!0;break}}if(!t){console.warn("[PreviewPlugin] No active camera found, creating default camera");let t=540,s=Ge/Ke;const n=e.getEntitiesWithComponents([Ve]);for(const i of n){const n=e.get(i,Ve);if(n.designResolution){const e=n.pixelsPerUnit||je;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const i=this.app_.getResource(Bs).getScene(Po),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,me,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:qe.ColorAndDepth};e.insert(o,Ne,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(Bs);await e.switchTo(Po),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 To={create(e){const t=e.depth??!0,s="linear"===e.filter,n=(t?1:0)|(s?2:0),i=Ps.createRenderTarget(e.width,e.height,n);return{_handle:i,textureId:Ps.getTargetTexture(i),width:e.width,height:e.height,_depth:t,_filter:s?"linear":"nearest"}},release(e){Ps.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Ps.releaseRenderTarget(e._handle),To.create({width:t,height:s,depth:e._depth,filter:e._filter})),begin(e,t){Ps.begin(t,e._handle)},end(){Ps.end()},getDepthTexture:e=>Ps.getTargetDepthTexture(e._handle)};var Co;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Co||(Co={}));class Ro{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Co[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Co.Debug:console.debug(t,s);break;case Co.Info:console.log(t,s);break;case Co.Warn:console.warn(t,s);break;case Co.Error:console.error(t,s)}}}class Ao{constructor(){this.handlers_=[],this.minLevel_=Co.Info,this.addHandler(new Ro)}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(Co.Debug,e,t,s)}info(e,t,s){this.log(Co.Info,e,t,s)}warn(e,t,s){this.log(Co.Warn,e,t,s)}error(e,t,s){this.log(Co.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 Io=new Ao;function zo(){return Io}function ko(e){Io.setMinLevel(e)}function Fo(e,t,s){Io.debug(e,t,s)}function Bo(e,t,s){Io.info(e,t,s)}function Lo(e,t,s){Io.warn(e,t,s)}function Uo(e,t,s){Io.error(e,t,s)}const Wo={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},Oo={Running:0,Paused:1,Completed:2,Cancelled:3},Do={None:0,Restart:1,PingPong:2};const Ho=1.70158,Yo=2.70158,$o=2.5949095;const Xo=2*Math.PI/3,No=2*Math.PI/4.5;const Vo=7.5625,jo=2.75;const qo=1e-6;function Go(e,t,s){switch(e){case Wo.Linear:return t;case Wo.EaseInQuad:return function(e){return e*e}(t);case Wo.EaseOutQuad:return function(e){return e*(2-e)}(t);case Wo.EaseInOutQuad:return function(e){return e<.5?2*e*e:(4-2*e)*e-1}(t);case Wo.EaseInCubic:return function(e){return e*e*e}(t);case Wo.EaseOutCubic:return function(e){const t=e-1;return t*t*t+1}(t);case Wo.EaseInOutCubic:return function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}(t);case Wo.EaseInBack:return function(e){return Yo*e*e*e-Ho*e*e}(t);case Wo.EaseOutBack:return function(e){const t=e-1;return 1+Yo*t*t*t+Ho*t*t}(t);case Wo.EaseInOutBack:return function(e){return e<.5?Math.pow(2*e,2)*(7.189819*e-$o)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+$o)+2)/2}(t);case Wo.EaseInElastic:return function(e){return 0===e||1===e?e:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*Xo)}(t);case Wo.EaseOutElastic:return function(e){return 0===e||1===e?e:Math.pow(2,-10*e)*Math.sin((10*e-.75)*Xo)+1}(t);case Wo.EaseInOutElastic:return function(e){return 0===e||1===e?e:e<.5?-Math.pow(2,20*e-10)*Math.sin((20*e-11.125)*No)/2:Math.pow(2,-20*e+10)*Math.sin((20*e-11.125)*No)/2+1}(t);case Wo.EaseOutBounce:return function(e){return e<1/jo?Vo*e*e:e<2/jo?Vo*(e-=1.5/jo)*e+.75:e<2.5/jo?Vo*(e-=2.25/jo)*e+.9375:Vo*(e-=2.625/jo)*e+.984375}(t);case Wo.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)<qo)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)<qo)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 Wo.Step:return function(e){return e<1?0:1}(t);default:return t}}const Ko=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??Wo.Linear,bezierPoints:null,state:Oo.Running,loop:i?.loop??Do.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)===Oo.Completed&&(this.resume(t),this.cppSequences_.delete(e))}for(const t of this.entries_.values()){if(t.state!==Oo.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=Go(t.easing,s,t.bezierPoints??void 0);if(t.callback(t.from+(t.to-t.from)*n),s>=1){if(t.loop!==Do.None){const e=0===t.loopCount;if(e||t.loopsRemaining>1){if(e||t.loopsRemaining--,t.elapsed=0,t.loop===Do.PingPong){const e=t.from;t.from=t.to,t.to=e}continue}}t.state=Oo.Completed,null!==t.sequenceNext&&this.resume(t.sequenceNext),t.sequenceNextExternal&&t.sequenceNextExternal.resume()}}}pause(e){const t=this.entries_.get(e);t&&t.state===Oo.Running&&(t.state=Oo.Paused)}resume(e){const t=this.entries_.get(e);t&&t.state===Oo.Paused&&(t.state=Oo.Running)}cancel(e){const t=this.entries_.get(e);t&&(t.state=Oo.Cancelled)}getState(e){const t=this.entries_.get(e);return t?t.state:Oo.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 Jo{constructor(e){this.id=e}get state(){return Ko.getState(this.id)}bezier(e,t,s,n){return Ko.setBezier(this.id,e,t,s,n),this}then(e){return e instanceof Jo?Ko.setSequenceNext(this.id,e.id):Ko.setSequenceNextExternal(this.id,e),this}pause(){Ko.pause(this.id)}resume(){Ko.resume(this.id)}cancel(){Ko.cancel(this.id)}}const Qo={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 Zo{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 Jo?(Ko.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 er=null,tr=null;function sr(e,t){er=e,tr=t,Ko.init(e,t)}function nr(){Ko.shutdown(),er=null,tr=null}function ir(){if(!er)throw new Error("Tween API not initialized");return er}function or(){if(!tr)throw new Error("Tween API not initialized");return tr}const rr={to(e,t,s,n,i,o){const r=ir(),a=or(),l=o?.easing??Wo.Linear,c=o?.delay??0,u=o?.loop??Do.None,d=o?.loopCount??0,h=r._anim_createTween(a,e,t,s,n,i,l,c,u,d);return new Zo(r,a,h)},value(e,t,s,n,i){const o=Ko.create(e,t,s,n,i);return new Jo(o)},cancel(e){ir()._anim_cancelTween(or(),e.entity)},cancelAll(e){ir()._anim_cancelAllTweens(or(),e)},update(e){ir()._anim_updateTweens(or(),e),Ko.update(e)}};class lr{constructor(){this.name="AnimationPlugin"}build(e){sr(e.wasmModule,e.world.getCppRegistry());const t=e.world;e.addSystemToSchedule(ue.Update,de([be(Me)],e=>{rr.update(e.delta)},{name:"TweenSystem"})),e.addSystemToSchedule(ue.Update,de([be(Me)],e=>{q(t,e.delta)},{name:"SpriteAnimatorSystem"}),{runAfter:["TweenSystem"]})}cleanup(){nr()}}const cr=new lr;var ur;!function(e){e[e.Linear=0]="Linear",e[e.Inverse=1]="Inverse",e[e.Exponential=2]="Exponential"}(ur||(ur={}));const dr={model:ur.Inverse,refDistance:100,maxDistance:1e3,rolloff:1};function hr(e,t=dr){const{model:s,refDistance:n,maxDistance:i,rolloff:o}=t,r=Math.max(e,.001);let a;switch(s){case ur.Linear:{const e=i-n;if(e<=0)return 1;a=1-(Math.min(Math.max(r,n),i)-n)/e;break}case ur.Inverse:a=n/Math.max(r,n);break;case ur.Exponential:a=Math.pow(Math.max(r,n)/n,-o);break;default:return 1}return Math.max(0,Math.min(1,a))}function fr(e,t,s,n,i){const o=e-s;return Math.max(-1,Math.min(1,o/i))}const pr=Ue("AudioSource",{clip:"",bus:"sfx",volume:1,pitch:1,loop:!1,playOnAwake:!1,spatial:!1,minDistance:100,maxDistance:1e3,attenuationModel:ur.Inverse,rolloff:1,priority:0,enabled:!0}),mr=Ue("AudioListener",{enabled:!0});class gr{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;D.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(ue.PreUpdate,de([be(Me)],t=>{if(!(!rt()||lt()))return void(c&&(l=!1,c=!1));c=!0;const n=e.world;let i=0,u=0,d=!1;const h=n.getEntitiesWithComponents([mr,Je]);for(const e of h){if(n.get(e,mr).enabled){const t=n.get(e,Je);i=t.position.x,u=t.position.y,d=!0;break}}const f=n.getEntitiesWithComponents([pr]);a.clear();for(const e of f){const t=n.get(e,pr);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=D.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,Je),a=r?.position.x??0,h=r?.position.y??0,f=a-i,p=h-u,m=hr(Math.sqrt(f*f+p*p),{model:t.attenuationModel,refDistance:t.minDistance,maxDistance:t.maxDistance,rolloff:t.rolloff}),g=fr(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(),D.dispose()}}const yr=new gr;let _r=null,xr=null;function wr(e,t){_r=e,xr=t}function vr(){_r=null,xr=null}const Sr={update(e){_r&&xr&&_r.particle_update?.(xr,e)},play(e){_r&&xr&&_r.particle_play?.(xr,e)},stop(e){_r&&xr&&_r.particle_stop?.(xr,e)},reset(e){_r&&xr&&_r.particle_reset?.(xr,e)},getAliveCount:e=>_r?_r.particle_getAliveCount?.(e)??0:0};class br{constructor(){this.name="ParticlePlugin"}build(e){wr(e.wasmModule,e.world.getCppRegistry()),e.addSystemToSchedule(ue.Update,de([be(Me)],e=>{Sr.update(e.delta)},{name:"ParticleSystem"}))}cleanup(){vr()}}const Mr=new br,Pr=1e6;class Er{constructor(){this.name="TilemapPlugin",this.initializedLayers_=new Set,this.sourceEntityKeys_=new Map}build(e){const t=e.wasmModule;oe(t);const s=e.world,n=this.initializedLayers_,i=this.sourceEntityKeys_;e.pipeline?.setTilemapRenderer(()=>{const t=e.getResource(St),o=t?.valid?t.worldLeft:-1e6,r=t?.valid?t.worldBottom:-1e6,a=t?.valid?t.worldRight:Pr,l=t?.valid?t.worldTop:Pr,c=s.getEntitiesWithComponents([G,me]);for(const e of c){const t=s.tryGet(e,G),i=s.tryGet(e,me);if(!t||!i)continue;if(!t.visible)continue;const c=t.texture;if(!c)continue;const u=ee(c);if(!u)continue;if(!n.has(e)){if(te.initLayer(e,t.width,t.height,t.tileWidth,t.tileHeight),t.tiles.length>0){const s=new Uint16Array(t.tiles.length);for(let e=0;e<t.tiles.length;e++)s[e]=t.tiles[e];te.setTiles(e,s)}n.add(e)}const d=t.tileWidth/u.width,h=t.tileHeight/u.height,f=t.tint,p=t.parallaxFactor;te.submitLayer(e,c,t.layer,0,t.tilesetColumns,d,h,i.worldPosition.x,i.worldPosition.y,o,r,a,l,f.r,f.g,f.b,f.a,t.opacity,p.x,p.y)}const u=s.getEntitiesWithComponents([se,me]);for(const e of u){if(s.tryGet(e,G))continue;const t=s.tryGet(e,se),c=s.tryGet(e,me);if(!t?.source||!c)continue;const u=ne(t.source);if(!u)continue;if(!i.has(e)){const t=[];for(let s=0;s<u.layers.length;s++){const i=1073741824+256*e+s,o=u.layers[s];te.initLayer(i,o.width,o.height,u.tileWidth,u.tileHeight),o.tiles.length>0&&te.setTiles(i,o.tiles),t.push(i),n.add(i)}i.set(e,t)}const d=i.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=ee(s.textureHandle);if(!n)continue;const i=u.tileWidth/n.width,h=u.tileHeight/n.height;te.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_)te.destroyLayer(e);this.initializedLayers_.clear(),this.sourceEntityKeys_.clear(),ie(),re()}}const Tr=new Er;function Cr(e,t){return e.toFixed(t)}function Rr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Ar{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">${Cr(e.fps,1)}</span> Frame: <span style="color:#d19a66">${Cr(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>${Rr(e.length>20?e.slice(0,20)+"...":e).padEnd(22)}<span style="color:#d19a66">${Cr(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 Ir(){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 zr=ce(Ir(),"Stats");class kr{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}}const Fr="StatsCollect";class Br{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 Lr{constructor(e){this.name="Stats",this.collector_=new Br,this.overlay_=null,this.options_=e??{}}build(e){this.collector_.reset(),e.enableStats(),e.insertResource(zr,Ir());if(!1!==this.options_.overlay&&"undefined"!=typeof document){const e=this.options_.container??document.body;this.overlay_=new Ar(e,this.options_.position)}const t=this.collector_,s=this.overlay_,n=de([be(Me),Qe()],(n,i)=>{t.pushFrame(n.delta);const o=e.getResource(zr);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(Fr),o.systemTimings=e}else o.systemTimings=new Map;const a=e.getPhaseTimings();o.phaseTimings=a?new Map(a):new Map;const l=Ps.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:Fr});e.addSystemToSchedule(ue.Last,n)}cleanup(){this.overlay_?.dispose(),this.overlay_=null}}const Ur=new Lr;class Wr{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 Or(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}}async function Dr(e){const{app:t,module:n,assets:i,scenes:o,firstScene:r}=e,a=t.getResource(s);a&&(a.registerEmbeddedAssets(i),a.setEmbeddedOnly(!0));const l=e.spineWasmBase64?await async function(e){if("undefined"==typeof ESSpineModule)return null;const t=await Or(ESSpineModule,e);return t||console.warn("Spine module not available"),t}(e.spineWasmBase64):null,c=e.physicsWasmBase64?await async function(e){if("undefined"==typeof ESPhysicsModule)return null;const t=await Or(ESPhysicsModule,e);return t||console.warn("Physics module not available"),t}(e.physicsWasmBase64):null,u=new Wr(i);await bo({app:t,module:n,provider:u,scenes:o,firstScene:r,spineModule:l,physicsModule:c,physicsConfig:e.physicsConfig,manifest:e.manifest,aspectRatio:e.canvas.width/e.canvas.height}),t.run()}const Hr=[Fn,qn,si,wi,Ri,ri,ki,Wi,Xi,Mi,fi,Vi,Ki,to,io,ho,po],Yr=[...Hr,cr,yr,Mr,Tr,xs];function $r(e,t){return function(e,t){const s=Os.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ot(e),Ae(e),Ot(e),Jt(e),bs(e),Ts(e);const i=new As;s.setPipeline(i);let l=o();const c=t?.getViewportSize??(()=>{const e=a();return{width:window.innerWidth*e,height:window.innerHeight*e}});function u(t,i,o){o||(o=Ns(e,n,t,i));const r=s.getResource(St);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(St,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,worldMouseX:0,worldMouseY:0,valid:!1});const d={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=c();u(e,t)}},h={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:r}=c();if(0===t||0===r)return;const a=e.registry_getCanvasEntity(n);if(a>=0){const e=n.getCanvas(a).backgroundColor;Ps.setClearColor(e.x,e.y,e.z,e.w)}const d=(o()-l)/1e3;let h;if(Ps.resize(t,r),s.hasResource(Bs)){const e=s.getResource(Bs).getActiveScenes();e.length>0&&(h=new Set(e))}i.setActiveScenes(h??null);const f=Ns(e,n,t,r,s.world,h);if(u(t,r,f),0===f.length)i.render({registry:{_cpp:n},viewProjection:Hs,width:t,height:r,elapsed:d});else{i.beginScreenCapture();for(const e of f){const s=e.viewportRect,o=Math.round(s.x*t),a=Math.round((1-s.y-s.h)*r),l=Math.round(s.w*t),c=Math.round(s.h*r);i.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:a,w:l,h:c},clearFlags:e.clearFlags,elapsed:d,cameraEntity:e.entity})}i.endScreenCapture(),Ps.setViewport(0,0,t,r)}}};if(s.addSystemToSchedule(ue.First,d),s.addSystemToSchedule(ue.Last,h),s.addPlugin(r),s.addPlugin(kt),s.addPlugin(vt),s.addPlugin(Ws),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Yr,...t})}le(mt);export{lr as AnimationPlugin,Os as App,bt as AssetRefCounter,s as Assets,ur as AttenuationModel,D as Audio,ut as AudioBus,mr as AudioListener,dt as AudioMixer,gr as AudioPlugin,ht as AudioPool,pr as AudioSource,ve as BitmapText,Qn as Button,Jn as ButtonState,Ne as Camera,Ve as Canvas,Oe as Children,qe as ClearFlags,Ke as DEFAULT_DESIGN_HEIGHT,Ge as DEFAULT_DESIGN_WIDTH,Xe as DEFAULT_FALLBACK_DT,He as DEFAULT_FIXED_TIMESTEP,Ye as DEFAULT_GRAVITY,$e as DEFAULT_MAX_DELTA_TIME,je as DEFAULT_PIXELS_PER_UNIT,Ft as DataType,zi as DragPlugin,Ii as DragState,Ai as Draggable,Ze as Draw,so as Dropdown,no as DropdownPlugin,Wo as EasingType,Pe as EventRegistry,en as FillDirection,mi as FillMethod,gi as FillOrigin,di as FocusManager,ui as FocusManagerState,Ni as FocusPlugin,ci as Focusable,kr as FrameHistory,Rs as GLDebug,Yt as Geometry,Qe as GetWorld,Le as INVALID_TEXTURE,yi as Image,xi as ImagePlugin,pi as ImageType,xt as Input,wt as InputPlugin,_t as InputState,Gn as Interactable,uo as LayoutGroupPlugin,Ji as ListView,eo as ListViewPlugin,Co as LogLevel,Ao as Logger,Do as LoopMode,he as Material,De as Name,Be as Parent,Sr as Particle,br as ParticlePlugin,ct as PhysicsPlugin,es as PostProcess,_s as PostProcessPlugin,qt as PostProcessStack,ge as PostProcessVolume,At as PrefabServer,It as Prefabs,zt as PrefabsPlugin,Eo as PreviewPlugin,Ei as ProgressBar,Pi as ProgressBarDirection,Ci as ProgressBarPlugin,Ie as ProjectionType,pe as Query,As as RenderPipeline,ws as RenderStage,To as RenderTexture,Ps as Renderer,be as Res,Se as ResMut,ye as RuntimeConfig,ji as SafeArea,Gi as SafeAreaPlugin,ze as ScaleMode,Bs as SceneManager,Fs as SceneManagerState,_e as SceneOwner,ue as Schedule,Fi as ScrollView,Ui as ScrollViewPlugin,Di as Slider,Oi as SliderDirection,$i as SliderPlugin,we as SpineAnimation,xe as Sprite,zr as Stats,Br as StatsCollector,Ar as StatsOverlay,Lr as StatsPlugin,yt as Storage,Ce as SystemRunner,An as Text,Tn as TextAlign,li as TextInput,hi as TextInputPlugin,Rn as TextOverflow,kn as TextPlugin,In as TextRenderer,Cn as TextVerticalAlign,se as Tilemap,te as TilemapAPI,G as TilemapLayer,Er as TilemapPlugin,Me as Time,vi as Toggle,bi as TogglePlugin,me as Transform,rr as Tween,Zo as TweenHandle,Oo as TweenState,Qo as TweenTarget,St as UICameraInfo,Zn as UIEventQueue,ei as UIEvents,Kn as UIInteraction,oi as UIInteractionPlugin,ti as UILayoutPlugin,Un as UIMask,jn as UIMaskPlugin,sn as UIRect,fo as UIRenderOrderPlugin,Mo as WebAssetProvider,Ee as World,Je as WorldTransform,cr as animationPlugin,dn as applyDirectionalFill,r as assetPlugin,yr as audioPlugin,hr as calculateAttenuation,fr as calculatePanning,ds as cleanupAllPostProcessVolumes,us as cleanupPostProcessVolume,nt as clearDrawCallbacks,ie as clearTextureDimensionsCache,ln as computeFillAnchors,un as computeFillSize,cn as computeHandleAnchors,tn as computeUIRectLayout,Vn as createMaskProcessor,So as createRuntimeSceneConfig,$r as createWebApp,Fo as debug,Ir as defaultFrameStats,Ue as defineComponent,ce as defineResource,de as defineSystem,ki as dragPlugin,io as dropdownPlugin,Uo as error,b as extractAnimClipTexturePaths,Ds as flushPendingSystems,Vi as focusPlugin,os as getAllEffectDefs,v as getAssetTypeEntry,x as getComponentAssetFieldDescriptors,i as getComponentEntityFields,w as getComponentSpineFieldDescriptor,ns as getEffectDef,is as getEffectTypes,zo as getLogger,t as getPlatform,ee as getTextureDimensions,ne as getTilemapSource,wi as imagePlugin,Bo as info,ot as initDrawAPI,Ts as initGLDebugAPI,Ot as initGeometryAPI,Ae as initMaterialAPI,wr as initParticleAPI,Dr as initPlayableRuntime,Jt as initPostProcessAPI,bs as initRendererAPI,bo as initRuntime,oe as initTilemapAPI,sr as initTweenAPI,vt as inputPlugin,Pt as instantiatePrefab,Wn as intersectRects,On as invertMatrix4,rt as isEditor,lt as isPlayMode,u as isWeChat,ho as layoutGroupPlugin,to as listViewPlugin,vo as loadRuntimeScene,y as loadSceneData,n as loadSceneWithAssets,E as parseAnimClipData,A as parseTmjJson,Mr as particlePlugin,H as platformFetch,Xn as pointInOBB,Hn as pointInWorldRect,xs as postProcessPlugin,kt as prefabsPlugin,Ri as progressBarPlugin,T as registerAnimClip,We as registerComponent,st as registerDrawCallback,Mt as registerEmbeddedAssets,k as registerTextureDimensions,F as registerTilemapSource,z as resolveRelativePath,Ki as safeAreaPlugin,Ws as sceneManagerPlugin,Dn as screenToWorld,Wi as scrollViewPlugin,Zi as setListViewRenderer,ko as setLogLevel,ke as setWasmErrorHandler,it as shutdownDrawAPI,Cs as shutdownGLDebugAPI,Dt as shutdownGeometryAPI,Re as shutdownMaterialAPI,vr as shutdownParticleAPI,Qt as shutdownPostProcessAPI,Ms as shutdownRendererAPI,re as shutdownTilemapAPI,nr as shutdownTweenAPI,Xi as sliderPlugin,q as spriteAnimatorSystemUpdate,Ur as statsPlugin,xn as syncFillSpriteSize,cs as syncPostProcessVolume,fi as textInputPlugin,Fn as textPlugin,Tr as tilemapPlugin,Mi as togglePlugin,mo as transitionTo,ri as uiInteractionPlugin,si as uiLayoutPlugin,qn as uiMaskPlugin,Hr as uiPlugins,po as uiRenderOrderPlugin,et as unregisterDrawCallback,p as updateCameraAspectRatio,Lo as warn,Ls as wrapSceneSystem};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/physics/index.d.ts b/desktop/public/sdk/esm/physics/index.d.ts
index 8b792f83a..896b532c6 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -1,47 +1,5 @@
-/**
- * @file resource.ts
- * @brief Resource system for global singleton data
- */
-interface ResourceDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _default: T;
-}
-interface ResDescriptor<T> {
- readonly _type: 'res';
- readonly _resource: ResourceDef<T>;
-}
-interface ResMutDescriptor<T> {
- readonly _type: 'res_mut';
- readonly _resource: ResourceDef<T>;
-}
-
-/**
- * @file types.ts
- * @brief Core type definitions for ESEngine SDK
- */
-type Entity = number;
-interface Vec2 {
- x: number;
- y: number;
-}
-interface Vec3 {
- x: number;
- y: number;
- z: number;
-}
-interface Vec4 {
- x: number;
- y: number;
- z: number;
- w: number;
-}
-interface Quat {
- w: number;
- x: number;
- y: number;
- z: number;
-}
+import { B as BuiltinComponentDef, R as ResourceDef, A as App, P as Plugin } from '../shared/app.js';
+import { V as Vec2, a as Entity } from '../shared/wasm.js';
interface RigidBodyData {
bodyType: number;
@@ -60,6 +18,8 @@ interface BoxColliderData {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
interface CircleColliderData {
radius: number;
@@ -69,6 +29,8 @@ interface CircleColliderData {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
interface CapsuleColliderData {
radius: number;
@@ -79,11 +41,13 @@ interface CapsuleColliderData {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
-declare const RigidBody$1: BuiltinComponentDef<RigidBodyData>;
-declare const BoxCollider$1: BuiltinComponentDef<BoxColliderData>;
-declare const CircleCollider$1: BuiltinComponentDef<CircleColliderData>;
-declare const CapsuleCollider$1: BuiltinComponentDef<CapsuleColliderData>;
+declare const RigidBody: BuiltinComponentDef<RigidBodyData>;
+declare const BoxCollider: BuiltinComponentDef<BoxColliderData>;
+declare const CircleCollider: BuiltinComponentDef<CircleColliderData>;
+declare const CapsuleCollider: BuiltinComponentDef<CapsuleColliderData>;
declare const BodyType: {
readonly Static: 0;
readonly Kinematic: 1;
@@ -91,950 +55,6 @@ declare const BodyType: {
};
type BodyType = (typeof BodyType)[keyof typeof BodyType];
-/**
- * @file component.ts
- * @brief Component definition and builtin components
- */
-
-interface ComponentDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _default: T;
- readonly _builtin: false;
- create(data?: Partial<T>): T;
-}
-interface BuiltinComponentDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _cppName: string;
- readonly _builtin: true;
- readonly _default: T;
-}
-type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
-type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
-
-/**
- * @file wasm.generated.ts
- * @brief ESEngine WASM Bindings TypeScript Definitions
- * @details Generated by EHT - DO NOT EDIT
- */
-
-interface UVec2 {
- x: number;
- y: number;
-}
-interface VectorEntity {
- size(): number;
- get(index: number): number;
- push_back(value: number): void;
- set(index: number, value: number): boolean;
- delete(): void;
-}
-interface UIRect {
- anchorMin: Vec2;
- anchorMax: Vec2;
- offsetMin: Vec2;
- offsetMax: Vec2;
- size: Vec2;
- pivot: Vec2;
-}
-interface FlexItem {
- flexGrow: number;
- flexShrink: number;
- flexBasis: number;
- order: number;
-}
-interface BoxCollider {
- halfExtents: Vec2;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CircleCollider {
- radius: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CapsuleCollider {
- radius: number;
- halfHeight: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface ParticleEmitter {
- rate: number;
- burstCount: number;
- burstInterval: number;
- duration: number;
- looping: boolean;
- playOnStart: boolean;
- maxParticles: number;
- lifetimeMin: number;
- lifetimeMax: number;
- shape: number;
- shapeRadius: number;
- shapeSize: Vec2;
- shapeAngle: number;
- speedMin: number;
- speedMax: number;
- angleSpreadMin: number;
- angleSpreadMax: number;
- startSizeMin: number;
- startSizeMax: number;
- endSizeMin: number;
- endSizeMax: number;
- sizeEasing: number;
- startColor: Vec4;
- endColor: Vec4;
- colorEasing: number;
- rotationMin: number;
- rotationMax: number;
- angularVelocityMin: number;
- angularVelocityMax: number;
- gravity: Vec2;
- damping: number;
- texture: number;
- spriteColumns: number;
- spriteRows: number;
- spriteFPS: number;
- spriteLoop: boolean;
- blendMode: number;
- layer: number;
- material: number;
- simulationSpace: number;
- enabled: boolean;
-}
-interface Transform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
- worldPosition: Vec3;
- worldRotation: Quat;
- worldScale: Vec3;
-}
-interface Velocity {
- linear: Vec3;
- angular: Vec3;
-}
-interface SpineAnimation {
- skeletonPath: string;
- atlasPath: string;
- skin: string;
- animation: string;
- timeScale: number;
- loop: boolean;
- playing: boolean;
- flipX: boolean;
- flipY: boolean;
- color: Vec4;
- layer: number;
- skeletonScale: number;
- material: number;
- enabled: boolean;
-}
-interface Interactable {
- enabled: boolean;
- blockRaycast: boolean;
- raycastTarget: boolean;
-}
-interface UIInteraction {
- hovered: boolean;
- pressed: boolean;
- justPressed: boolean;
- justReleased: boolean;
-}
-interface RigidBody {
- bodyType: number;
- gravityScale: number;
- linearDamping: number;
- angularDamping: number;
- fixedRotation: boolean;
- bullet: boolean;
- enabled: boolean;
-}
-interface BitmapText {
- text: string;
- color: Vec4;
- fontSize: number;
- align: number;
- spacing: number;
- layer: number;
- font: number;
- enabled: boolean;
-}
-interface Sprite {
- texture: number;
- color: Vec4;
- size: Vec2;
- uvOffset: Vec2;
- uvScale: Vec2;
- layer: number;
- flipX: boolean;
- flipY: boolean;
- material: number;
- enabled: boolean;
-}
-interface UIMask {
- enabled: boolean;
- mode: number;
-}
-interface FlexContainer {
- direction: number;
- wrap: number;
- justifyContent: number;
- alignItems: number;
- gap: Vec2;
- padding: Vec4;
-}
-interface Parent {
- entity: number;
-}
-interface Children {
- entities: VectorEntity;
-}
-interface ScreenSpace {
-}
-interface Canvas {
- designResolution: UVec2;
- pixelsPerUnit: number;
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: Vec4;
-}
-interface Camera {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- aspectRatio: number;
- isActive: boolean;
- priority: number;
- viewportX: number;
- viewportY: number;
- viewportW: number;
- viewportH: number;
- clearFlags: number;
-}
-interface Registry {
- create(): Entity;
- destroy(entity: Entity): void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- hasUIRect(entity: Entity): boolean;
- getUIRect(entity: Entity): UIRect;
- addUIRect(entity: Entity, component: UIRect): void;
- removeUIRect(entity: Entity): void;
- hasFlexItem(entity: Entity): boolean;
- getFlexItem(entity: Entity): FlexItem;
- addFlexItem(entity: Entity, component: FlexItem): void;
- removeFlexItem(entity: Entity): void;
- hasBoxCollider(entity: Entity): boolean;
- getBoxCollider(entity: Entity): BoxCollider;
- addBoxCollider(entity: Entity, component: BoxCollider): void;
- removeBoxCollider(entity: Entity): void;
- hasCircleCollider(entity: Entity): boolean;
- getCircleCollider(entity: Entity): CircleCollider;
- addCircleCollider(entity: Entity, component: CircleCollider): void;
- removeCircleCollider(entity: Entity): void;
- hasCapsuleCollider(entity: Entity): boolean;
- getCapsuleCollider(entity: Entity): CapsuleCollider;
- addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
- removeCapsuleCollider(entity: Entity): void;
- hasParticleEmitter(entity: Entity): boolean;
- getParticleEmitter(entity: Entity): ParticleEmitter;
- addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
- removeParticleEmitter(entity: Entity): void;
- hasTransform(entity: Entity): boolean;
- getTransform(entity: Entity): Transform;
- addTransform(entity: Entity, component: Transform): void;
- removeTransform(entity: Entity): void;
- hasVelocity(entity: Entity): boolean;
- getVelocity(entity: Entity): Velocity;
- addVelocity(entity: Entity, component: Velocity): void;
- removeVelocity(entity: Entity): void;
- hasSpineAnimation(entity: Entity): boolean;
- getSpineAnimation(entity: Entity): SpineAnimation;
- addSpineAnimation(entity: Entity, component: SpineAnimation): void;
- removeSpineAnimation(entity: Entity): void;
- hasInteractable(entity: Entity): boolean;
- getInteractable(entity: Entity): Interactable;
- addInteractable(entity: Entity, component: Interactable): void;
- removeInteractable(entity: Entity): void;
- hasUIInteraction(entity: Entity): boolean;
- getUIInteraction(entity: Entity): UIInteraction;
- addUIInteraction(entity: Entity, component: UIInteraction): void;
- removeUIInteraction(entity: Entity): void;
- hasRigidBody(entity: Entity): boolean;
- getRigidBody(entity: Entity): RigidBody;
- addRigidBody(entity: Entity, component: RigidBody): void;
- removeRigidBody(entity: Entity): void;
- hasBitmapText(entity: Entity): boolean;
- getBitmapText(entity: Entity): BitmapText;
- addBitmapText(entity: Entity, component: BitmapText): void;
- removeBitmapText(entity: Entity): void;
- hasSprite(entity: Entity): boolean;
- getSprite(entity: Entity): Sprite;
- addSprite(entity: Entity, component: Sprite): void;
- removeSprite(entity: Entity): void;
- hasUIMask(entity: Entity): boolean;
- getUIMask(entity: Entity): UIMask;
- addUIMask(entity: Entity, component: UIMask): void;
- removeUIMask(entity: Entity): void;
- hasFlexContainer(entity: Entity): boolean;
- getFlexContainer(entity: Entity): FlexContainer;
- addFlexContainer(entity: Entity, component: FlexContainer): void;
- removeFlexContainer(entity: Entity): void;
- hasParent(entity: Entity): boolean;
- getParent(entity: Entity): Parent;
- addParent(entity: Entity, component: Parent): void;
- removeParent(entity: Entity): void;
- hasChildren(entity: Entity): boolean;
- getChildren(entity: Entity): Children;
- addChildren(entity: Entity, component: Children): void;
- removeChildren(entity: Entity): void;
- hasScreenSpace(entity: Entity): boolean;
- getScreenSpace(entity: Entity): ScreenSpace;
- addScreenSpace(entity: Entity, component: ScreenSpace): void;
- removeScreenSpace(entity: Entity): void;
- hasCanvas(entity: Entity): boolean;
- getCanvas(entity: Entity): Canvas;
- addCanvas(entity: Entity, component: Canvas): void;
- removeCanvas(entity: Entity): void;
- hasCamera(entity: Entity): boolean;
- getCamera(entity: Entity): Camera;
- addCamera(entity: Entity, component: Camera): void;
- removeCamera(entity: Entity): void;
- setParent(child: Entity, parent: Entity): void;
-}
-
-/**
- * @file wasm.ts
- * @brief WASM module type definitions
- */
-
-interface CppRegistry extends Registry {
- delete(): void;
- removeParent(entity: Entity): void;
- [key: string]: Function | undefined;
-}
-interface CppResourceManager {
- createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
- createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
- createShader(vertSrc: string, fragSrc: string): number;
- registerExternalTexture(glTextureId: number, width: number, height: number): number;
- getTextureGLId(handle: number): number;
- releaseTexture(handle: number): void;
- releaseShader(handle: number): void;
- setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
- registerTextureWithPath(handle: number, path: string): void;
- loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
- createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
- releaseBitmapFont(handle: number): void;
- measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
- width: number;
- height: number;
- };
-}
-interface EmscriptenFS {
- writeFile(path: string, data: string | Uint8Array): void;
- readFile(path: string, opts?: {
- encoding?: string;
- }): string | Uint8Array;
- mkdir(path: string): void;
- mkdirTree(path: string): void;
- unlink(path: string): void;
- stat(path: string): {
- mode: number;
- size: number;
- };
- isFile(mode: number): boolean;
- isDir(mode: number): boolean;
- analyzePath(path: string): {
- exists: boolean;
- parentExists: boolean;
- };
-}
-interface SpineBounds {
- x: number;
- y: number;
- width: number;
- height: number;
- valid: boolean;
-}
-interface ESEngineModule {
- Registry: new () => CppRegistry;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- HEAPF32: Float32Array;
- FS: EmscriptenFS;
- materialDataProvider?: (materialId: number, outShaderIdPtr: number, outBlendModePtr: number, outUniformBufferPtr: number, outUniformCountPtr: number) => void;
- initRenderer(): void;
- initRendererWithCanvas(canvasSelector: string): boolean;
- initRendererWithContext(contextHandle: number): boolean;
- shutdownRenderer(): void;
- GL: {
- registerContext(ctx: WebGLRenderingContext | WebGL2RenderingContext, options: {
- majorVersion: number;
- minorVersion: number;
- enableExtensionsByDefault?: boolean;
- }): number;
- };
- renderFrame(registry: CppRegistry, width: number, height: number): void;
- renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;
- getResourceManager(): CppResourceManager;
- getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;
- invalidateMaterialCache(materialId: number): void;
- clearMaterialCache(): void;
- draw_begin(matrixPtr: number): void;
- draw_end(): void;
- draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_rect(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
- draw_rectOutline(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_circle(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
- draw_circleOutline(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
- draw_texture(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_textureRotated(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_setLayer(layer: number): void;
- draw_setDepth(depth: number): void;
- draw_getDrawCallCount(): number;
- draw_getPrimitiveCount(): number;
- draw_setBlendMode(mode: number): void;
- draw_setDepthTest(enabled: boolean): void;
- draw_mesh(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
- draw_meshWithUniforms(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
- geometry_create(): number;
- geometry_init(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
- geometry_setIndices16(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_setIndices32(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_updateVertices(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
- geometry_release(handle: number): void;
- geometry_isValid(handle: number): boolean;
- postprocess_init(width: number, height: number): boolean;
- postprocess_shutdown(): void;
- postprocess_resize(width: number, height: number): void;
- postprocess_addPass(name: string, shaderHandle: number): number;
- postprocess_removePass(name: string): void;
- postprocess_setPassEnabled(name: string, enabled: boolean): void;
- postprocess_isPassEnabled(name: string): boolean;
- postprocess_setUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- postprocess_begin(): void;
- postprocess_end(): void;
- postprocess_getPassCount(): number;
- postprocess_isInitialized(): boolean;
- postprocess_setBypass(bypass: boolean): void;
- postprocess_isBypassed(): boolean;
- postprocess_clearPasses(): void;
- postprocess_setOutputTarget(fboId: number): void;
- postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
- postprocess_beginScreenCapture(): void;
- postprocess_endScreenCapture(): void;
- postprocess_executeScreenPasses(): void;
- postprocess_addScreenPass(name: string, shaderHandle: number): number;
- postprocess_clearScreenPasses(): void;
- postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- renderer_init(width: number, height: number): void;
- renderer_resize(width: number, height: number): void;
- renderer_begin(matrixPtr: number, targetHandle: number): void;
- renderer_flush(): void;
- renderer_end(): void;
- renderer_submitSprites(registry: CppRegistry): void;
- renderer_submitBitmapText(registry: CppRegistry): void;
- renderer_submitSpine?(registry: CppRegistry): void;
- renderer_submitParticles?(registry: CppRegistry): void;
- renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
- particle_update?(registry: CppRegistry, dt: number): void;
- particle_play?(registry: CppRegistry, entity: number): void;
- particle_stop?(registry: CppRegistry, entity: number): void;
- particle_reset?(registry: CppRegistry, entity: number): void;
- particle_getAliveCount?(entity: number): number;
- tilemap_initLayer?(entity: number, width: number, height: number, tileWidth: number, tileHeight: number): void;
- tilemap_destroyLayer?(entity: number): void;
- tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
- tilemap_getTile?(entity: number, x: number, y: number): number;
- tilemap_fillRect?(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
- tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
- tilemap_hasLayer?(entity: number): boolean;
- tilemap_submitLayer?(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- renderer_setStage(stage: number): void;
- renderer_createTarget(width: number, height: number, flags: number): number;
- renderer_releaseTarget(handle: number): void;
- renderer_getTargetTexture(handle: number): number;
- renderer_getTargetDepthTexture(handle: number): number;
- renderer_getDrawCalls(): number;
- renderer_getTriangles(): number;
- renderer_getSprites(): number;
- renderer_getText(): number;
- renderer_getSpine?(): number;
- renderer_getMeshes(): number;
- renderer_getCulled(): number;
- renderer_setClearColor(r: number, g: number, b: number, a: number): void;
- renderer_setViewport(x: number, y: number, w: number, h: number): void;
- renderer_setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
- renderer_clearBuffers(flags: number): void;
- renderer_setEntityClipRect(entity: number, x: number, y: number, w: number, h: number): void;
- renderer_clearEntityClipRect(entity: number): void;
- renderer_clearAllClipRects(): void;
- renderer_clearStencil(): void;
- renderer_setEntityStencilMask(entity: number, refValue: number): void;
- renderer_setEntityStencilTest(entity: number, refValue: number): void;
- renderer_clearEntityStencilMask(entity: number): void;
- renderer_clearAllStencilMasks(): void;
- registry_getCanvasEntity(registry: CppRegistry): number;
- registry_getCameraEntities(registry: CppRegistry): number[];
- getChildEntities(registry: CppRegistry, entity: number): number[];
- registry_getGeneration(registry: CppRegistry, entity: number): number;
- registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;
- gl_enableErrorCheck(enabled: boolean): void;
- gl_checkErrors(context: string): number;
- renderer_diagnose(): void;
- uiLayout_update(registry: CppRegistry, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
- uiHitTest_getHitEntity(): number;
- uiHitTest_getHitEntityPrev(): number;
- uiRenderOrder_update(registry: CppRegistry): void;
- uiFlexLayout_update(registry: CppRegistry): void;
- getUIRectComputedWidth(registry: CppRegistry, entity: number): number;
- getUIRectComputedHeight(registry: CppRegistry, entity: number): number;
- transform_update(registry: CppRegistry): void;
- _anim_createTween(registry: CppRegistry, entity: number, targetProp: number, from: number, to: number, duration: number, easing: number, delay: number, loopMode: number, loopCount: number): number;
- _anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
- _anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_setTweenBezier(registry: CppRegistry, tweenEntity: number, p1x: number, p1y: number, p2x: number, p2y: number): void;
- _anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
- _anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
- _anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-
-/**
- * @file world.ts
- * @brief ECS World with C++ Registry integration
- */
-
-declare class World {
- private cppRegistry_;
- private module_;
- private entities_;
- private tsStorage_;
- private entityComponents_;
- private queryPool_;
- private queryPoolIdx_;
- private worldVersion_;
- private queryCache_;
- private builtinMethodCache_;
- private iterationDepth_;
- private nextEntityId_;
- private nextGeneration_;
- private spawnCallbacks_;
- private despawnCallbacks_;
- private worldTick_;
- private componentAddedTicks_;
- private componentChangedTicks_;
- private componentRemovedBuffer_;
- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void;
- disconnectCpp(): void;
- get hasCpp(): boolean;
- getCppRegistry(): CppRegistry | null;
- spawn(): Entity;
- despawn(entity: Entity): void;
- onSpawn(callback: (entity: Entity) => void): () => void;
- onDespawn(callback: (entity: Entity) => void): () => void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- getWorldVersion(): number;
- beginIteration(): void;
- endIteration(): void;
- resetIterationDepth(): void;
- isIterating(): boolean;
- getAllEntities(): Entity[];
- setParent(child: Entity, parent: Entity): void;
- removeParent(entity: Entity): void;
- insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
- set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
- get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
- has(entity: Entity, component: AnyComponentDef): boolean;
- tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null;
- remove(entity: Entity, component: AnyComponentDef): void;
- private getBuiltinMethods;
- private insertBuiltin;
- private getBuiltin;
- private hasBuiltin;
- private removeBuiltin;
- private insertScript;
- private getScript;
- private hasScript;
- private removeScript;
- private getStorage;
- resetQueryPool(): void;
- getComponentTypes(entity: Entity): string[];
- getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string): Entity[];
- advanceTick(): void;
- getWorldTick(): number;
- isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
- isChangedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
- getRemovedEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[];
- cleanRemovedBuffer(beforeTick: number): void;
- private recordAddedTick_;
- private recordChangedTick_;
- private recordRemovedTick_;
-}
-
-/**
- * @file query.ts
- * @brief Component query system with mutable component support
- */
-
-interface MutWrapper<T extends AnyComponentDef> {
- readonly _type: 'mut';
- readonly _component: T;
-}
-interface AddedWrapper<T extends AnyComponentDef> {
- readonly _filterType: 'added';
- readonly _component: T;
-}
-interface ChangedWrapper<T extends AnyComponentDef> {
- readonly _filterType: 'changed';
- readonly _component: T;
-}
-type QueryArg$1 = AnyComponentDef | MutWrapper<AnyComponentDef> | AddedWrapper<AnyComponentDef> | ChangedWrapper<AnyComponentDef>;
-interface QueryDescriptor<C extends readonly QueryArg$1[]> {
- readonly _type: 'query';
- readonly _components: C;
- readonly _mutIndices: number[];
- readonly _with: AnyComponentDef[];
- readonly _without: AnyComponentDef[];
- readonly _addedFilters: Array<{
- index: number;
- component: AnyComponentDef;
- }>;
- readonly _changedFilters: Array<{
- index: number;
- component: AnyComponentDef;
- }>;
-}
-interface RemovedQueryDescriptor<T extends AnyComponentDef> {
- readonly _type: 'removed';
- readonly _component: T;
-}
-
-/**
- * @file commands.ts
- * @brief Deferred entity/component operations
- */
-
-interface CommandsDescriptor {
- readonly _type: 'commands';
-}
-
-/**
- * @file event.ts
- * @brief Event system with double-buffered event buses
- */
-interface EventDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _phantom?: T;
-}
-interface EventWriterDescriptor<T> {
- readonly _type: 'event_writer';
- readonly _event: EventDef<T>;
-}
-interface EventReaderDescriptor<T> {
- readonly _type: 'event_reader';
- readonly _event: EventDef<T>;
-}
-
-/**
- * @file system.ts
- * @brief System definition and scheduling
- */
-
-declare enum Schedule {
- Startup = 0,
- First = 1,
- PreUpdate = 2,
- Update = 3,
- PostUpdate = 4,
- Last = 5,
- FixedPreUpdate = 10,
- FixedUpdate = 11,
- FixedPostUpdate = 12
-}
-interface GetWorldDescriptor {
- readonly _type: 'get_world';
-}
-type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
-type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
-interface SystemDef {
- readonly _id: symbol;
- readonly _params: readonly SystemParam[];
- readonly _fn: (...args: never[]) => void;
- readonly _name: string;
-}
-
-/**
- * @file renderPipeline.ts
- * @brief Unified render pipeline for runtime and editor
- */
-
-interface RenderParams {
- registry: {
- _cpp: CppRegistry;
- };
- viewProjection: Float32Array;
- width: number;
- height: number;
- elapsed: number;
-}
-interface CameraRenderParams {
- registry: {
- _cpp: CppRegistry;
- };
- viewProjection: Float32Array;
- viewportPixels: {
- x: number;
- y: number;
- w: number;
- h: number;
- };
- clearFlags: number;
- elapsed: number;
- cameraEntity?: Entity;
-}
-type SpineRendererFn = (registry: {
- _cpp: CppRegistry;
-}, elapsed: number) => void;
-type TilemapRendererFn = () => void;
-type MaskProcessorFn = (registry: CppRegistry, vp: Float32Array, viewportX: number, viewportY: number, viewportW: number, viewportH: number) => void;
-declare class RenderPipeline {
- private spineRenderer_;
- private tilemapRenderer_;
- private maskProcessor_;
- private lastWidth_;
- private lastHeight_;
- private activeScenes_;
- get spineRenderer(): SpineRendererFn | null;
- setSpineRenderer(fn: SpineRendererFn | null): void;
- setTilemapRenderer(fn: TilemapRendererFn | null): void;
- get maskProcessor(): MaskProcessorFn | null;
- setMaskProcessor(fn: MaskProcessorFn | null): void;
- setActiveScenes(scenes: Set<string> | null): void;
- beginScreenCapture(): void;
- endScreenCapture(): void;
- render(params: RenderParams): void;
- renderCamera(params: CameraRenderParams): void;
- private executeDrawCallbacks;
-}
-
-/**
- * @file material.ts
- * @brief Material and Shader API for custom rendering
- * @details Provides shader creation and material management for custom visual effects.
- */
-
-type ShaderHandle = number;
-
-/**
- * @file scene.ts
- * @brief Scene loading utilities
- */
-
-interface SceneEntityData {
- id: number;
- name: string;
- parent: number | null;
- children: number[];
- components: SceneComponentData[];
- visible?: boolean;
-}
-interface SceneComponentData {
- type: string;
- data: Record<string, unknown>;
-}
-interface SliceBorder {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-interface TextureMetadata {
- version: string;
- type: 'texture';
- sliceBorder: SliceBorder;
-}
-interface SceneData {
- version: string;
- name: string;
- entities: SceneEntityData[];
- textureMetadata?: Record<string, TextureMetadata>;
-}
-
-/**
- * @file customDraw.ts
- * @brief Custom draw callback registration for the render pipeline
- */
-type DrawCallback = (elapsed: number) => void;
-
-interface PassConfig {
- name: string;
- shader: ShaderHandle;
- enabled: boolean;
- floatUniforms: Map<string, number>;
- vec4Uniforms: Map<string, Vec4>;
-}
-declare class PostProcessStack {
- readonly id: number;
- private passes_;
- private destroyed_;
- constructor();
- addPass(name: string, shader: ShaderHandle): this;
- removePass(name: string): this;
- setEnabled(name: string, enabled: boolean): this;
- setUniform(passName: string, uniform: string, value: number): this;
- setUniformVec4(passName: string, uniform: string, value: Vec4): this;
- setAllPassesEnabled(enabled: boolean): void;
- get passCount(): number;
- get enabledPassCount(): number;
- get passes(): readonly PassConfig[];
- get isDestroyed(): boolean;
- destroy(): void;
-}
-
-interface SceneConfig {
- name: string;
- path?: string;
- data?: SceneData;
- systems?: Array<{
- schedule: Schedule;
- system: SystemDef;
- }>;
- setup?: (ctx: SceneContext) => void | Promise<void>;
- cleanup?: (ctx: SceneContext) => void;
-}
-interface SceneContext {
- readonly name: string;
- readonly entities: ReadonlySet<Entity>;
- spawn(): Entity;
- despawn(entity: Entity): void;
- registerDrawCallback(id: string, fn: DrawCallback): void;
- bindPostProcess(camera: Entity, stack: PostProcessStack): void;
- unbindPostProcess(camera: Entity): void;
- setPersistent(entity: Entity, persistent: boolean): void;
-}
-
-/**
- * @file app.ts
- * @brief Application builder and web platform integration
- */
-
-type PluginDependency = string | ResourceDef<any>;
-interface Plugin {
- name?: string;
- dependencies?: PluginDependency[];
- build(app: App): void;
- finish?(app: App): void;
- cleanup?(app?: App): void;
-}
-declare class App {
- private readonly world_;
- private readonly resources_;
- private readonly systems_;
- private runner_;
- private running_;
- private lastTime_;
- private fixedTimestep_;
- private fixedAccumulator_;
- private maxDeltaTime_;
- private maxFixedSteps_;
- private module_;
- private pipeline_;
- private spineInitPromise_?;
- private physicsInitPromise_?;
- private physicsModule_?;
- private readonly installed_plugins_;
- private readonly installedPluginSet_;
- private readonly installedPluginNames_;
- private pluginsFinished_;
- private readonly eventRegistry_;
- private readonly sortedSystemsCache_;
- private error_handler_;
- private system_error_handler_;
- private statsEnabled_;
- private phaseTimings_;
- private frame_paused_;
- private user_paused_;
- private step_pending_;
- private play_speed_;
- private constructor();
- static new(): App;
- addPlugin(plugin: Plugin): this;
- addEvent<T>(event: EventDef<T>): this;
- addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
- runBefore?: string[];
- runAfter?: string[];
- }): this;
- addSystem(system: SystemDef): this;
- addStartupSystem(system: SystemDef): this;
- removeSystem(systemId: symbol): boolean;
- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
- get wasmModule(): ESEngineModule | null;
- get pipeline(): RenderPipeline | null;
- setPipeline(pipeline: RenderPipeline): void;
- setSpineRenderer(fn: SpineRendererFn | null): void;
- get spineInitPromise(): Promise<unknown> | undefined;
- set spineInitPromise(p: Promise<unknown> | undefined);
- get physicsInitPromise(): Promise<unknown> | undefined;
- set physicsInitPromise(p: Promise<unknown> | undefined);
- get physicsModule(): unknown;
- set physicsModule(m: unknown);
- get world(): World;
- setFixedTimestep(timestep: number): this;
- setMaxDeltaTime(v: number): this;
- setMaxFixedSteps(v: number): this;
- onError(handler: (error: unknown, systemName: string) => void): this;
- onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
- onWasmError(handler: (error: unknown, context: string) => void): this;
- setPaused(paused: boolean): void;
- isPaused(): boolean;
- stepFrame(): void;
- setPlaySpeed(speed: number): void;
- getPlaySpeed(): number;
- enableStats(): this;
- getSystemTimings(): ReadonlyMap<string, number> | null;
- getPhaseTimings(): ReadonlyMap<string, number> | null;
- getEntityCount(): number;
- insertResource<T>(resource: ResourceDef<T>, value: T): this;
- getResource<T>(resource: ResourceDef<T>): T;
- hasResource<T>(resource: ResourceDef<T>): boolean;
- registerScene(config: SceneConfig): this;
- setInitialScene(name: string): this;
- tick(delta: number): void;
- run(): void;
- private mainLoop;
- quit(): void;
- private finishPlugins_;
- private sortSystems;
- private runSchedule;
- private updateTime;
-}
-
/**
* @file PhysicsModuleLoader.ts
* @brief Loads and initializes the Physics WASM module (standalone or side module)
@@ -1045,9 +65,9 @@ interface PhysicsWasmModule {
_physics_createBody(entityId: number, bodyType: number, x: number, y: number, angle: number, gravityScale: number, linearDamping: number, angularDamping: number, fixedRotation: number, bullet: number): void;
_physics_destroyBody(entityId: number): void;
_physics_hasBody(entityId: number): number;
- _physics_addBoxShape(entityId: number, halfW: number, halfH: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;
- _physics_addCircleShape(entityId: number, radius: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;
- _physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number): void;
+ _physics_addBoxShape(entityId: number, halfW: number, halfH: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number, categoryBits: number, maskBits: number): void;
+ _physics_addCircleShape(entityId: number, radius: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number, categoryBits: number, maskBits: number): void;
+ _physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number, offX: number, offY: number, density: number, friction: number, restitution: number, isSensor: number, categoryBits: number, maskBits: number): void;
_physics_step(dt: number): void;
_physics_setBodyTransform(entityId: number, x: number, y: number, angle: number): void;
_physics_getDynamicBodyCount(): number;
@@ -1114,6 +134,7 @@ interface PhysicsPluginConfig {
gravity?: Vec2;
fixedTimestep?: number;
subStepCount?: number;
+ collisionLayerMasks?: number[];
}
interface CollisionEnterEvent {
entityA: Entity;
@@ -1164,5 +185,5 @@ declare class Physics {
static setDebugDrawConfig(app: App, config: Partial<PhysicsDebugDrawConfig>): void;
}
-export { BodyType, BoxCollider$1 as BoxCollider, CapsuleCollider$1 as CapsuleCollider, CircleCollider$1 as CircleCollider, Physics, PhysicsAPI, PhysicsDebugDraw, PhysicsEvents, PhysicsPlugin, RigidBody$1 as RigidBody, drawPhysicsDebug, loadPhysicsModule, loadPhysicsSideModule, setupPhysicsDebugDraw };
+export { BodyType, BoxCollider, CapsuleCollider, CircleCollider, Physics, PhysicsAPI, PhysicsDebugDraw, PhysicsEvents, PhysicsPlugin, RigidBody, drawPhysicsDebug, loadPhysicsModule, loadPhysicsSideModule, setupPhysicsDebugDraw };
export type { BoxColliderData, CapsuleColliderData, CircleColliderData, CollisionEnterEvent, ESEngineMainModule, PhysicsDebugDrawConfig, PhysicsEventsData, PhysicsModuleFactory, PhysicsPluginConfig, PhysicsWasmModule, RigidBodyData, SensorEvent };
diff --git a/desktop/public/sdk/esm/physics/index.js b/desktop/public/sdk/esm/physics/index.js
index 5262651d4..b2fa7397d 100644
--- a/desktop/public/sdk/esm/physics/index.js
+++ b/desktop/public/sdk/esm/physics/index.js
@@ -1,2 +1,2 @@
-const e=4294967295,t=100,n=100;function s(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(s);const t={};for(const n in e)t[n]=s(e[n]);return t}let r=0;function i(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function o(e,t){const n=a.get(e)??i().get(e);if(n)return n;const o=function(e,t){const n=++r,i=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=>i?e?{...s(t),...e}:s(t):e?{...t,...e}:{...t}}}(e,t);return i().set(e,o),a.set(e,o),function(e,t,n){const s=globalThis;s.__esengine_registerComponent&&s.__esengine_registerComponent(e,t,n)}(e,t,!1),o}const a=new Map;function l(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return a.set(e,n),n}const c=l("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}});l("Sprite",{texture:e,color:{r:1,g:1,b:1,a:1},size:{x:t,y:n},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),l("Camera",{projectionType:1,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:3});const u=l("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}});l("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}});const y=l("Parent",{entity:0});l("Children",{entities:[]}),l("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0}),l("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});const d=0;l("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:3,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:d,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:d,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:e,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:0,enabled:!0}),o("Name",{value:""}),o("SceneOwner",{scene:"",persistent:!1}),o("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});let p=0;function h(e,t){const n=++p;return{_id:Symbol(`Resource_${n}_${t??""}`),_name:t??`Resource_${n}`,_default:e}}const f=h({delta:0,elapsed:0,frameCount:0},"Time");function _(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e)}var m;!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"}(m||(m={}));let g=0;async function b(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 x(e,t){await t.loadDynamicLibrary(new Uint8Array(e),{loadAsync:!0,allowUndefined:!0});const n=t.cwrap.bind(t);return{_physics_init:n("physics_init",null,["number","number","number","number"]),_physics_shutdown:n("physics_shutdown",null,[]),_physics_createBody:n("physics_createBody",null,["number","number","number","number","number","number","number","number","number","number"]),_physics_destroyBody:n("physics_destroyBody",null,["number"]),_physics_hasBody:n("physics_hasBody","number",["number"]),_physics_addBoxShape:n("physics_addBoxShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_addCircleShape:n("physics_addCircleShape",null,["number","number","number","number","number","number","number","number"]),_physics_addCapsuleShape:n("physics_addCapsuleShape",null,["number","number","number","number","number","number","number","number","number"]),_physics_step:n("physics_step",null,["number"]),_physics_setBodyTransform:n("physics_setBodyTransform",null,["number","number","number","number"]),_physics_getDynamicBodyCount:n("physics_getDynamicBodyCount","number",[]),_physics_getDynamicBodyTransforms:n("physics_getDynamicBodyTransforms","number",[]),_physics_collectEvents:n("physics_collectEvents",null,[]),_physics_getCollisionEnterCount:n("physics_getCollisionEnterCount","number",[]),_physics_getCollisionEnterBuffer:n("physics_getCollisionEnterBuffer","number",[]),_physics_getCollisionExitCount:n("physics_getCollisionExitCount","number",[]),_physics_getCollisionExitBuffer:n("physics_getCollisionExitBuffer","number",[]),_physics_getSensorEnterCount:n("physics_getSensorEnterCount","number",[]),_physics_getSensorEnterBuffer:n("physics_getSensorEnterBuffer","number",[]),_physics_getSensorExitCount:n("physics_getSensorExitCount","number",[]),_physics_getSensorExitBuffer:n("physics_getSensorExitBuffer","number",[]),_physics_applyForce:n("physics_applyForce",null,["number","number","number"]),_physics_applyImpulse:n("physics_applyImpulse",null,["number","number","number"]),_physics_setLinearVelocity:n("physics_setLinearVelocity",null,["number","number","number"]),_physics_getLinearVelocity:n("physics_getLinearVelocity","number",["number"]),_physics_setGravity:n("physics_setGravity",null,["number","number"]),_physics_getGravity:n("physics_getGravity","number",[]),_physics_setAngularVelocity:n("physics_setAngularVelocity",null,["number","number"]),_physics_getAngularVelocity:n("physics_getAngularVelocity","number",["number"]),_physics_applyTorque:n("physics_applyTorque",null,["number","number"]),_physics_applyAngularImpulse:n("physics_applyAngularImpulse",null,["number","number"]),_physics_updateBodyProperties:n("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=l("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),M=l("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),E=l("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),P=l("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0}),S={Static:0,Kinematic:1,Dynamic:2};var A;function C(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"}(A||(A={}));let v=1;const D=new Map;function B(){throw new Error("Material API not initialized. Call initMaterialAPI() first.")}const T={createShader:(e,t)=>B().createShader(e,t),releaseShader(e){e>0&&B().releaseShader(e)},create(e){const t=v++,n={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??A.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 D.set(t,n),t},get:e=>D.get(e),setUniform(e,t,n){const s=D.get(e);s&&(s.uniforms.set(t,n),s.dirty_=!0)},getUniform(e,t){const n=D.get(e);return n?.uniforms.get(t)},setBlendMode(e,t){const n=D.get(e);n&&(n.blendMode=t)},getBlendMode(e){const t=D.get(e);return t?.blendMode??A.Normal},setDepthTest(e,t){const n=D.get(e);n&&(n.depthTest=t)},getShader(e){const t=D.get(e);return t?.shader??0},release(e){D.delete(e)},isValid:e=>D.has(e),releaseAll(){D.clear()},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??A.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=D.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const n=v++,s={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return D.set(n,s),n},toAssetData(e,t){const n=D.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=D.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};const R=new Float32Array(256);function U(){throw new Error("Draw API not initialized. Call initDrawAPI() first.")}const z={r:1,g:1,b:1,a:1},F={begin(e){const t=U();try{t.HEAPF32.set(e,0),t.draw_begin(0)}catch(e){_(e,"Draw.begin")}},end(){try{U().draw_end()}catch(e){_(e,"Draw.end")}},line(e,t,n,s=1){try{U().draw_line(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){_(e,"Draw.line")}},rect(e,t,n,s=!0){try{U().draw_rect(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){_(e,"Draw.rect")}},rectOutline(e,t,n,s=1){try{U().draw_rectOutline(e.x,e.y,t.x,t.y,n.r,n.g,n.b,n.a,s)}catch(e){_(e,"Draw.rectOutline")}},circle(e,t,n,s=!0,r=32){try{U().draw_circle(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){_(e,"Draw.circle")}},circleOutline(e,t,n,s=1,r=32){try{U().draw_circleOutline(e.x,e.y,t,n.r,n.g,n.b,n.a,s,r)}catch(e){_(e,"Draw.circleOutline")}},texture(e,t,n,s=z){try{U().draw_texture(e.x,e.y,t.x,t.y,n,s.r,s.g,s.b,s.a)}catch(e){_(e,"Draw.texture")}},textureRotated(e,t,n,s,r=z){try{U().draw_textureRotated(e.x,e.y,t.x,t.y,n,s,r.r,r.g,r.b,r.a)}catch(e){_(e,"Draw.textureRotated")}},setLayer(e){U().draw_setLayer(e)},setDepth(e){U().draw_setDepth(e)},getDrawCallCount:()=>0,getPrimitiveCount:()=>0,setBlendMode(e){U().draw_setBlendMode(e)},setDepthTest(e){U().draw_setDepthTest(e)},drawMesh(e,t,n){try{const s=U();s.HEAPF32.set(n,0),s.draw_mesh(e,t,0)}catch(n){_(n,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,n){try{const s=U(),r=T.get(t);if(!r)return;if(F.setBlendMode(r.blendMode),F.setDepthTest(r.depthTest),0===r.uniforms.size)return void F.drawMesh(e,r.shader,n);let i;if(s.HEAPF32.set(n,0),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,n]of r.uniforms){const s=V(t);if(!(s<0)){if(C(n))R[i++]=10,R[i++]=s,R[i++]=n.slot??e++,R[i++]=n.textureId;else if("number"==typeof n)R[i++]=1,R[i++]=s,R[i++]=n;else if(Array.isArray(n)){R[i++]=n.length,R[i++]=s;for(let e=0;e<n.length;e++)R[i++]=n[e]}else"w"in n?(R[i++]=4,R[i++]=s,R[i++]=n.x,R[i++]=n.y,R[i++]=n.z,R[i++]=n.w):"z"in n?(R[i++]=3,R[i++]=s,R[i++]=n.x,R[i++]=n.y,R[i++]=n.z):(R[i++]=2,R[i++]=s,R[i++]=n.x,R[i++]=n.y);if(i>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<i)&&(r.cachedBuffer_=new Float32Array(i)),r.cachedBuffer_.set(R.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void s.draw_mesh(e,r.shader,0);s.HEAPF32.set(r.cachedBuffer_.subarray(0,i),0),s.draw_meshWithUniforms(e,r.shader,0,0,i)}catch(n){_(n,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},H={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},I=new Set;function V(e){const t=H[e];return void 0!==t?t:(I.has(e)||(I.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(H).join(", ")}`)),-1)}const $=new Map;const L=h({enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1},"PhysicsDebugDraw"),O={r:.2,g:.4,b:1,a:.7},W={r:.2,g:1,b:.2,a:.7},j={r:.2,g:1,b:1,a:.7},G={r:1,g:1,b:.2,a:.5},k={r:1,g:.2,b:.2,a:.8},N={r:1,g:.2,b:.2,a:1},q=1.5,X=16;function Y(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function K(e){switch(e){case S.Static:return O;case S.Kinematic:return j;default:return W}}function J(e,t,n,s,r,i){const o=Math.cos(r),a=Math.sin(r),l=[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}].map(n=>({x:e+n.x*o-n.y*a,y:t+n.x*a+n.y*o}));for(let e=0;e<4;e++)F.line(l[e],l[(e+1)%4],i,q)}function Q(e,t,n,s,r,i){const o=Math.cos(r),a=Math.sin(r),l=(n,s)=>({x:e+n*o-s*a,y:t+n*a+s*o}),c=l(-n,s),u=l(n,s),y=l(-n,-s),d=l(n,-s);F.line(c,y,i,q),F.line(u,d,i,q);for(let e=0;e<X;e++){const t=e/X*Math.PI,r=(e+1)/X*Math.PI,o=l(-n*Math.cos(t),s+n*Math.sin(t)),a=l(-n*Math.cos(r),s+n*Math.sin(r));F.line(o,a,i,q)}for(let e=0;e<X;e++){const t=Math.PI+e/X*Math.PI,r=Math.PI+(e+1)/X*Math.PI,o=l(-n*Math.cos(t),-s+n*Math.sin(t)),a=l(-n*Math.cos(r),-s+n*Math.sin(r));F.line(o,a,i,q)}}function Z(e,t,n,s){const r=e+.5*n,i=t+.5*s;F.line({x:e,y:t},{x:r,y:i},k,q);const o=Math.sqrt(n*n+s*s);if(o<1)return;const a=Math.PI/6,l=n/o,c=s/o,u=r-6*(l*Math.cos(a)-c*Math.sin(a)),y=i-6*(l*Math.sin(a)+c*Math.cos(a)),d=r-6*(l*Math.cos(a)+c*Math.sin(a)),p=i-6*(-l*Math.sin(a)+c*Math.cos(a));F.line({x:r,y:i},{x:u,y:y},k,q),F.line({x:r,y:i},{x:d,y:p},k,q)}function ee(e,t,n){const s=e.getResource(L);if(!s||!s.enabled)return;const r=function(e){const t=e.world.getEntitiesWithComponents([u]);for(const n of t){const t=e.world.get(n,u);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=e.world.getEntitiesWithComponents([w,c]);let o=null;s.showVelocity&&e.hasResource(t)&&(o=e.getResource(t));for(const t of i){const n=e.world.get(t,w);if(!n.enabled)continue;const i=e.world.get(t,c),a=i.worldPosition.x,l=i.worldPosition.y,u=Y(i.worldRotation);if(s.showColliders){if(e.world.has(t,M)){const s=e.world.get(t,M),i=s.isSensor?G:K(n.bodyType),o=s.offset.x*r,c=s.offset.y*r,y=Math.cos(u),d=Math.sin(u);J(a+o*y-c*d,l+o*d+c*y,s.halfExtents.x*r,s.halfExtents.y*r,u,i)}if(e.world.has(t,E)){const s=e.world.get(t,E),i=s.isSensor?G:K(n.bodyType),o=s.offset.x*r,c=s.offset.y*r,y=Math.cos(u),d=Math.sin(u),p=a+o*y-c*d,h=l+o*d+c*y;F.circleOutline({x:p,y:h},s.radius*r,i,q,32)}if(e.world.has(t,P)){const s=e.world.get(t,P),i=s.isSensor?G:K(n.bodyType),o=s.offset.x*r,c=s.offset.y*r,y=Math.cos(u),d=Math.sin(u);Q(a+o*y-c*d,l+o*d+c*y,s.radius*r,s.halfHeight*r,u,i)}}if(s.showVelocity&&o&&n.bodyType===S.Dynamic){const e=o.getLinearVelocity(t);Z(a,l,e.x*r,e.y*r)}}if(s.showContacts&&e.hasResource(n)){const t=e.getResource(n);for(const e of t.collisionEnters)F.circle({x:e.contactX,y:e.contactY},3,N,!0,32)}}function te(e,t,n){var s,r;e.insertResource(L,{enabled:!1,showColliders:!0,showVelocity:!1,showContacts:!1}),s="physics-debug-draw",r=()=>{ee(e,t,n)},$.set(s,{fn:r,scene:""})}const ne=h({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),se=h(null,"PhysicsAPI");function re(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function ie(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class oe{constructor(e,t={},n){this.wasmUrl_=e,this.factory_=n,this.config_={gravity:t.gravity??{x:0,y:-9.81},fixedTimestep:t.fixedTimestep??1/60,subStepCount:t.subStepCount??4}}build(e){e.insertResource(ne,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,n=new Map,s=b(this.wasmUrl_,this.factory_).then(s=>{s._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([u]);for(const n of t){const t=e.world.get(n,u);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;var a;o.onDespawn(e=>{t.has(e)&&(s._physics_destroyBody(e),t.delete(e),n.delete(e))}),e.addSystemToSchedule(m.PostUpdate,function(e,t,n){const s=++g;return{_id:Symbol(`System_${s}_${n?.name}`),_params:e,_fn:t,_name:n?.name??`System_${s}`}}([(a=f,{_type:"res",_resource:a})],a=>{const l=o.getEntitiesWithComponents([w,c]),u=new Set;for(const r of l){u.add(r);const a=o.get(r,w),l=o.get(r,c);if(t.has(r)){const e=n.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(s._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=re(l.worldRotation);s._physics_createBody(r,a.bodyType,l.worldPosition.x*i,l.worldPosition.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),ae(e,s,r),t.add(r),n.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===S.Kinematic){const e=re(l.worldRotation);s._physics_setBodyTransform(r,l.worldPosition.x*i,l.worldPosition.y*i,e)}}for(const e of t)u.has(e)||(s._physics_destroyBody(e),t.delete(e),n.delete(e));s._physics_step(a.delta),function(e,t,n){const s=t._physics_getDynamicBodyCount();if(0===s)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<s;r++){const s=i+4*r,o=t.HEAPU32[s],a=t.HEAPF32[s+1]*n,l=t.HEAPF32[s+2]*n,u=t.HEAPF32[s+3];if(!e.world.valid(o))continue;const d=e.world.get(o,c);if(!d)continue;let p=a,h=l,f=u;if(e.world.has(o,y)){const t=e.world.get(o,y);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,c)){const n=e.world.get(t.entity,c),s=re(n.worldRotation),r=a-n.worldPosition.x,i=l-n.worldPosition.y,o=Math.cos(-s),y=Math.sin(-s);p=(r*o-i*y)/(0!==n.worldScale.x?n.worldScale.x:1),h=(r*y+i*o)/(0!==n.worldScale.y?n.worldScale.y:1),f=u-s}}d.position.x=p,d.position.y=h;const _=ie(f);d.rotation.w=_.w,d.rotation.x=_.x,d.rotation.y=_.y,d.rotation.z=_.z,e.world.insert(o,c,d)}}(e,s,r),function(e,t,n){t._physics_collectEvents();const s=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;s.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*n,contactY:t.HEAPF32[r+5]*n})}}const i=[],o=t._physics_getCollisionExitCount();if(o>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let n=0;n<o;n++){const s=e+2*n;i.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(ne,{collisionEnters:s,collisionExits:i,sensorEnters:a,sensorExits:c})}(e,s,r)},{name:"PhysicsSystem"})),e.physicsModule=s,e.insertResource(se,le._fromModule(s)),te(e,se,ne),e.setFixedTimestep(this.config_.fixedTimestep)});s.catch(e=>{console.error("[ESEngine] Physics initialization failed:",e)}),e.physicsInitPromise=s}}function ae(e,t,n){const s=e.world;if(s.has(n,M)){const e=s.get(n,M);return void t._physics_addBoxShape(n,e.halfExtents.x,e.halfExtents.y,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,E)){const e=s.get(n,E);return void t._physics_addCircleShape(n,e.radius,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}if(s.has(n,P)){const e=s.get(n,P);t._physics_addCapsuleShape(n,e.radius,e.halfHeight,e.offset.x,e.offset.y,e.density,e.friction,e.restitution,e.isSensor?1:0)}}class le{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(le.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(L);n&&(n.enabled=t,e.insertResource(L,n))}static setDebugDrawConfig(e,t){const n=e.getResource(L);n&&e.insertResource(L,{...n,...t})}}export{S as BodyType,M as BoxCollider,P as CapsuleCollider,E as CircleCollider,le as Physics,se as PhysicsAPI,L as PhysicsDebugDraw,ne as PhysicsEvents,oe as PhysicsPlugin,w as RigidBody,ee as drawPhysicsDebug,b as loadPhysicsModule,x as loadPhysicsSideModule,te as setupPhysicsDebugDraw};
+export{d as Physics,k as PhysicsAPI,m as PhysicsDebugDraw,e as PhysicsEvents,P as PhysicsPlugin,n as drawPhysicsDebug,l as loadPhysicsModule,o as loadPhysicsSideModule,p as setupPhysicsDebugDraw}from"../shared/index.js";export{B as BodyType,f as BoxCollider,_ as CapsuleCollider,C as CircleCollider,e as RigidBody}from"../shared/material.js";
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/shared/SpineModuleLoader.js b/desktop/public/sdk/esm/shared/SpineModuleLoader.js
new file mode 100644
index 000000000..86efebdfb
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/SpineModuleLoader.js
@@ -0,0 +1,2 @@
+import{R as e,M as t,b as s,c as a,T as n,e as i,B as r,C as o,f as l,N as c,g as h,I as d,h as u,d as f}from"./material.js";let p=null;function m(e){p=e}function g(){if(!p)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return p}function _(){return null!==p}function y(){return p?.name??null}function b(){return"wechat"===p?.name}function w(){return"web"===p?.name}async function x(e,t){return g().fetch(e,t)}async function T(e){return g().readFile(e)}async function A(e){return g().readTextFile(e)}async function v(e){return g().fileExists(e)}async function C(e,t){return g().instantiateWasm(e,t)}function P(e,t){return g().createCanvas(e,t)}function S(){return g().now()}function I(){if("wechat"===p?.name){const e=globalThis;return e.wx?.getSystemInfoSync?.()?.pixelRatio??1}return"undefined"!=typeof window&&window.devicePixelRatio||1}class M{constructor(){this.cache_=new Map,this.pending_=new Map,this.failed_=new Map}async getOrLoad(t,s,a=e.assetLoadTimeout){const n=this.cache_.get(t);if(void 0!==n)return n;const i=this.failed_.get(t);if(i&&Date.now()<i.expiry)throw i.error;this.failed_.delete(t);const r=this.pending_.get(t);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const e=s(),n=await(a>0?Promise.race([e,new Promise((e,s)=>setTimeout(()=>{o.aborted=!0,s(new Error(`AsyncCache timeout: ${t} (${a}ms)`))},a))]):e);return o.aborted||this.cache_.set(t,n),this.pending_.delete(t),n})(),this.pending_.set(t,o);try{return await o.promise}catch(s){throw this.pending_.delete(t),s instanceof Error&&(this.failed_.set(t,{error:s,expiry:Date.now()+e.assetFailureCooldown}),s.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${s.message}`)),s}}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 F{constructor(e,t=""){this.cache_=new M,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 s=this.cache_.get(e);s&&(t.release(s.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())t.release(e.handle);this.cache_.clear()}async loadInternal(e){const s=this.resolvePath(e);if(!await v(s))throw new Error(`Material file not found: ${s}`);const a=await A(s);if(!a)throw new Error(`Failed to read material file: ${s}`);const n=JSON.parse(a);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const i=this.resolveShaderPath(e,n.shader),r=await this.shaderLoader_.load(i);return{handle:t.createFromAsset(n,r),shaderHandle:r,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}function E(e){const t=new Set;for(const s of e.frames)s.texture&&t.add(s.texture);return Array.from(t)}function $(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 L=new Map;function k(e){L.set(e.name,e)}function R(e){L.delete(e)}function U(e){return L.get(e)}function B(){L.clear()}const W=s("SpriteAnimator",{clip:"",speed:1,playing:!0,loop:!0,enabled:!0,currentFrame:0,frameTimer:0});function j(e,t){const s=e.getEntitiesWithComponents([W]);for(const n of s){const s=e.get(n,W);if(!s.enabled||!s.playing||!s.clip)continue;const i=L.get(s.clip);if(!i||0===i.frames.length)continue;const r=1/(i.fps*s.speed),o=0===s.frameTimer&&0===s.currentFrame;s.frameTimer+=t;let l=o;if(s.frameTimer>=r&&(s.frameTimer-=r,s.currentFrame++,s.currentFrame>=i.frames.length&&(s.loop&&i.loop?s.currentFrame=0:(s.currentFrame=i.frames.length-1,s.playing=!1)),l=!0),l&&e.has(n,a)){const t=i.frames[s.currentFrame],r=e.get(n,a);r.texture=t.texture,t.uvOffset&&(r.uvOffset=t.uvOffset,r.uvScale=t.uvScale),e.insert(n,a,r)}l&&e.insert(n,W,s)}}class O{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},a=this.bufferCache_.get(e);if(!a){const t=this.createDeferredHandle();return this.preload(e).then(()=>{if(this.disposed_)return;const a=this.bufferCache_.get(e);a&&t.resolve(this.backend_.play(a,s))}).catch(t=>{console.warn(`Failed to preload audio: ${e}`,t)}),t}return this.backend_.play(a,s)}static playBGM(e,t){const s=e=>{this.fadeAnimId_&&(cancelAnimationFrame(this.fadeAnimId_),this.fadeAnimId_=0);const s=t?.volume??1,a=this.bgmVolume_;this.bgmVolume_=s,this.bgmHandle_&&t?.crossFade?this.fadeOut(this.bgmHandle_,t.crossFade,a):this.bgmHandle_&&this.bgmHandle_.stop();const n=t?.fadeIn??t?.crossFade;this.bgmHandle_=this.backend_.play(e,{bus:"music",volume:n?0:s,loop:!0}),n&&this.fadeIn(this.bgmHandle_,n,s)},a=this.bufferCache_.get(e);a?s(a):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 a=performance.now(),n=()=>{const i=(performance.now()-a)/1e3,r=Math.min(i/t,1);e.setVolume(r*s),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(n):this.fadeAnimId_=0};this.fadeAnimId_=requestAnimationFrame(n)}static fadeOut(e,t,s){const a=performance.now(),n=()=>{const i=(performance.now()-a)/1e3,r=Math.min(i/t,1);e.setVolume(s*(1-r)),r<1&&e.isPlaying?this.fadeAnimId_=requestAnimationFrame(n):(e.stop(),this.fadeAnimId_=0)};this.fadeAnimId_=requestAnimationFrame(n)}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}}}}O.mixer_=null,O.bufferCache_=new Map,O.bgmHandle_=null,O.bgmVolume_=1,O.fadeAnimId_=0,O.disposed_=!1;const H=new Map,D=new Map;function G(e,t,s){H.set(e,{width:t,height:s})}function V(e){return H.get(e)}function N(){H.clear()}function X(e,t){D.set(e,t)}function J(e){return D.get(e)}function K(){D.clear()}let z=null;function Y(e){z=e}function q(){z=null}const Q={initLayer(e,t,s,a,n){z?.tilemap_initLayer(e,t,s,a,n)},destroyLayer(e){z?.tilemap_destroyLayer(e)},setTile(e,t,s,a){z?.tilemap_setTile(e,t,s,a)},getTile:(e,t,s)=>z?z.tilemap_getTile(e,t,s):0,fillRect(e,t,s,a,n,i){z?.tilemap_fillRect(e,t,s,a,n,i)},setTiles(e,t){if(!z)return;const s=t.byteLength,a=z._malloc(s);new Uint16Array(z.HEAPU8.buffer,a,t.length).set(t),z.tilemap_setTiles(e,a,t.length),z._free(a)},hasLayer:e=>!!z&&z.tilemap_hasLayer(e),submitLayer(e,t,s,a,n,i,r,o,l,c,h,d,u,f,p,m,g,_,y,b){z?.tilemap_submitLayer(e,t,s,a,n,i,r,o,l,c,h,d,u,f,p,m,g,_,y,b)}},Z=s("Tilemap",{source:""}),ee=s("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 te(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 se(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 ae(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 ne(e){const t=e.width,s=e.height,a=e.tilewidth??0,n=e.tileheight??0;if(!(t&&s&&a&&n))return null;const i=e.tilesets,r=[],o=[];if(i)for(const e of i){const t=e.firstgid??1;o.push(t),r.push({name:e.name??"",image:e.image??"",tileWidth:e.tilewidth??a,tileHeight:e.tileheight??n,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 a=e.width??t,n=e.height??s,i=!1!==e.visible,r=e.data,l=new Uint16Array(a*n);if(r){const e=o[0]??1;for(let t=0;t<r.length&&t<l.length;t++)l[t]=ae(r[t],e)}const h="number"==typeof e.opacity?e.opacity:1,d=se(e.tintcolor),u="number"==typeof e.parallaxx?e.parallaxx:1,f="number"==typeof e.parallaxy?e.parallaxy:1;c.push({name:e.name??"",width:a,height:n,visible:i,tiles:l,opacity:h,tintColor:d,parallaxX:u,parallaxY:f})}const h=[],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,a=e.properties;if(a)for(const e of a)t.set(e.name,e.value);let n="rect",i=null;if(e.ellipse)n="ellipse";else if(e.point)n="point";else if(e.polygon){n="polygon";const t=e.polygon;i=[];for(const e of t)i.push(e.x,e.y)}else if(e.polyline){n="polygon";const t=e.polyline;i=[];for(const e of t)i.push(e.x,e.y)}s.push({shape:n,x:e.x??0,y:e.y??0,width:e.width??0,height:e.height??0,rotation:e.rotation??0,vertices:i,properties:t})}h.push({name:e.name??"",objects:s})}if(i)for(const e of i){const t=e.firstgid??1,s=e.tiles;if(s)for(const e of s){const s=e.properties;if(s)for(const a of s)"collision"===a.name&&!0===a.value&&d.push(e.id+t)}}return{width:t,height:s,tileWidth:a,tileHeight:n,layers:c,tilesets:r,objectGroups:h,collisionTileIds:d}}function ie(e,t){const s=e.lastIndexOf("/"),a=((s>=0?e.substring(0,s+1):"")+t).split("/"),n=[];for(const e of a)".."===e?n.pop():"."!==e&&""!==e&&n.push(e);return n.join("/")}async function re(e,t){const s=z;if(!s)return null;const a=new TextEncoder,n=a.encode(e),i=s._malloc(n.byteLength);s.HEAPU8.set(n,i);const r=s.tiled_loadMap(i,n.byteLength);if(s._free(i),0===r)return null;try{const e=s.tiled_getExternalTilesetCount(r);for(let n=0;n<e;n++){const e=s.tiled_getExternalTilesetSource(r,n);if(!t)return s.tiled_freeMap(r),null;const i=await t(e),o=a.encode(i),l=s._malloc(o.byteLength);s.HEAPU8.set(o,l);const c=s.tiled_loadExternalTileset(r,n,l,o.byteLength);if(s._free(l),!c)return s.tiled_freeMap(r),null}if(!s.tiled_finalize(r))return s.tiled_freeMap(r),null;const n={width:s.tiled_getMapWidth(r),height:s.tiled_getMapHeight(r),tileWidth:s.tiled_getMapTileWidth(r),tileHeight:s.tiled_getMapTileHeight(r),layers:[],tilesets:[],objectGroups:[],collisionTileIds:[]},i=s.tiled_getLayerCount(r);for(let e=0;e<i;e++){const t=s.tiled_getLayerWidth(r,e),a=s.tiled_getLayerHeight(r,e),i=t*a,o=2*i,l=s._malloc(o);s.tiled_getLayerTiles(r,e,l,i);const c=new Uint16Array(i);c.set(new Uint16Array(s.HEAPU8.buffer,l,i)),s._free(l),n.layers.push({name:s.tiled_getLayerName(r,e),width:t,height:a,visible:s.tiled_getLayerVisible(r,e),tiles:c,opacity:s.tiled_getLayerOpacity(r,e),tintColor:s.tiled_getLayerTintColor?te(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 o=s.tiled_getTilesetCount(r);for(let e=0;e<o;e++)n.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),n}catch{return s.tiled_freeMap(r),null}}const oe=Math.PI/180;function le(e,t,s,a,o,c){const h=function(e,t,s,a){const n=new Uint8Array(t*s),i=[],r=(i,r)=>{if(i>=t||r>=s)return!1;const o=r*t+i;if(n[o])return!1;const l=8191&e[o];return 0!==l&&a.has(l)};for(let e=0;e<s;e++)for(let a=0;a<t;a++){if(!r(a,e))continue;let o=1;for(;r(a+o,e);)o++;let l=1,c=!0;for(;c;){const t=e+l;if(t>=s)break;for(let e=0;e<o;e++)if(!r(a+e,t)){c=!1;break}c&&l++}for(let s=0;s<l;s++)for(let i=0;i<o;i++)n[(e+s)*t+(a+i)]=1;i.push({col:a,row:e,width:o,height:l})}return i}(t.tiles,t.width,t.height,a),d=[],u=s.tileWidth,f=s.tileHeight,p=s.height*f;for(const t of h){const s=t.width*u,a=t.height*f,h=o+t.col*u+.5*s,m=c+(p-t.row*f)-.5*a,g=e.spawn();e.insert(g,n,{position:{x:h,y:m,z:0}}),e.insert(g,i,{bodyType:r.Static}),e.insert(g,l,{halfExtents:{x:.5*s,y:.5*a}}),d.push(g)}return d}function ce(e,t,s,a={}){const c=[],h=t.tilesets[0];let d=0;for(const a of t.layers){if(!a.visible)continue;const i=e.spawn();e.insert(i,n,{});const r=h?s.get(h.image)??0:0,o=h?.columns??1;e.insert(i,ee,{width:a.width,height:a.height,tileWidth:t.tileWidth,tileHeight:t.tileHeight,texture:r,tilesetColumns:o,layer:d,tiles:Array.from(a.tiles),tint:{...a.tintColor},opacity:a.opacity,visible:a.visible,parallaxFactor:{x:a.parallaxX,y:a.parallaxY}}),c.push(i),d++}if(!1!==a.generateObjectCollision&&t.objectGroups.length>0){const s=function(e,t,s,a){const c=[],h=t.height*t.tileHeight;for(const d of t.objectGroups)for(const t of d.objects){if("point"===t.shape)continue;const d=e.spawn(),u=t.x,f=t.y,p=s+u+.5*t.width,m=a+(h-f)-.5*t.height,g=-t.rotation*oe;if(e.insert(d,n,{position:{x:p,y:m,z:0}}),e.insert(d,i,{bodyType:r.Static}),"ellipse"===t.shape){const s=.5*Math.max(t.width,t.height);e.insert(d,o,{radius:s})}else if("polygon"===t.shape&&t.vertices){let s=1/0,a=1/0,n=-1/0,i=-1/0;for(let e=0;e<t.vertices.length;e+=2){const r=t.vertices[e],o=t.vertices[e+1];r<s&&(s=r),r>n&&(n=r),o<a&&(a=o),o>i&&(i=o)}const r=n-s,o=i-a,c=.5*(s+n),h=.5*(a+i);e.insert(d,l,{halfExtents:{x:.5*r,y:.5*o},offset:{x:c,y:-h}})}else e.insert(d,l,{halfExtents:{x:.5*t.width,y:.5*t.height}});if(0!==g){const t=.5*g;e.insert(d,n,{position:{x:p,y:m,z:0},rotation:{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}})}c.push(d)}return c}(e,t,0,0);c.push(...s)}const u=new Set(a.collisionTileIds??t.collisionTileIds);if(u.size>0)for(const s of t.layers){if(!s.visible)continue;const a=le(e,s,t,u,0,0);c.push(...a)}return c}const he=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 de(e,t){he.set(e,t)}function ue(e){const t=he.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 fe(e){return he.get(e)?.fields??[]}function pe(e){return he.get(e)?.spine??null}const me=new Map([["Slider",["fillEntity","handleEntity"]],["ProgressBar",["fillEntity"]],["Toggle",["graphicEntity","group"]],["ScrollView",["contentEntity"]],["Dropdown",["listEntity","labelEntity"]]]);function ge(e,t){me.set(e,t)}function _e(e){return me.get(e)}function ye(e,t){const s=me.get(e.type);if(!s)return;const a=e.data;for(const n of s){const s=a[n];if("number"==typeof s&&s!==d){const i=t.get(s);void 0===i&&console.warn(`[Scene] Entity reference not found: ${e.type}.${n} references entity ${s} which does not exist`),a[n]=void 0!==i?i:d}}}function be(e,t){const s=new Map;for(const a of t.entities){if(!1===a.visible)continue;const t=e.spawn();s.set(a.id,t),e.insert(t,c,{value:a.name})}for(const a of t.entities){if(!1===a.visible)continue;const t=s.get(a.id);for(const n of a.components)ye(n,s),Ae(e,t,n,a.name)}for(const a of t.entities)if(null!==a.parent){const t=s.get(a.id),n=s.get(a.parent);void 0!==t&&void 0!==n&&e.setParent(t,n)}return s}function we(e,t){return be(e,t)}async function xe(e,t,s){const a=s?.assetServer,n=s?.assetBaseUrl??a?.baseUrl,i=new Map;a&&await async function(e,t,s,a,n){const i=new Map;for(const e of Te.keys())i.set(e,new Set);const r=[],o=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=he.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],a=s[t.spine.atlasField];if(e&&a){const t=`${e}:${a}`;o.has(t)||(o.add(t),r.push({skeleton:e,atlas:a}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];"string"==typeof t&&t&&i.get(e.type)?.add(t)}}const l=new Map,c=[...Te.entries()].map(async([e,n])=>{const r=await n.load(i.get(e),t,s,a);l.set(e,r)}),h=r.map(async e=>{const a=await t.loadSpine(e.skeleton,e.atlas,s);a.success||console.warn(`Failed to load Spine: ${a.error}`)});if(await Promise.all([...c,...h]),n){for(const e of a.values())n.textureUrls.add(e);const e=l.get("material");if(e)for(const t of e.values())t>0&&n.materialHandles.add(t);const t=i.get("font");if(t)for(const e of t)n.fontPaths.add(e);for(const e of o)n.spineKeys.add(e)}for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=he.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 a=s[e.field];if("string"!=typeof a||!a)continue;const n=t.get(a);void 0!==n&&(s[e.field]=n)}}}(t,a,n,i,s?.collectAssets);const r=be(e,t);if(a&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&a.setTextureMetadataByPath(t,s.sliceBorder)}return r}const Te=new Map([["texture",{async load(e,t,s,a){const n=new Map,i=[...e].map(async e=>{try{const i=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,r=await t.loadTexture(i);n.set(e,r.handle),a.set(e,i),G(r.handle,r.width,r.height)}catch(t){console.warn(`Failed to load texture: ${e}`,t),n.set(e,0)}});return await Promise.all(i),n}}],["material",{async load(e,t,s){const a=new Map,n=[...e].map(async e=>{try{const n=await t.loadMaterial(e,s);a.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),a.set(e,0)}});return await Promise.all(n),a}}],["font",{async load(e,t,s){const a=new Map,n=[...e].map(async e=>{try{const n=await t.loadBitmapFont(e,s);a.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),a.set(e,0)}});return await Promise.all(n),a}}],["anim-clip",{async load(e,t,s,a){const n=[...e].map(async e=>{try{const n=await t.loadJson(e),i=E(n),r=new Map,o=i.map(async e=>{try{const n=s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(n);r.set(e,i.handle),a.set(e,n)}catch(t){console.warn(`Failed to load anim texture: ${e}`,t),r.set(e,0)}});await Promise.all(o);k($(e,n,r))}catch(t){console.warn(`Failed to load animation clip: ${e}`,t)}});return await Promise.all(n),new Map}}],["audio",{async load(e,t,s){const a=[...e].map(e=>s?`${s}/${e}`:`/${e}`);return await O.preloadAll(a).catch(e=>{console.warn("Failed to preload audio assets:",e)}),new Map}}],["tilemap",{async load(e,t,s,a){const n=[...e].map(async e=>{try{const n=ne(await t.loadJson(e));if(!n)return void console.warn(`Failed to parse tilemap: ${e}`);const i=[];for(const r of n.tilesets){const n=ie(e,r.image);let o=0;try{const e=s?`${s}/${n}`:`/${n}`,i=await t.loadTexture(e);o=i.handle,a.set(n,e),G(i.handle,i.width,i.height)}catch(e){console.warn(`Failed to load tileset texture: ${n}`,e)}i.push({textureHandle:o,columns:r.columns})}X(e,{tileWidth:n.tileWidth,tileHeight:n.tileHeight,layers:n.layers.map(e=>({name:e.name,width:e.width,height:e.height,tiles:e.tiles})),tilesets:i})}catch(t){console.warn(`Failed to load tilemap: ${e}`,t)}});return await Promise.all(n),new Map}}]]);function Ae(e,t,s,a){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 n=h(s.type);if(n)e.insert(t,n,s.data);else{const e=a?` on entity "${a}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function ve(e,t){const s=e.getEntitiesWithComponents([u]);for(const a of s){const s=e.get(a,u);s&&(s.aspectRatio=t,e.insert(a,u,s))}}function Ce(e,t){const s=e.getEntitiesWithComponents([c]);for(const a of s){const s=e.get(a,c);if(s&&s.value===t)return a}return null}const Pe=[{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}],Se={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"},Ie=new Map,Me=new Set;for(const e of Pe)for(const t of e.extensions)Ie.set(t,e),Me.add(t);function Fe(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Ee(e){return Ie.get(Fe(e))}function $e(e){return Ee(e)?.editorType??"unknown"}function Le(e){return Ee(e)?.addressableType??null}function ke(e){for(const t of Pe)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Re(e){return Me.has(e.toLowerCase())}function Ue(){return Me}function Be(e){return"string"==typeof e&&(!!e.includes("/")&&Re(Fe(e)))}function We(){const e=[];for(const t of Pe)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function je(){return We().map(e=>({type:"suffix",value:e}))}function Oe(e){return Se[e.toLowerCase()]}function He(e){const t=Ee(e);return t?.wechatPackInclude??!1}function De(e){const t=Ee(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}function Ge(e,t){for(const s of Pe)s.editorType===e&&(s.buildTransform=t)}function Ve(e){return Ee(e)?.buildTransform}class Ne{constructor(t){this.textureCache_=new M,this.shaderCache_=new M,this.jsonCache_=new M,this.textCache_=new M,this.binaryCache_=new M,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new M,this.prefabCache_=new M,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_=t,this.canvas_=P(e.textCanvasSize,e.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const s={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new F(s)}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 a=this.textureCacheKey(e,s),n=this.textureCache_.get(a);if(!n)continue;const i=(this.textureRefCounts_.get(a)??1)-1;i<=0?(t.releaseTexture(n.handle),this.textureCache_.delete(a),this.textureRefCounts_.delete(a)):this.textureRefCounts_.set(a,i)}}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(),t.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 a=`${e}:${t}`;if(this.loadedSpines_.has(a))return{success:!0};try{const n=this.resolveUrl(t,s),i=await this.fetchText(n);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const r=t.substring(0,t.lastIndexOf("/")),o=this.parseAtlasTextures(i),l=[];for(const e of o){const t=r?`${r}/${e}`:e,a=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(a);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),h="binary"===Ee(e)?.contentType,d=h?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(a),this.spineController_){const e=this.spineController_.loadSkeleton(d,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let a=0;a<s;a++){const s=this.spineController_.getAtlasPageTextureName(e,a),n=l.find(e=>e.name===s);if(n){const s=t.getTextureGLId(n.info.handle);this.spineController_.setAtlasPageTexture(e,a,s,n.info.width,n.info.height)}}this.spineSkeletons_.set(a,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=Ee(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("/")),a="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!a)throw new Error("Invalid bmfont asset: no fnt file specified");const n=s?`${s}/${a}`:a;return this.loadFntFile(n)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const a=s[1],n=e.substring(0,e.lastIndexOf("/")),i=n?`${n}/${a}`:a,r=await this.loadTextureRaw(i);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 ue(e.type)){const a=e.data[s];if("string"==typeof a&&a){const n=t(a);n&&(e.data[s]=n)}}const s=pe(e.type);if(s)for(const a of[s.skeletonField,s.atlasField]){const s=e.data[a];if("string"==typeof s&&s){const n=t(s);n&&(e.data[a]=n)}}}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 xe(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 a of e){const e=a.address??a.path;switch(a.type){case"texture":s.push(this.loadTexture(a.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(a.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const n=a.metadata?.atlas;n&&s.push(this.loadSpine(a.path,n).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(a.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(a.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(a.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(a.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(a.path).then(s=>{t.text.set(e,s)}))}}const a=await Promise.allSettled(s);for(const e of a)"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),a=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),a}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 a=this.baseUrl?`${this.baseUrl}/${t}`:t;return this.loadImageFromSrc(a)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return this.loadImageFromSrc(e)}loadImageFromSrc(e){return new Promise((t,s)=>{const a=g().createImage();a.crossOrigin="anonymous",a.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(a,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void t(e)}catch{}t(a)},a.onerror=()=>s(new Error(`Failed to load image: ${e}`)),a.src=e})}createTextureFromImage(e,t){const{width:s,height:a}=e,n=this.getWebGL2Context();return n?this.createTextureWebGL2(n,e,s,a,t):this.createTextureFallback(e,s,a,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,a,n){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,n?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const r=this.module_.GL,o=r.getNewId(r.textures);r.textures[o]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(o,s,a),width:s,height:a}}createTextureFallback(e,t,s,a){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const n=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(n.data.buffer);this.unpremultiplyAlpha(i);const r=this.module_.getResourceManager(),o=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,o);const l=r.createTexture(t,s,o,i.length,1,a);return this.module_._free(o),{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 a=255/s;e[t]=Math.min(255,Math.round(e[t]*a)),e[t+1]=Math.min(255,Math.round(e[t+1]*a)),e[t+2]=Math.min(255,Math.round(e[t+2]*a))}}}async loadShaderInternal(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,a=this.getEmbedded(s);if(a){const s=this.decodeDataUrlText(a),{vertex:n,fragment:i}=this.parseEsShader(s);if(!n||!i)throw new Error(`Invalid shader format: ${e}`);return t.createShader(n,i)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await v(s))throw new Error(`Shader file not found: ${e}`);const n=await A(s);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:i,fragment:r}=this.parseEsShader(n);if(!i||!r)throw new Error(`Invalid shader format: ${e}`);return t.createShader(i,r)}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(De(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 a=await A(t);return JSON.parse(a)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await x(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 A(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await x(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 T(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await x(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 a=s.split("/").filter(e=>e);let n="";for(const e of a){n=n?`${n}/${e}`:e;try{t.analyzePath(n).exists||t.mkdir(n)}catch{try{t.mkdir(n)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Xe=f(null,"Assets");class Je{build(e){const t=e.wasmModule;t?e.insertResource(Xe,new Ne(t)):console.warn("AssetPlugin: No WASM module available")}}const Ke=new Je;function ze(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"])}}async function Ye(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const s=await t();return{raw:s,api:ze(s)}}export{je as $,Xe as A,Q as B,Z as C,J as D,N as E,Y as F,q as G,m as H,Je as I,Ne as J,M as K,B as L,F as M,K as N,Ce as O,Le as P,ke as Q,Ue as R,W as S,ee as T,U,Ve as V,Oe as W,ue as X,We as Y,$e as Z,y as _,xe as a,He as a0,Re as a1,_ as a2,w as a3,Ae as a4,ce as a5,Be as a6,re as a7,v as a8,C as a9,T as aa,A as ab,Ge as ac,de as ad,ge as ae,ye as af,De as ag,R as ah,_e as b,Ke as c,I as d,P as e,we as f,g,fe as h,b as i,pe as j,Ee as k,Ye as l,E as m,$ as n,ne as o,S as p,ie as q,k as r,G as s,X as t,ve as u,O as v,ze as w,x,j as y,V as z};
+//# sourceMappingURL=SpineModuleLoader.js.map
diff --git a/desktop/public/sdk/esm/shared/SpineModuleLoader.js.map b/desktop/public/sdk/esm/shared/SpineModuleLoader.js.map
new file mode 100644
index 000000000..11bc3b0c1
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/SpineModuleLoader.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"SpineModuleLoader.js","sources":["../../src/platform/base.ts","../../src/asset/AsyncCache.ts","../../src/asset/MaterialLoader.ts","../../src/animation/AnimClipLoader.ts","../../src/animation/SpriteAnimator.ts","../../src/audio/Audio.ts","../../src/tilemap/tilesetCache.ts","../../src/tilemap/tilemapAPI.ts","../../src/tilemap/components.ts","../../src/tilemap/tiledLoader.ts","../../src/tilemap/collisionMerge.ts","../../src/scene.ts","../../src/assetTypes.ts","../../src/asset/AssetServer.ts","../../src/asset/AssetPlugin.ts","../../src/spine/SpineModuleLoader.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["currentPlatform","setPlatform","adapter","getPlatform","Error","isPlatformInitialized","getPlatformType","name","isWeChat","isWeb","async","platformFetch","url","options","fetch","platformReadFile","path","readFile","platformReadTextFile","readTextFile","platformFileExists","fileExists","platformInstantiateWasm","pathOrBuffer","imports","instantiateWasm","platformCreateCanvas","width","height","createCanvas","platformNow","now","platformDevicePixelRatio","g","globalThis","wx","getSystemInfoSync","pixelRatio","window","devicePixelRatio","AsyncCache","constructor","this","cache_","Map","pending_","failed_","getOrLoad","key","loader","timeout","RuntimeConfig","assetLoadTimeout","cached","get","undefined","failed","Date","expiry","error","delete","existing","aborted","promise","entry","loaderPromise","result","Promise","race","_","reject","setTimeout","set","err","assetFailureCooldown","message","startsWith","console","warn","has","clear","clearAll","values","MaterialLoader","shaderLoader","basePath","shaderLoader_","basePath_","load","loadInternal","release","loaded","Material","handle","releaseAll","fullPath","resolvePath","content","data","JSON","parse","type","shaderPath","resolveShaderPath","shader","shaderHandle","createFromAsset","materialPath","dir","substring","lastIndexOf","extractAnimClipTexturePaths","paths","Set","frame","frames","texture","add","Array","from","parseAnimClipData","clipPath","textureHandles","fps","loop","map","f","atlasFrame","af","uvOffset","x","pageWidth","y","pageHeight","uvScale","clipRegistry","registerAnimClip","clip","unregisterAnimClip","getAnimClip","clearAnimClips","SpriteAnimator","defineComponent","speed","playing","enabled","currentFrame","frameTimer","spriteAnimatorSystemUpdate","world","deltaTime","entities","getEntitiesWithComponents","entity","animator","length","frameDuration","needsInitialApply","frameChanged","Sprite","sprite","insert","Audio","init","backend","mixer","backend_","mixer_","bufferCache_","bgmHandle_","bgmVolume_","disposed_","fadeAnimId_","cancelAnimationFrame","preload","buffer","loadBuffer","preloadAll","urls","all","preloadFromData","loadBufferFromData","playSFX","config","playConfig","bus","volume","playbackRate","pitch","pan","priority","pending","createDeferredHandle","then","buf","resolve","play","catch","playBGM","targetVolume","oldVolume","crossFade","fadeOut","stop","fadeInDuration","fadeIn","stopAll","stopBGM","setMasterVolume","master","setMusicVolume","music","setSFXVolume","sfx","setUIVolume","ui","muteBus","busName","muted","getBus","getBufferHandle","dispose","unloadBuffer","duration","setVolume","startTime","performance","tick","elapsed","t","Math","min","isPlaying","requestAnimationFrame","startVolume","real","id","pause","resume","v","setPan","p","setLoop","l","setPlaybackRate","r","currentTime","texDimsCache_","tilemapCache_","registerTextureDimensions","getTextureDimensions","clearTextureDimensionsCache","registerTilemapSource","getTilemapSource","clearTilemapSourceCache","module_","initTilemapAPI","m","shutdownTilemapAPI","TilemapAPI","initLayer","tileWidth","tileHeight","tilemap_initLayer","destroyLayer","tilemap_destroyLayer","setTile","tileId","tilemap_setTile","getTile","tilemap_getTile","fillRect","w","h","tilemap_fillRect","setTiles","tiles","bytes","byteLength","ptr","_malloc","Uint16Array","HEAPU8","tilemap_setTiles","_free","hasLayer","tilemap_hasLayer","submitLayer","textureId","sortLayer","depth","tilesetColumns","uvTileWidth","uvTileHeight","originX","originY","camLeft","camBottom","camRight","camTop","tintR","tintG","tintB","tintA","opacity","parallaxX","parallaxY","tilemap_submitLayer","Tilemap","source","TilemapLayer","layer","tint","b","a","visible","parallaxFactor","parseTintColorU32","val","parseTintColor","hex","s","slice","parseInt","convertGid","gid","firstGid","flags","parseTmjJson","json","tilewidth","tileheight","rawTilesets","tilesets","firstGids","ts","firstgid","push","image","columns","tileCount","tilecount","rawLayers","layers","lw","lh","rawData","i","tintColor","tintcolor","parallaxx","parallaxy","objectGroups","collisionTileIds","objs","objects","parsed","obj","props","rawProps","properties","value","shape","vertices","ellipse","point","polygon","polyPts","pt","polyline","linePts","rotation","rawTiles","tile","tileProps","resolveRelativePath","relativePath","lastSlash","parts","split","resolved","part","pop","join","parseTiledMap","jsonString","resolveExternal","api","encoder","TextEncoder","encoded","encode","tiled_loadMap","extCount","tiled_getExternalTilesetCount","tiled_getExternalTilesetSource","tiled_freeMap","tsjContent","tsjEncoded","tsjPtr","ok","tiled_loadExternalTileset","tiled_finalize","tiled_getMapWidth","tiled_getMapHeight","tiled_getMapTileWidth","tiled_getMapTileHeight","layerCount","tiled_getLayerCount","tiled_getLayerWidth","tiled_getLayerHeight","tileBytes","tilePtr","tiled_getLayerTiles","tiled_getLayerName","tiled_getLayerVisible","tiled_getLayerOpacity","tiled_getLayerTintColor","tiled_getLayerParallaxX","tiled_getLayerParallaxY","tilesetCount","tiled_getTilesetCount","tiled_getTilesetName","tiled_getTilesetImage","tiled_getTilesetTileWidth","tiled_getTilesetTileHeight","tiled_getTilesetColumns","tiled_getTilesetTileCount","DEG_TO_RAD","PI","generateTileCollision","mapData","collisionIds","merged","mapWidth","mapHeight","visited","Uint8Array","results","isCollision","col","row","idx","canExpand","nextRow","dx","dy","mergeCollisionTiles","tileW","tileH","mapPixelH","rect","mergedW","mergedH","worldX","worldY","spawn","Transform","position","z","RigidBody","bodyType","BodyType","Static","BoxCollider","halfExtents","loadTiledMap","firstTileset","layerIndex","textureHandle","generateObjectCollision","collisionEntities","mapOriginX","mapOriginY","group","tiledX","tiledY","angle","radius","max","CircleCollider","minX","Infinity","minY","maxX","maxY","vx","vy","polyW","polyH","polyCX","polyCY","offset","half","cos","sin","loadTiledCollisionObjects","tileCollisionIds","size","tileEntities","COMPONENT_ASSET_FIELDS","fields","field","spine","skeletonField","atlasField","registerComponentAssetFields","componentType","getComponentAssetFields","getComponentAssetFieldDescriptors","getComponentSpineFieldDescriptor","COMPONENT_ENTITY_FIELDS","registerComponentEntityFields","getComponentEntityFields","remapEntityFields","compData","entityMap","editorId","INVALID_ENTITY","runtimeId","spawnAndLoadEntities","sceneData","entityData","Name","components","loadComponent","parent","parentEntity","setParent","loadSceneData","loadSceneWithAssets","assetServer","baseUrl","assetBaseUrl","texturePathToUrl","collectAssets","assetPaths","ASSET_FIELD_HANDLERS","keys","spines","spineKeys","skelPath","atlasPath","skeleton","atlas","desc","assetHandles","loadPromises","entries","handler","handles","spinePromises","loadSpine","success","textureUrls","materialHandles","fontPaths","preloadSceneAssets","textureMetadata","texturePath","metadata","Object","sliceBorder","setTextureMetadataByPath","promises","info","loadTexture","loadMaterial","fontPath","loadBitmapFont","loadJson","texturePaths","texPromises","texPath","_assetServer","tmjPath","imagePath","entityName","rectData","anchor","anchorMin","anchorMax","maskData","mode","comp","getComponent","context","updateCameraAspectRatio","aspectRatio","cameraEntities","Camera","camera","findEntityByName","ASSET_TYPE_REGISTRY","extensions","contentType","editorType","addressableType","wechatPackInclude","hasTransitiveDeps","MIME_MAP","png","jpg","jpeg","gif","webp","svg","bmp","mp3","wav","ogg","aac","flac","webm","skel","esmaterial","esshader","esprefab","esanim","bmfont","fnt","extToEntry","allExtensions","ext","extractExtension","extensionOrPath","dotIndex","toLowerCase","getAssetTypeEntry","getEditorType","getAddressableType","getAddressableTypeByEditorType","isKnownAssetExtension","getAllAssetExtensions","looksLikeAssetPath","includes","getCustomExtensions","getWeChatPackOptions","getAssetMimeType","isCustomExtension","toBuildPath","registerAssetBuildTransform","transform","buildTransform","getAssetBuildTransform","AssetServer","module","textureCache_","shaderCache_","jsonCache_","textCache_","binaryCache_","loadedSpines_","virtualFSPaths_","fontCache_","prefabCache_","embedded_","embeddedOnly_","addressableManifest_","addressIndex_","labelIndex_","groupAssets_","spineController_","spineSkeletons_","textureRefCounts_","assetRefResolver_","canvas_","textCanvasSize","ctx_","getContext","willReadFrequently","loadShader","materialLoader_","registerEmbeddedAssets","assets","location","protocol","setEmbeddedOnly","loadTextureWithFlip","loadTextureRaw","getTexture","textureCacheKey","hasTexture","getTextureRefCount","total","flip","releaseTexture","rm","getResourceManager","count","releaseBitmapFont","unloadSkeleton","cleanupVirtualFS","fs","FS","unlink","setTextureMetadata","border","left","right","top","bottom","setSpineController","controller","getSpineSkeletonHandle","skeletonPath","cacheKey","atlasUrl","resolveUrl","atlasContent","fetchText","writeToVirtualFS","atlasDir","textureNames","parseAtlasTextures","loadedTextures","texName","texUrl","registerTextureWithPath","skelUrl","isBinary","skelData","fetchBinary","skelHandle","loadSkeleton","pageCount","getAtlasPageCount","pageName","getAtlasPageTextureName","tex","find","glId","getTextureGLId","setAtlasPageTexture","String","isSpineLoaded","releaseSpine","fontEntry","loadBmfontAsset","loadFntFile","getFont","releaseFont","fetchJson","fntFile","generatedFnt","fntUrl","fntContent","pageMatch","match","fntDir","texInfo","setAssetRefResolver","resolver","loadPrefab","resolvePrefabRefs_","prefab","nestedPrefab","prefabPath","getMaterial","hasMaterial","loadShaderInternal","noCache","loadText","loadBinary","loadScene","loadAll","manifest","setAddressableManifest","allAssets","groups","loadAddressableAssets","groupName","groupList","asset","address","label","labels","list","resolveAddress","loadAddressableAsset","loadByLabel","loadGroup","bundle","textures","materials","fonts","prefabs","text","binary","mat","allSettled","status","reason","loadTextureInternal","img","loadImage","createTextureFromImage","localPath","isLocalPath","toLocalPath","embedded","getEmbedded","loadImageFromSrc","imgSrc","createImage","crossOrigin","onload","createImageBitmap","bitmap","premultiplyAlpha","colorSpaceConversion","onerror","src","gl","getWebGL2Context","createTextureWebGL2","createTextureFallback","glObj","GL","currentContext","GLctx","ctx","WebGL2RenderingContext","createTexture","bindTexture","TEXTURE_2D","pixelStorei","UNPACK_FLIP_Y_WEBGL","UNPACK_PREMULTIPLY_ALPHA_WEBGL","texImage2D","RGBA","UNSIGNED_BYTE","texParameteri","TEXTURE_MIN_FILTER","LINEAR","TEXTURE_MAG_FILTER","TEXTURE_WRAP_S","REPEAT","TEXTURE_WRAP_T","generateMipmap","glTextureId","getNewId","registerExternalTexture","nextPowerOf2","clearRect","drawImage","imageData","getImageData","pixels","unpremultiplyAlpha","scale","round","decodeDataUrlText","vertex","fragment","parseEsShader","createShader","vertexMatch","fragmentMatch","trim","dataUrl","atob","decodeDataUrlBinary","raw","charCodeAt","response","arrayBuffer","virtualPath","ensureVirtualDir","writeFile","e","filter","currentPath","analyzePath","exists","mkdir","base","n","line","trimmed","endsWith","Assets","defineResource","AssetPlugin","build","app","wasmModule","insertResource","assetPlugin","wrapSpineModule","cw","cwrap","bind","getLastError","createInstance","destroyInstance","playAnimation","addAnimation","setSkin","update","getAnimations","getSkins","getBonePosition","getBoneRotation","getBounds","getMeshBatchCount","getMeshBatchVertexCount","getMeshBatchIndexCount","getMeshBatchData","loadSpineModule","wasmUrl","factory"],"mappings":"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"}
\ No newline at end of file
diff --git a/desktop/public/sdk/esm/shared/app.d.ts b/desktop/public/sdk/esm/shared/app.d.ts
new file mode 100644
index 000000000..829e4128f
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/app.d.ts
@@ -0,0 +1,1499 @@
+import { C as Color, V as Vec2, a as Entity, b as Vec3, Q as Quat, c as CppRegistry, E as ESEngineModule, d as Vec4, T as TextureHandle, F as FontHandle } from './wasm.js';
+
+/**
+ * @file component.ts
+ * @brief Component definition and builtin components
+ */
+
+interface ComponentDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _default: T;
+ readonly _builtin: false;
+ create(data?: Partial<T>): T;
+}
+declare function defineComponent<T extends object>(name: string, defaults: T): ComponentDef<T>;
+declare function defineTag(name: string): ComponentDef<{}>;
+declare function getUserComponent(name: string): ComponentDef<any> | undefined;
+declare function clearUserComponents(): void;
+declare function unregisterComponent(name: string): void;
+interface BuiltinComponentDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _cppName: string;
+ readonly _builtin: true;
+ readonly _default: T;
+}
+type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
+declare function isBuiltinComponent(comp: AnyComponentDef): comp is BuiltinComponentDef<any>;
+declare function registerComponent(name: string, def: AnyComponentDef): void;
+declare function getComponent(name: string): AnyComponentDef | undefined;
+declare const ProjectionType: {
+ readonly Perspective: 0;
+ readonly Orthographic: 1;
+};
+type ProjectionType = (typeof ProjectionType)[keyof typeof ProjectionType];
+declare const ClearFlags: {
+ readonly None: 0;
+ readonly ColorOnly: 1;
+ readonly DepthOnly: 2;
+ readonly ColorAndDepth: 3;
+};
+type ClearFlags = (typeof ClearFlags)[keyof typeof ClearFlags];
+declare const ScaleMode: {
+ readonly FixedWidth: 0;
+ readonly FixedHeight: 1;
+ readonly Expand: 2;
+ readonly Shrink: 3;
+ readonly Match: 4;
+};
+type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];
+interface TransformData {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+ worldPosition: Vec3;
+ worldRotation: Quat;
+ worldScale: Vec3;
+}
+type LocalTransformData = TransformData;
+type WorldTransformData = TransformData;
+interface SpriteData {
+ texture: number;
+ color: Color;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ material: number;
+ enabled: boolean;
+}
+interface CameraData {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ /** Editor-only: not synced to C++ Camera component, used for gizmo rendering */
+ showFrustum: boolean;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
+}
+interface CanvasData {
+ designResolution: Vec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Color;
+}
+interface VelocityData {
+ linear: Vec3;
+ angular: Vec3;
+}
+interface ParentData {
+ entity: Entity;
+}
+interface ChildrenData {
+ entities: Entity[];
+}
+interface SpineAnimationData {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Color;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+ enabled: boolean;
+}
+interface BitmapTextData {
+ text: string;
+ color: Color;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+ enabled: boolean;
+}
+interface NameData {
+ value: string;
+}
+interface SceneOwnerData {
+ scene: string;
+ persistent: boolean;
+}
+declare const Transform: BuiltinComponentDef<TransformData>;
+declare const LocalTransform: BuiltinComponentDef<TransformData>;
+declare const WorldTransform: BuiltinComponentDef<TransformData>;
+declare const Sprite: BuiltinComponentDef<SpriteData>;
+declare const Camera: BuiltinComponentDef<CameraData>;
+declare const Canvas: BuiltinComponentDef<CanvasData>;
+declare const Velocity: BuiltinComponentDef<VelocityData>;
+declare const Parent: BuiltinComponentDef<ParentData>;
+declare const Children: BuiltinComponentDef<ChildrenData>;
+declare const BitmapText: BuiltinComponentDef<BitmapTextData>;
+declare const SpineAnimation: BuiltinComponentDef<SpineAnimationData>;
+declare const EmitterShape: {
+ readonly Point: 0;
+ readonly Circle: 1;
+ readonly Rectangle: 2;
+ readonly Cone: 3;
+};
+type EmitterShape = (typeof EmitterShape)[keyof typeof EmitterShape];
+declare const SimulationSpace: {
+ readonly World: 0;
+ readonly Local: 1;
+};
+type SimulationSpace = (typeof SimulationSpace)[keyof typeof SimulationSpace];
+declare const ParticleEasing: {
+ readonly Linear: 0;
+ readonly EaseIn: 1;
+ readonly EaseOut: 2;
+ readonly EaseInOut: 3;
+};
+type ParticleEasing = (typeof ParticleEasing)[keyof typeof ParticleEasing];
+interface ParticleEmitterData {
+ rate: number;
+ burstCount: number;
+ burstInterval: number;
+ duration: number;
+ looping: boolean;
+ playOnStart: boolean;
+ maxParticles: number;
+ lifetimeMin: number;
+ lifetimeMax: number;
+ shape: number;
+ shapeRadius: number;
+ shapeSize: Vec2;
+ shapeAngle: number;
+ speedMin: number;
+ speedMax: number;
+ angleSpreadMin: number;
+ angleSpreadMax: number;
+ startSizeMin: number;
+ startSizeMax: number;
+ endSizeMin: number;
+ endSizeMax: number;
+ sizeEasing: number;
+ startColor: Color;
+ endColor: Color;
+ colorEasing: number;
+ rotationMin: number;
+ rotationMax: number;
+ angularVelocityMin: number;
+ angularVelocityMax: number;
+ gravity: Vec2;
+ damping: number;
+ texture: number;
+ spriteColumns: number;
+ spriteRows: number;
+ spriteFPS: number;
+ spriteLoop: boolean;
+ blendMode: number;
+ layer: number;
+ material: number;
+ simulationSpace: number;
+ enabled: boolean;
+}
+declare const ParticleEmitter: BuiltinComponentDef<ParticleEmitterData>;
+declare const Name: ComponentDef<NameData>;
+declare const SceneOwner: ComponentDef<SceneOwnerData>;
+interface PostProcessVolumeData {
+ effects: {
+ type: string;
+ enabled: boolean;
+ uniforms: Record<string, number>;
+ }[];
+ isGlobal: boolean;
+ shape: 'box' | 'sphere';
+ size: {
+ x: number;
+ y: number;
+ };
+ priority: number;
+ weight: number;
+ blendDistance: number;
+}
+declare const PostProcessVolume: ComponentDef<PostProcessVolumeData>;
+
+type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
+declare function getComponentDefaults(typeName: string): Record<string, unknown> | null;
+
+/**
+ * @file resource.ts
+ * @brief Resource system for global singleton data
+ */
+interface ResourceDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _default: T;
+}
+declare function defineResource<T>(defaultValue: T, name?: string): ResourceDef<T>;
+interface ResDescriptor<T> {
+ readonly _type: 'res';
+ readonly _resource: ResourceDef<T>;
+}
+interface ResMutDescriptor<T> {
+ readonly _type: 'res_mut';
+ readonly _resource: ResourceDef<T>;
+}
+declare function Res<T>(resource: ResourceDef<T>): ResDescriptor<T>;
+declare function ResMut<T>(resource: ResourceDef<T>): ResMutDescriptor<T>;
+declare class ResMutInstance<T> {
+ private value_;
+ private readonly setter_;
+ constructor(value: T, setter: (v: T) => void);
+ get(): T;
+ set(value: T): void;
+ modify(fn: (value: T) => void): void;
+ /** @internal */
+ updateValue(value: T): void;
+}
+declare class ResourceStorage {
+ private resources_;
+ private resMutPool_;
+ insert<T>(resource: ResourceDef<T>, value: T): void;
+ get<T>(resource: ResourceDef<T>): T;
+ set<T>(resource: ResourceDef<T>, value: T): void;
+ has<T>(resource: ResourceDef<T>): boolean;
+ remove<T>(resource: ResourceDef<T>): void;
+ getResMut<T>(resource: ResourceDef<T>): ResMutInstance<T>;
+}
+interface TimeData {
+ delta: number;
+ elapsed: number;
+ frameCount: number;
+}
+declare const Time: ResourceDef<TimeData>;
+
+/**
+ * @file world.ts
+ * @brief ECS World with C++ Registry integration
+ */
+
+declare class World {
+ private cppRegistry_;
+ private module_;
+ private entities_;
+ private tsStorage_;
+ private entityComponents_;
+ private queryPool_;
+ private queryPoolIdx_;
+ private worldVersion_;
+ private queryCache_;
+ private builtinMethodCache_;
+ private iterationDepth_;
+ private nextEntityId_;
+ private nextGeneration_;
+ private spawnCallbacks_;
+ private despawnCallbacks_;
+ private worldTick_;
+ private componentAddedTicks_;
+ private componentChangedTicks_;
+ private componentRemovedBuffer_;
+ connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void;
+ disconnectCpp(): void;
+ get hasCpp(): boolean;
+ getCppRegistry(): CppRegistry | null;
+ spawn(): Entity;
+ despawn(entity: Entity): void;
+ onSpawn(callback: (entity: Entity) => void): () => void;
+ onDespawn(callback: (entity: Entity) => void): () => void;
+ valid(entity: Entity): boolean;
+ entityCount(): number;
+ getWorldVersion(): number;
+ beginIteration(): void;
+ endIteration(): void;
+ resetIterationDepth(): void;
+ isIterating(): boolean;
+ getAllEntities(): Entity[];
+ setParent(child: Entity, parent: Entity): void;
+ removeParent(entity: Entity): void;
+ insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
+ set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
+ has(entity: Entity, component: AnyComponentDef): boolean;
+ tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null;
+ remove(entity: Entity, component: AnyComponentDef): void;
+ private getBuiltinMethods;
+ private insertBuiltin;
+ private getBuiltin;
+ private hasBuiltin;
+ private removeBuiltin;
+ private insertScript;
+ private getScript;
+ private hasScript;
+ private removeScript;
+ private getStorage;
+ resetQueryPool(): void;
+ getComponentTypes(entity: Entity): string[];
+ getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string): Entity[];
+ advanceTick(): void;
+ getWorldTick(): number;
+ isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
+ isChangedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
+ getRemovedEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[];
+ cleanRemovedBuffer(beforeTick: number): void;
+ private recordAddedTick_;
+ private recordChangedTick_;
+ private recordRemovedTick_;
+}
+
+/**
+ * @file query.ts
+ * @brief Component query system with mutable component support
+ */
+
+interface MutWrapper<T extends AnyComponentDef> {
+ readonly _type: 'mut';
+ readonly _component: T;
+}
+declare function Mut<T extends AnyComponentDef>(component: T): MutWrapper<T>;
+interface AddedWrapper<T extends AnyComponentDef> {
+ readonly _filterType: 'added';
+ readonly _component: T;
+}
+interface ChangedWrapper<T extends AnyComponentDef> {
+ readonly _filterType: 'changed';
+ readonly _component: T;
+}
+declare function Added<T extends AnyComponentDef>(component: T): AddedWrapper<T>;
+declare function Changed<T extends AnyComponentDef>(component: T): ChangedWrapper<T>;
+type QueryArg$1 = AnyComponentDef | MutWrapper<AnyComponentDef> | AddedWrapper<AnyComponentDef> | ChangedWrapper<AnyComponentDef>;
+interface QueryDescriptor<C extends readonly QueryArg$1[]> {
+ readonly _type: 'query';
+ readonly _components: C;
+ readonly _mutIndices: number[];
+ readonly _with: AnyComponentDef[];
+ readonly _without: AnyComponentDef[];
+ readonly _addedFilters: Array<{
+ index: number;
+ component: AnyComponentDef;
+ }>;
+ readonly _changedFilters: Array<{
+ index: number;
+ component: AnyComponentDef;
+ }>;
+}
+interface QueryBuilder<C extends readonly QueryArg$1[]> extends QueryDescriptor<C> {
+ with(...components: AnyComponentDef[]): QueryBuilder<C>;
+ without(...components: AnyComponentDef[]): QueryBuilder<C>;
+}
+declare function Query<C extends QueryArg$1[]>(...components: C): QueryBuilder<C>;
+type UnwrapQueryArg<T> = T extends MutWrapper<infer C> ? C : T extends AddedWrapper<infer C> ? C : T extends ChangedWrapper<infer C> ? C : T;
+type ComponentsData<C extends readonly QueryArg$1[]> = {
+ [K in keyof C]: ComponentData<UnwrapQueryArg<C[K]>>;
+};
+type QueryResult<C extends readonly QueryArg$1[]> = [
+ Entity,
+ ...ComponentsData<C>
+];
+declare class QueryInstance<C extends readonly QueryArg$1[]> implements Iterable<QueryResult<C>> {
+ private readonly world_;
+ private readonly descriptor_;
+ private readonly actualComponents_;
+ private readonly allRequired_;
+ private readonly result_;
+ private readonly mutData_;
+ private readonly cacheKey_;
+ private readonly lastRunTick_;
+ constructor(world: World, descriptor: QueryDescriptor<C>, lastRunTick?: number);
+ private passesChangeFilters_;
+ [Symbol.iterator](): Iterator<QueryResult<C>>;
+ forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void;
+ single(): QueryResult<C> | null;
+ isEmpty(): boolean;
+ count(): number;
+ toArray(): QueryResult<C>[];
+}
+interface RemovedQueryDescriptor<T extends AnyComponentDef> {
+ readonly _type: 'removed';
+ readonly _component: T;
+}
+declare function Removed<T extends AnyComponentDef>(component: T): RemovedQueryDescriptor<T>;
+declare class RemovedQueryInstance<T extends AnyComponentDef> implements Iterable<Entity> {
+ private readonly world_;
+ private readonly component_;
+ private readonly lastRunTick_;
+ constructor(world: World, component: T, lastRunTick: number);
+ [Symbol.iterator](): Iterator<Entity>;
+ isEmpty(): boolean;
+ toArray(): Entity[];
+}
+
+/**
+ * @file commands.ts
+ * @brief Deferred entity/component operations
+ */
+
+interface CommandsDescriptor {
+ readonly _type: 'commands';
+}
+declare function Commands(): CommandsDescriptor;
+interface SpawnComponentEntry {
+ component: AnyComponentDef;
+ data: unknown;
+}
+declare class EntityCommands {
+ private readonly commands_;
+ private readonly entityRef_;
+ private readonly components_;
+ private isNew_;
+ constructor(commands: CommandsInstance, entity: Entity | null);
+ insert<T extends object>(component: AnyComponentDef, data?: Partial<T>): this;
+ remove(component: AnyComponentDef): this;
+ id(): Entity;
+ finalize(): void;
+}
+declare class CommandsInstance {
+ private readonly world_;
+ private readonly resources_;
+ private pending_;
+ private spawned_;
+ constructor(world: World, resources: ResourceStorage);
+ spawn(): EntityCommands;
+ entity(entity: Entity): EntityCommands;
+ despawn(entity: Entity): this;
+ insertResource<T>(resource: ResourceDef<T>, value: T): this;
+ queueInsert(entity: Entity, component: AnyComponentDef, data: unknown): void;
+ queueRemove(entity: Entity, component: AnyComponentDef): void;
+ spawnImmediate(components: SpawnComponentEntry[], entityRef: {
+ entity: Entity;
+ }): void;
+ flush(): void;
+ private executeCommand;
+}
+
+/**
+ * @file event.ts
+ * @brief Event system with double-buffered event buses
+ */
+interface EventDef<T> {
+ readonly _id: symbol;
+ readonly _name: string;
+ readonly _phantom?: T;
+}
+declare function defineEvent<T>(name: string): EventDef<T>;
+declare class EventBus<T> {
+ private readBuffer_;
+ private writeBuffer_;
+ send(event: T): void;
+ getReadBuffer(): readonly T[];
+ swap(): void;
+}
+declare class EventRegistry {
+ private readonly buses_;
+ register<T>(event: EventDef<T>): void;
+ getBus<T>(event: EventDef<T>): EventBus<T>;
+ swapAll(): void;
+}
+interface EventWriterDescriptor<T> {
+ readonly _type: 'event_writer';
+ readonly _event: EventDef<T>;
+}
+interface EventReaderDescriptor<T> {
+ readonly _type: 'event_reader';
+ readonly _event: EventDef<T>;
+}
+declare function EventWriter<T>(event: EventDef<T>): EventWriterDescriptor<T>;
+declare function EventReader<T>(event: EventDef<T>): EventReaderDescriptor<T>;
+declare class EventWriterInstance<T> {
+ private readonly bus_;
+ constructor(bus: EventBus<T>);
+ send(event: T): void;
+}
+declare class EventReaderInstance<T> implements Iterable<T> {
+ private readonly bus_;
+ constructor(bus: EventBus<T>);
+ [Symbol.iterator](): Iterator<T>;
+ isEmpty(): boolean;
+ toArray(): T[];
+}
+
+/**
+ * @file system.ts
+ * @brief System definition and scheduling
+ */
+
+declare enum Schedule {
+ Startup = 0,
+ First = 1,
+ PreUpdate = 2,
+ Update = 3,
+ PostUpdate = 4,
+ Last = 5,
+ FixedPreUpdate = 10,
+ FixedUpdate = 11,
+ FixedPostUpdate = 12
+}
+interface GetWorldDescriptor {
+ readonly _type: 'get_world';
+}
+declare function GetWorld(): GetWorldDescriptor;
+type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
+type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
+type InferParam<P> = P extends QueryDescriptor<infer C> ? QueryInstance<C> : P extends ResDescriptor<infer T> ? T : P extends ResMutDescriptor<infer T> ? ResMutInstance<T> : P extends CommandsDescriptor ? CommandsInstance : P extends EventWriterDescriptor<infer T> ? EventWriterInstance<T> : P extends EventReaderDescriptor<infer T> ? EventReaderInstance<T> : P extends RemovedQueryDescriptor<infer _T> ? RemovedQueryInstance<_T> : P extends GetWorldDescriptor ? World : never;
+type InferParams<P extends readonly SystemParam[]> = {
+ [K in keyof P]: InferParam<P[K]>;
+};
+interface SystemDef {
+ readonly _id: symbol;
+ readonly _params: readonly SystemParam[];
+ readonly _fn: (...args: never[]) => void;
+ readonly _name: string;
+}
+interface SystemOptions {
+ name?: string;
+ runBefore?: string[];
+ runAfter?: string[];
+}
+declare function defineSystem<P extends readonly SystemParam[]>(params: [...P], fn: (...args: InferParams<P>) => void, options?: SystemOptions): SystemDef;
+declare function addSystem(system: SystemDef): void;
+declare function addStartupSystem(system: SystemDef): void;
+declare function addSystemToSchedule(schedule: Schedule, system: SystemDef): void;
+declare class SystemRunner {
+ private readonly world_;
+ private readonly resources_;
+ private readonly eventRegistry_;
+ private readonly argsCache_;
+ private readonly systemTicks_;
+ private currentLastRunTick_;
+ private timings_;
+ constructor(world: World, resources: ResourceStorage, eventRegistry?: EventRegistry);
+ setTimingEnabled(enabled: boolean): void;
+ getTimings(): ReadonlyMap<string, number> | null;
+ run(system: SystemDef): void;
+ private resolveParam;
+}
+
+/**
+ * @file renderPipeline.ts
+ * @brief Unified render pipeline for runtime and editor
+ */
+
+interface RenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ width: number;
+ height: number;
+ elapsed: number;
+}
+interface CameraRenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ viewportPixels: {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ };
+ clearFlags: number;
+ elapsed: number;
+ cameraEntity?: Entity;
+}
+type SpineRendererFn = (registry: {
+ _cpp: CppRegistry;
+}, elapsed: number) => void;
+type TilemapRendererFn = () => void;
+type MaskProcessorFn = (registry: CppRegistry, vp: Float32Array, viewportX: number, viewportY: number, viewportW: number, viewportH: number) => void;
+declare class RenderPipeline {
+ private spineRenderer_;
+ private tilemapRenderer_;
+ private maskProcessor_;
+ private lastWidth_;
+ private lastHeight_;
+ private activeScenes_;
+ get spineRenderer(): SpineRendererFn | null;
+ setSpineRenderer(fn: SpineRendererFn | null): void;
+ setTilemapRenderer(fn: TilemapRendererFn | null): void;
+ get maskProcessor(): MaskProcessorFn | null;
+ setMaskProcessor(fn: MaskProcessorFn | null): void;
+ setActiveScenes(scenes: Set<string> | null): void;
+ beginScreenCapture(): void;
+ endScreenCapture(): void;
+ render(params: RenderParams): void;
+ renderCamera(params: CameraRenderParams): void;
+ private executeDrawCallbacks;
+}
+
+/**
+ * @file blend.ts
+ * @brief Blend mode definitions for rendering
+ */
+declare enum BlendMode {
+ Normal = 0,
+ Additive = 1,
+ Multiply = 2,
+ Screen = 3,
+ PremultipliedAlpha = 4
+}
+
+/**
+ * @file material.ts
+ * @brief Material and Shader API for custom rendering
+ * @details Provides shader creation and material management for custom visual effects.
+ */
+
+type ShaderHandle = number;
+type MaterialHandle = number;
+interface TextureRef {
+ __textureRef: true;
+ textureId: number;
+ slot?: number;
+}
+type UniformValue = number | Vec2 | Vec3 | Vec4 | number[] | TextureRef;
+declare function isTextureRef(v: UniformValue): v is TextureRef;
+interface MaterialOptions {
+ shader: ShaderHandle;
+ uniforms?: Record<string, UniformValue>;
+ blendMode?: BlendMode;
+ depthTest?: boolean;
+}
+interface MaterialAssetData {
+ version: string;
+ type: 'material';
+ shader: string;
+ blendMode: number;
+ depthTest: boolean;
+ properties: Record<string, unknown>;
+}
+interface MaterialData {
+ shader: ShaderHandle;
+ uniforms: Map<string, UniformValue>;
+ blendMode: BlendMode;
+ depthTest: boolean;
+ dirty_: boolean;
+ cachedBuffer_: Float32Array | null;
+ cachedIdx_: number;
+}
+declare function initMaterialAPI(wasmModule: ESEngineModule): void;
+declare function shutdownMaterialAPI(): void;
+declare const Material: {
+ /**
+ * Creates a shader from vertex and fragment source code.
+ * @param vertexSrc GLSL vertex shader source
+ * @param fragmentSrc GLSL fragment shader source
+ * @returns Shader handle, or 0 on failure
+ */
+ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle;
+ /**
+ * Releases a shader.
+ * @param shader Shader handle to release
+ */
+ releaseShader(shader: ShaderHandle): void;
+ /**
+ * Creates a material with a shader and optional settings.
+ * @param options Material creation options
+ * @returns Material handle
+ */
+ create(options: MaterialOptions): MaterialHandle;
+ /**
+ * Gets material data by handle.
+ * @param material Material handle
+ * @returns Material data or undefined
+ */
+ get(material: MaterialHandle): MaterialData | undefined;
+ /**
+ * Sets a uniform value on a material.
+ * @param material Material handle
+ * @param name Uniform name
+ * @param value Uniform value
+ */
+ setUniform(material: MaterialHandle, name: string, value: UniformValue): void;
+ /**
+ * Gets a uniform value from a material.
+ * @param material Material handle
+ * @param name Uniform name
+ * @returns Uniform value or undefined
+ */
+ getUniform(material: MaterialHandle, name: string): UniformValue | undefined;
+ /**
+ * Sets the blend mode for a material.
+ * @param material Material handle
+ * @param mode Blend mode
+ */
+ setBlendMode(material: MaterialHandle, mode: BlendMode): void;
+ /**
+ * Gets the blend mode of a material.
+ * @param material Material handle
+ * @returns Blend mode
+ */
+ getBlendMode(material: MaterialHandle): BlendMode;
+ /**
+ * Sets depth test enabled for a material.
+ * @param material Material handle
+ * @param enabled Whether depth test is enabled
+ */
+ setDepthTest(material: MaterialHandle, enabled: boolean): void;
+ /**
+ * Gets the shader handle for a material.
+ * @param material Material handle
+ * @returns Shader handle
+ */
+ getShader(material: MaterialHandle): ShaderHandle;
+ /**
+ * Releases a material (does not release the shader).
+ * @param material Material handle
+ */
+ release(material: MaterialHandle): void;
+ /**
+ * Checks if a material exists.
+ * @param material Material handle
+ * @returns True if material exists
+ */
+ isValid(material: MaterialHandle): boolean;
+ releaseAll(): void;
+ /**
+ * Creates a material from asset data.
+ * @param data Material asset data (properties object)
+ * @param shaderHandle Pre-loaded shader handle
+ * @returns Material handle
+ */
+ createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle): MaterialHandle;
+ /**
+ * Creates a material instance that shares the shader with source.
+ * @param source Source material handle
+ * @returns New material handle with copied settings
+ */
+ createInstance(source: MaterialHandle): MaterialHandle;
+ /**
+ * Exports material to serializable asset data.
+ * @param material Material handle
+ * @param shaderPath Shader file path for asset reference
+ * @returns Material asset data
+ */
+ toAssetData(material: MaterialHandle, shaderPath: string): MaterialAssetData | null;
+ /**
+ * Gets all uniforms from a material.
+ * @param material Material handle
+ * @returns Map of uniform names to values
+ */
+ getUniforms(material: MaterialHandle): Map<string, UniformValue>;
+ tex(textureId: number, slot?: number): TextureRef;
+};
+declare function registerMaterialCallback(): void;
+declare const ShaderSources: {
+ SPRITE_VERTEX: string;
+ SPRITE_FRAGMENT: string;
+ COLOR_VERTEX: string;
+ COLOR_FRAGMENT: string;
+};
+
+/**
+ * @file MaterialLoader.ts
+ * @brief Material asset loading and caching
+ */
+
+interface LoadedMaterial {
+ handle: MaterialHandle;
+ shaderHandle: ShaderHandle;
+ path: string;
+}
+interface ShaderLoader {
+ load(path: string): Promise<ShaderHandle>;
+ get(path: string): ShaderHandle | undefined;
+}
+declare class MaterialLoader {
+ private cache_;
+ private shaderLoader_;
+ private basePath_;
+ constructor(shaderLoader: ShaderLoader, basePath?: string);
+ load(path: string): Promise<LoadedMaterial>;
+ get(path: string): LoadedMaterial | undefined;
+ has(path: string): boolean;
+ release(path: string): void;
+ releaseAll(): void;
+ private loadInternal;
+ private resolvePath;
+ private resolveShaderPath;
+}
+
+interface PrefabData {
+ version: string;
+ name: string;
+ rootEntityId: number;
+ entities: PrefabEntityData[];
+}
+interface PrefabEntityData {
+ prefabEntityId: number;
+ name: string;
+ parent: number | null;
+ children: number[];
+ components: {
+ type: string;
+ data: Record<string, unknown>;
+ }[];
+ visible: boolean;
+ nestedPrefab?: {
+ prefabPath: string;
+ overrides: PrefabOverride[];
+ };
+}
+interface PrefabOverride {
+ prefabEntityId: number;
+ type: 'property' | 'component_added' | 'component_removed' | 'name' | 'visibility';
+ componentType?: string;
+ propertyName?: string;
+ value?: unknown;
+ componentData?: {
+ type: string;
+ data: Record<string, unknown>;
+ };
+}
+interface InstantiatePrefabOptions {
+ assetServer?: AssetServer;
+ assetBaseUrl?: string;
+ parent?: Entity;
+ overrides?: PrefabOverride[];
+}
+interface InstantiatePrefabResult {
+ root: Entity;
+ entities: Map<number, Entity>;
+}
+declare function instantiatePrefab(world: World, prefab: PrefabData, options?: InstantiatePrefabOptions): Promise<InstantiatePrefabResult>;
+
+/**
+ * @file SpineModuleLoader.ts
+ * @brief Loads and initializes the standalone Spine WASM module
+ */
+interface SpineWasmModule {
+ _spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;
+ _spine_unloadSkeleton(handle: number): void;
+ _spine_getAtlasPageCount(handle: number): number;
+ _spine_getAtlasPageTextureName(handle: number, pageIndex: number): number;
+ _spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
+ _spine_createInstance(skeletonHandle: number): number;
+ _spine_destroyInstance(instanceId: number): void;
+ _spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;
+ _spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;
+ _spine_setSkin(instanceId: number, name: number): void;
+ _spine_update(instanceId: number, dt: number): void;
+ _spine_getAnimations(instanceId: number): number;
+ _spine_getSkins(instanceId: number): number;
+ _spine_getBonePosition(instanceId: number, bone: number, outXPtr: number, outYPtr: number): number;
+ _spine_getBoneRotation(instanceId: number, bone: number): number;
+ _spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;
+ _spine_getMeshBatchCount(instanceId: number): number;
+ _spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
+ _spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
+ _spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;
+ cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;
+ UTF8ToString(ptr: number): string;
+ stringToNewUTF8(str: string): number;
+ HEAPF32: Float32Array;
+ HEAPU8: Uint8Array;
+ HEAPU32: Uint32Array;
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+}
+interface SpineWrappedAPI {
+ loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: string, atlasLen: number, isBinary: boolean): number;
+ getLastError(): string;
+ unloadSkeleton(handle: number): void;
+ getAtlasPageCount(handle: number): number;
+ getAtlasPageTextureName(handle: number, pageIndex: number): string;
+ setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
+ createInstance(skeletonHandle: number): number;
+ destroyInstance(instanceId: number): void;
+ playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;
+ addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;
+ setSkin(instanceId: number, name: string): void;
+ update(instanceId: number, dt: number): void;
+ getAnimations(instanceId: number): string;
+ getSkins(instanceId: number): string;
+ getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;
+ getBoneRotation(instanceId: number, bone: string): number;
+ getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;
+ getMeshBatchCount(instanceId: number): number;
+ getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
+ getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
+ getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;
+}
+declare function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI;
+type SpineModuleFactory = (config?: Record<string, unknown>) => Promise<SpineWasmModule>;
+declare function loadSpineModule(wasmUrl: string, factory?: SpineModuleFactory): Promise<{
+ raw: SpineWasmModule;
+ api: SpineWrappedAPI;
+}>;
+
+/**
+ * @file SpineController.ts
+ * @brief Spine animation control for the modular Spine WASM module
+ */
+
+type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';
+type SpineEventCallback = (event: SpineEvent) => void;
+interface SpineEvent {
+ type: SpineEventType;
+ entity: Entity;
+ track: number;
+ animation: string | null;
+ eventName?: string;
+ intValue?: number;
+ floatValue?: number;
+ stringValue?: string;
+}
+declare class SpineModuleController {
+ private raw_;
+ private api_;
+ private listeners_;
+ constructor(raw: SpineWasmModule, api: SpineWrappedAPI);
+ get raw(): SpineWasmModule;
+ loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number;
+ getLastError(): string;
+ unloadSkeleton(handle: number): void;
+ getAtlasPageCount(handle: number): number;
+ getAtlasPageTextureName(handle: number, pageIndex: number): string;
+ setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
+ createInstance(skeletonHandle: number): number;
+ destroyInstance(instanceId: number): void;
+ play(instanceId: number, animation: string, loop?: boolean, track?: number): boolean;
+ addAnimation(instanceId: number, animation: string, loop?: boolean, delay?: number, track?: number): boolean;
+ setSkin(instanceId: number, skinName: string): void;
+ update(instanceId: number, dt: number): void;
+ getAnimations(instanceId: number): string[];
+ getSkins(instanceId: number): string[];
+ getBonePosition(instanceId: number, boneName: string): Vec2 | null;
+ getBoneRotation(instanceId: number, boneName: string): number;
+ getBounds(instanceId: number): {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ extractMeshBatches(instanceId: number): {
+ vertices: Float32Array;
+ indices: Uint16Array;
+ textureId: number;
+ blendMode: number;
+ }[];
+ on(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;
+ off(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;
+ removeAllListeners(entity: Entity): void;
+}
+
+type AssetContentType = 'json' | 'text' | 'binary' | 'image' | 'audio';
+type AddressableAssetType = 'texture' | 'material' | 'spine' | 'bitmap-font' | 'prefab' | 'json' | 'text' | 'binary' | 'audio';
+type EditorAssetType = 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton' | 'bitmap-font' | 'prefab' | 'json' | 'audio' | 'scene' | 'anim-clip' | 'tilemap' | 'unknown';
+type AssetBuildTransform = (content: string, context: unknown) => string;
+interface AssetTypeEntry {
+ extensions: string[];
+ contentType: AssetContentType;
+ editorType: EditorAssetType;
+ addressableType: AddressableAssetType | null;
+ wechatPackInclude: boolean;
+ hasTransitiveDeps: boolean;
+ buildTransform?: AssetBuildTransform;
+}
+declare function getAssetTypeEntry(extensionOrPath: string): AssetTypeEntry | undefined;
+declare function getEditorType(path: string): EditorAssetType;
+declare function getAddressableType(path: string): AddressableAssetType | null;
+declare function getAddressableTypeByEditorType(editorType: string): AddressableAssetType | null;
+declare function isKnownAssetExtension(ext: string): boolean;
+declare function getAllAssetExtensions(): Set<string>;
+declare function looksLikeAssetPath(value: unknown): value is string;
+declare function getCustomExtensions(): string[];
+declare function getWeChatPackOptions(): Array<{
+ type: string;
+ value: string;
+}>;
+declare function getAssetMimeType(ext: string): string | undefined;
+declare function isCustomExtension(path: string): boolean;
+declare function toBuildPath(path: string): string;
+declare function registerAssetBuildTransform(editorType: EditorAssetType, transform: AssetBuildTransform): void;
+declare function getAssetBuildTransform(extensionOrPath: string): AssetBuildTransform | undefined;
+
+/**
+ * @file AssetServer.ts
+ * @brief Asset loading and caching system
+ */
+
+interface TextureInfo {
+ handle: TextureHandle;
+ width: number;
+ height: number;
+}
+interface SliceBorder$1 {
+ left: number;
+ right: number;
+ top: number;
+ bottom: number;
+}
+interface SpineLoadResult {
+ success: boolean;
+ error?: string;
+}
+interface SpineDescriptor {
+ skeleton: string;
+ atlas: string;
+ baseUrl?: string;
+}
+interface FileLoadOptions {
+ baseUrl?: string;
+ noCache?: boolean;
+}
+
+interface AddressableResultMap {
+ texture: TextureInfo;
+ material: LoadedMaterial;
+ spine: SpineLoadResult;
+ 'bitmap-font': FontHandle;
+ prefab: PrefabData;
+ json: unknown;
+ text: string;
+ binary: ArrayBuffer;
+ audio: ArrayBuffer;
+}
+interface AssetBundle {
+ textures: Map<string, TextureInfo>;
+ materials: Map<string, LoadedMaterial>;
+ spine: Map<string, SpineLoadResult>;
+ fonts: Map<string, FontHandle>;
+ prefabs: Map<string, PrefabData>;
+ json: Map<string, unknown>;
+ text: Map<string, string>;
+ binary: Map<string, ArrayBuffer>;
+}
+interface AddressableManifestAsset {
+ path: string;
+ address?: string;
+ type: AddressableAssetType;
+ size: number;
+ labels: string[];
+ metadata?: {
+ atlas?: string;
+ atlasPage?: number;
+ atlasFrame?: {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ };
+}
+interface AddressableManifestGroup {
+ bundleMode: string;
+ labels: string[];
+ assets: Record<string, AddressableManifestAsset>;
+}
+interface AddressableManifest {
+ version: '2.0';
+ groups: Record<string, AddressableManifestGroup>;
+}
+declare class AssetServer {
+ baseUrl?: string;
+ private module_;
+ private textureCache_;
+ private shaderCache_;
+ private jsonCache_;
+ private textCache_;
+ private binaryCache_;
+ private loadedSpines_;
+ private virtualFSPaths_;
+ private materialLoader_;
+ private canvas_;
+ private ctx_;
+ private fontCache_;
+ private prefabCache_;
+ private embedded_;
+ private embeddedOnly_;
+ private addressableManifest_;
+ private addressIndex_;
+ private labelIndex_;
+ private groupAssets_;
+ private spineController_;
+ private spineSkeletons_;
+ private textureRefCounts_;
+ private assetRefResolver_;
+ constructor(module: ESEngineModule);
+ registerEmbeddedAssets(assets: Record<string, string>): void;
+ setEmbeddedOnly(value: boolean): void;
+ /**
+ * Load texture with vertical flip (for Sprite/UI).
+ * OpenGL UV origin is bottom-left, so standard images need flipping.
+ */
+ loadTexture(source: string): Promise<TextureInfo>;
+ /**
+ * Load texture without flip (for Spine).
+ * Spine runtime handles UV coordinates internally.
+ */
+ loadTextureRaw(source: string): Promise<TextureInfo>;
+ getTexture(source: string): TextureInfo | undefined;
+ hasTexture(source: string): boolean;
+ getTextureRefCount(source: string): number;
+ releaseTexture(source: string): void;
+ releaseAll(): void;
+ private cleanupVirtualFS;
+ setTextureMetadata(handle: TextureHandle, border: SliceBorder$1): void;
+ setTextureMetadataByPath(source: string, border: SliceBorder$1): boolean;
+ setSpineController(controller: SpineModuleController): void;
+ getSpineSkeletonHandle(skeletonPath: string, atlasPath: string): number | undefined;
+ loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;
+ isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;
+ releaseSpine(key: string): void;
+ loadBitmapFont(fontPath: string, baseUrl?: string): Promise<FontHandle>;
+ getFont(fontPath: string): FontHandle | undefined;
+ releaseFont(fontPath: string): void;
+ private loadBmfontAsset;
+ private loadFntFile;
+ setAssetRefResolver(resolver: (ref: string) => string | null): void;
+ loadPrefab(path: string, baseUrl?: string): Promise<PrefabData>;
+ private resolvePrefabRefs_;
+ loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;
+ getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;
+ hasMaterial(path: string, baseUrl?: string): boolean;
+ loadShader(path: string): Promise<ShaderHandle>;
+ loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T>;
+ loadText(path: string, options?: FileLoadOptions): Promise<string>;
+ loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;
+ loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;
+ loadAll(manifest: AddressableManifest): Promise<AssetBundle>;
+ setAddressableManifest(manifest: AddressableManifest): void;
+ resolveAddress(address: string): AddressableManifestAsset | undefined;
+ load<T extends AddressableAssetType = AddressableAssetType>(address: string): Promise<AddressableResultMap[T]>;
+ loadByLabel(label: string): Promise<AssetBundle>;
+ loadGroup(groupName: string): Promise<AssetBundle>;
+ private loadAddressableAsset;
+ private loadAddressableAssets;
+ private textureCacheKey;
+ private loadTextureWithFlip;
+ private loadTextureInternal;
+ private loadImage;
+ private loadImageFromSrc;
+ private createTextureFromImage;
+ private getWebGL2Context;
+ private createTextureWebGL2;
+ private createTextureFallback;
+ private unpremultiplyAlpha;
+ private loadShaderInternal;
+ private parseEsShader;
+ private decodeDataUrlText;
+ private decodeDataUrlBinary;
+ private isLocalPath;
+ private toLocalPath;
+ private getEmbedded;
+ private fetchJson;
+ private fetchText;
+ private fetchBinary;
+ private writeToVirtualFS;
+ private ensureVirtualDir;
+ private resolveUrl;
+ private nextPowerOf2;
+ private parseAtlasTextures;
+}
+
+/**
+ * @file scene.ts
+ * @brief Scene loading utilities
+ */
+
+interface SceneEntityData {
+ id: number;
+ name: string;
+ parent: number | null;
+ children: number[];
+ components: SceneComponentData[];
+ visible?: boolean;
+}
+interface SceneComponentData {
+ type: string;
+ data: Record<string, unknown>;
+}
+interface SliceBorder {
+ left: number;
+ right: number;
+ top: number;
+ bottom: number;
+}
+interface TextureMetadata {
+ version: string;
+ type: 'texture';
+ sliceBorder: SliceBorder;
+}
+interface SceneData {
+ version: string;
+ name: string;
+ entities: SceneEntityData[];
+ textureMetadata?: Record<string, TextureMetadata>;
+}
+interface LoadedSceneAssets {
+ textureUrls: Set<string>;
+ materialHandles: Set<number>;
+ fontPaths: Set<string>;
+ spineKeys: Set<string>;
+}
+interface SceneLoadOptions {
+ assetServer?: AssetServer;
+ assetBaseUrl?: string;
+ collectAssets?: LoadedSceneAssets;
+}
+type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap';
+interface AssetFieldDescriptor {
+ field: string;
+ type: AssetFieldType;
+}
+interface SpineFieldDescriptor {
+ skeletonField: string;
+ atlasField: string;
+}
+interface ComponentAssetFields {
+ fields?: AssetFieldDescriptor[];
+ spine?: SpineFieldDescriptor;
+}
+declare function registerComponentAssetFields(componentType: string, config: ComponentAssetFields): void;
+declare function getComponentAssetFields(componentType: string): string[];
+declare function getComponentAssetFieldDescriptors(componentType: string): readonly {
+ field: string;
+ type: AssetFieldType;
+}[];
+declare function getComponentSpineFieldDescriptor(componentType: string): {
+ skeletonField: string;
+ atlasField: string;
+} | null;
+declare function registerComponentEntityFields(componentType: string, fields: string[]): void;
+declare function getComponentEntityFields(componentType: string): string[] | undefined;
+declare function remapEntityFields(compData: SceneComponentData, entityMap: Map<number, Entity>): void;
+declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;
+declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;
+declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void;
+declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;
+declare function findEntityByName(world: World, name: string): Entity | null;
+
+/**
+ * @file customDraw.ts
+ * @brief Custom draw callback registration for the render pipeline
+ */
+type DrawCallback = (elapsed: number) => void;
+declare function registerDrawCallback(id: string, fn: DrawCallback, scene?: string): void;
+declare function unregisterDrawCallback(id: string): void;
+declare function clearDrawCallbacks(): void;
+
+interface PassConfig {
+ name: string;
+ shader: ShaderHandle;
+ enabled: boolean;
+ floatUniforms: Map<string, number>;
+ vec4Uniforms: Map<string, Vec4>;
+}
+declare class PostProcessStack {
+ readonly id: number;
+ private passes_;
+ private destroyed_;
+ constructor();
+ addPass(name: string, shader: ShaderHandle): this;
+ removePass(name: string): this;
+ setEnabled(name: string, enabled: boolean): this;
+ setUniform(passName: string, uniform: string, value: number): this;
+ setUniformVec4(passName: string, uniform: string, value: Vec4): this;
+ setAllPassesEnabled(enabled: boolean): void;
+ get passCount(): number;
+ get enabledPassCount(): number;
+ get passes(): readonly PassConfig[];
+ get isDestroyed(): boolean;
+ destroy(): void;
+}
+
+type SceneStatus = 'loading' | 'running' | 'paused' | 'sleeping' | 'unloading';
+interface SceneConfig {
+ name: string;
+ path?: string;
+ data?: SceneData;
+ systems?: Array<{
+ schedule: Schedule;
+ system: SystemDef;
+ }>;
+ setup?: (ctx: SceneContext) => void | Promise<void>;
+ cleanup?: (ctx: SceneContext) => void;
+}
+interface SceneContext {
+ readonly name: string;
+ readonly entities: ReadonlySet<Entity>;
+ spawn(): Entity;
+ despawn(entity: Entity): void;
+ registerDrawCallback(id: string, fn: DrawCallback): void;
+ bindPostProcess(camera: Entity, stack: PostProcessStack): void;
+ unbindPostProcess(camera: Entity): void;
+ setPersistent(entity: Entity, persistent: boolean): void;
+}
+interface TransitionOptions {
+ keepPersistent?: boolean;
+ transition?: 'none' | 'fade';
+ duration?: number;
+ color?: Color;
+ onStart?: () => void;
+ onComplete?: () => void;
+}
+declare class SceneManagerState {
+ private readonly app_;
+ private readonly configs_;
+ private readonly scenes_;
+ private readonly contexts_;
+ private readonly additiveScenes_;
+ private readonly pausedScenes_;
+ private readonly sleepingScenes_;
+ private readonly loadOrder_;
+ private activeScene_;
+ private initialScene_;
+ private transition_;
+ private switching_;
+ private loadPromises_;
+ constructor(app: App);
+ reset(): void;
+ register(config: SceneConfig): void;
+ setInitial(name: string): void;
+ getInitial(): string | null;
+ isTransitioning(): boolean;
+ switchTo(name: string, options?: TransitionOptions): Promise<void>;
+ private startFadeTransition;
+ updateTransition(dt: number): void;
+ load(name: string): Promise<SceneContext>;
+ loadAdditive(name: string): Promise<SceneContext>;
+ unload(name: string, options?: TransitionOptions): Promise<void>;
+ private loadSceneData_;
+ private releaseSceneAssets_;
+ pause(name: string): void;
+ resume(name: string): void;
+ sleep(name: string): void;
+ wake(name: string): void;
+ private setPostProcessPassesEnabled;
+ isPaused(name: string): boolean;
+ isSleeping(name: string): boolean;
+ isLoaded(name: string): boolean;
+ isActive(name: string): boolean;
+ getActive(): string | null;
+ getActiveScenes(): string[];
+ getLoaded(): string[];
+ getLoadOrder(): string[];
+ bringToTop(name: string): void;
+ getScene(name: string): SceneContext | null;
+ getSceneStatus(name: string): SceneStatus | null;
+}
+declare const SceneManager: ResourceDef<SceneManagerState>;
+declare function wrapSceneSystem(app: App, sceneName: string, system: SystemDef): SystemDef;
+
+/**
+ * @file app.ts
+ * @brief Application builder and web platform integration
+ */
+
+type PluginDependency = string | ResourceDef<any>;
+interface Plugin {
+ name?: string;
+ dependencies?: PluginDependency[];
+ build(app: App): void;
+ finish?(app: App): void;
+ cleanup?(app?: App): void;
+}
+declare class App {
+ private readonly world_;
+ private readonly resources_;
+ private readonly systems_;
+ private runner_;
+ private running_;
+ private lastTime_;
+ private fixedTimestep_;
+ private fixedAccumulator_;
+ private maxDeltaTime_;
+ private maxFixedSteps_;
+ private module_;
+ private pipeline_;
+ private spineInitPromise_?;
+ private physicsInitPromise_?;
+ private physicsModule_?;
+ private readonly installed_plugins_;
+ private readonly installedPluginSet_;
+ private readonly installedPluginNames_;
+ private pluginsFinished_;
+ private readonly eventRegistry_;
+ private readonly sortedSystemsCache_;
+ private error_handler_;
+ private system_error_handler_;
+ private statsEnabled_;
+ private phaseTimings_;
+ private frame_paused_;
+ private user_paused_;
+ private step_pending_;
+ private play_speed_;
+ private constructor();
+ static new(): App;
+ addPlugin(plugin: Plugin): this;
+ addEvent<T>(event: EventDef<T>): this;
+ addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
+ runBefore?: string[];
+ runAfter?: string[];
+ }): this;
+ addSystem(system: SystemDef): this;
+ addStartupSystem(system: SystemDef): this;
+ removeSystem(systemId: symbol): boolean;
+ connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
+ get wasmModule(): ESEngineModule | null;
+ get pipeline(): RenderPipeline | null;
+ setPipeline(pipeline: RenderPipeline): void;
+ setSpineRenderer(fn: SpineRendererFn | null): void;
+ get spineInitPromise(): Promise<unknown> | undefined;
+ set spineInitPromise(p: Promise<unknown> | undefined);
+ get physicsInitPromise(): Promise<unknown> | undefined;
+ set physicsInitPromise(p: Promise<unknown> | undefined);
+ get physicsModule(): unknown;
+ set physicsModule(m: unknown);
+ get world(): World;
+ setFixedTimestep(timestep: number): this;
+ setMaxDeltaTime(v: number): this;
+ setMaxFixedSteps(v: number): this;
+ onError(handler: (error: unknown, systemName: string) => void): this;
+ onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
+ onWasmError(handler: (error: unknown, context: string) => void): this;
+ setPaused(paused: boolean): void;
+ isPaused(): boolean;
+ stepFrame(): void;
+ setPlaySpeed(speed: number): void;
+ getPlaySpeed(): number;
+ enableStats(): this;
+ getSystemTimings(): ReadonlyMap<string, number> | null;
+ getPhaseTimings(): ReadonlyMap<string, number> | null;
+ getEntityCount(): number;
+ insertResource<T>(resource: ResourceDef<T>, value: T): this;
+ getResource<T>(resource: ResourceDef<T>): T;
+ hasResource<T>(resource: ResourceDef<T>): boolean;
+ registerScene(config: SceneConfig): this;
+ setInitialScene(name: string): this;
+ tick(delta: number): void;
+ run(): void;
+ private mainLoop;
+ quit(): void;
+ private finishPlugins_;
+ private sortSystems;
+ private runSchedule;
+ private updateTime;
+}
+interface WebAppOptions {
+ getViewportSize?: () => {
+ width: number;
+ height: number;
+ };
+ glContextHandle?: number;
+ plugins?: Plugin[];
+}
+declare function flushPendingSystems(app: App): void;
+
+export { CommandsInstance as $, App as A, BitmapText as H, Camera as K, Canvas as O, Changed as T, Children as V, World as W, ClearFlags as Y, Commands as Z, SpineModuleController as a, SceneOwner as a$, EmitterShape as a3, EntityCommands as a4, EventReader as a6, EventReaderInstance as a8, EventRegistry as a9, PostProcessVolume as aA, ProjectionType as aE, Query as aF, QueryInstance as aI, Removed as aK, RemovedQueryInstance as aM, RenderPipeline as aO, Res as aP, ResMut as aR, ResMutInstance as aT, ScaleMode as aU, SceneManager as aZ, SceneManagerState as a_, EventWriter as aa, EventWriterInstance as ac, GetWorld as ae, LocalTransform as ak, Material as am, MaterialLoader as ao, Mut as aq, Name as as, Parent as au, ParticleEasing as aw, ParticleEmitter as ax, isTextureRef as b$, Schedule as b2, ShaderSources as b4, SimulationSpace as b5, SpineAnimation as b7, defineEvent as bA, defineResource as bB, defineSystem as bC, defineTag as bD, findEntityByName as bE, flushPendingSystems as bF, getAddressableType as bG, getAddressableTypeByEditorType as bH, getAllAssetExtensions as bI, getAssetBuildTransform as bJ, getAssetMimeType as bK, getAssetTypeEntry as bL, getComponent as bM, getComponentAssetFieldDescriptors as bN, getComponentAssetFields as bO, getComponentDefaults as bP, getComponentEntityFields as bQ, getComponentSpineFieldDescriptor as bR, getCustomExtensions as bS, getEditorType as bT, getUserComponent as bU, getWeChatPackOptions as bV, initMaterialAPI as bW, instantiatePrefab as bX, isBuiltinComponent as bY, isCustomExtension as bZ, isKnownAssetExtension as b_, Sprite as bc, SystemRunner as bh, Time as bk, Transform as bm, Velocity as bq, WorldTransform as bs, addStartupSystem as bu, addSystem as bv, addSystemToSchedule as bw, clearDrawCallbacks as bx, clearUserComponents as by, defineComponent as bz, loadComponent as c0, loadSceneData as c1, loadSceneWithAssets as c2, looksLikeAssetPath as c3, registerAssetBuildTransform as c4, registerComponent as c5, registerComponentAssetFields as c6, registerComponentEntityFields as c7, registerDrawCallback as c8, registerMaterialCallback as c9, remapEntityFields as ca, shutdownMaterialAPI as cb, toBuildPath as cc, unregisterComponent as cd, unregisterDrawCallback as ce, updateCameraAspectRatio as cf, wrapSceneSystem as cg, PostProcessStack as g, AssetServer as i, loadSpineModule as l, BlendMode as o, Added as r, wrapSpineModule as w };
+export type { BuiltinComponentDef as B, ComponentDef as C, AssetBundle as D, AssetContentType as E, AssetFieldType as F, AssetTypeEntry as G, InstantiatePrefabResult as I, BitmapTextData as J, CameraData as L, MaskProcessorFn as M, CameraRenderParams as N, Plugin as P, CanvasData as Q, ResourceDef as R, SpineModuleFactory as S, ChangedWrapper as U, ChildrenData as X, CommandsDescriptor as _, ComponentData as a0, DrawCallback as a1, EditorAssetType as a2, EventDef as a5, EventReaderDescriptor as a7, PostProcessVolumeData as aB, PrefabData as aC, PrefabEntityData as aD, QueryBuilder as aG, QueryDescriptor as aH, QueryResult as aJ, RemovedQueryDescriptor as aL, RenderParams as aN, ResDescriptor as aQ, ResMutDescriptor as aS, SceneComponentData as aV, SceneContext as aW, SceneEntityData as aX, SceneLoadOptions as aY, EventWriterDescriptor as ab, FileLoadOptions as ad, GetWorldDescriptor as af, InferParam as ag, InferParams as ah, InstantiatePrefabOptions as ai, LoadedMaterial as aj, LocalTransformData as al, MaterialAssetData as an, MaterialOptions as ap, MutWrapper as ar, NameData as at, ParentData as av, ParticleEmitterData as ay, PluginDependency as az, SpineEvent as b, SceneOwnerData as b0, SceneStatus as b1, ShaderLoader as b3, SliceBorder$1 as b6, SpineAnimationData as b8, SpineDescriptor as b9, SpineLoadResult as ba, SpineRendererFn as bb, SpriteData as bd, SystemDef as be, SystemOptions as bf, SystemParam as bg, TextureInfo as bi, TextureRef as bj, TimeData as bl, TransformData as bn, TransitionOptions as bo, UniformValue as bp, VelocityData as br, WorldTransformData as bt, SpineEventCallback as c, SpineEventType as d, SpineWasmModule as e, SpineWrappedAPI as f, ShaderHandle as h, PrefabOverride as j, SceneData as k, AddressableManifest as m, SceneConfig as n, MaterialHandle as p, WebAppOptions as q, AddedWrapper as s, AddressableAssetType as t, AddressableManifestAsset as u, AddressableManifestGroup as v, AddressableResultMap as x, AnyComponentDef as y, AssetBuildTransform as z };
diff --git a/desktop/public/sdk/esm/shared/index.js b/desktop/public/sdk/esm/shared/index.js
new file mode 100644
index 000000000..9fe140c23
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/index.js
@@ -0,0 +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};
+//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/shared/index.js.map b/desktop/public/sdk/esm/shared/index.js.map
new file mode 100644
index 000000000..25132ca04
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/index.js.map
@@ -0,0 +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":"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"}
\ No newline at end of file
diff --git a/desktop/public/sdk/esm/shared/material.js b/desktop/public/sdk/esm/shared/material.js
new file mode 100644
index 000000000..f1fdf5656
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/material.js
@@ -0,0 +1,2 @@
+const t=1920,e=1080,n=100,i=512,s={x:100,y:100},r="Arial",o=24,a=1.2,c=.5,l=1/60,h={x:0,y:-9.81},u=1/60,d="default",_={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 p(t){t.Text&&(t.Text._default.fontFamily=_.defaultFontFamily),t.TextInput&&(t.TextInput._default.fontFamily=_.defaultFontFamily),t.Canvas&&(t.Canvas._default.scaleMode=_.canvasScaleMode,t.Canvas._default.matchWidthOrHeight=_.canvasMatchWidthOrHeight)}const f={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4};function m(t,e){if(void 0!==e.maxDeltaTime&&(_.maxDeltaTime=e.maxDeltaTime,t.setMaxDeltaTime(e.maxDeltaTime)),void 0!==e.maxFixedSteps&&(_.maxFixedSteps=e.maxFixedSteps,t.setMaxFixedSteps(e.maxFixedSteps)),void 0!==e.textCanvasSize&&(_.textCanvasSize=e.textCanvasSize),void 0!==e.defaultFontFamily&&(_.defaultFontFamily=e.defaultFontFamily),void 0!==e.sceneTransitionDuration&&(_.sceneTransitionDuration=e.sceneTransitionDuration),e.sceneTransitionColor){const t=e.sceneTransitionColor.replace("#","");_.sceneTransitionColor={r:parseInt(t.substring(0,2),16)/255,g:parseInt(t.substring(2,4),16)/255,b:parseInt(t.substring(4,6),16)/255,a:1}}void 0!==e.canvasScaleMode&&(_.canvasScaleMode=f[e.canvasScaleMode]??1),void 0!==e.canvasMatchWidthOrHeight&&(_.canvasMatchWidthOrHeight=e.canvasMatchWidthOrHeight),void 0!==e.assetLoadTimeout&&(_.assetLoadTimeout=e.assetLoadTimeout),void 0!==e.assetFailureCooldown&&(_.assetFailureCooldown=e.assetFailureCooldown)}const g=0,y=4294967295,w=4294967295,v=0,b=(t=0,e=0)=>({x:t,y:e}),x=(t=0,e=0,n=0)=>({x:t,y:e,z:n}),C=(t=0,e=0,n=0,i=1)=>({x:t,y:e,z:n,w:i}),M=(t=1,e=1,n=1,i=1)=>({r:t,g:e,b:n,a:i}),R=(t=1,e=0,n=0,i=0)=>({w:t,x:e,y:n,z:i});function T(t){if(null===t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(T);const e={};for(const n in t)e[n]=T(t[n]);return e}let S=0;function k(t,e){const n=++S,i=function(t){for(const e in t){const n=t[e];if(null!==n&&"object"==typeof n)return!0}return!1}(e);return{_id:Symbol(`Component_${n}_${t}`),_name:t,_default:e,_builtin:!1,create:t=>i?t?{...T(e),...t}:T(e):t?{...e,...t}:{...e}}}function A(){const t=globalThis;return t.__esengine_componentRegistry??(t.__esengine_componentRegistry=new Map)}function E(t,e){const n=j.get(t)??A().get(t);if(n)return n;const i=k(t,e);return A().set(t,i),j.set(t,i),z(t,e,!1),i}function P(t){const e=j.get(t)??A().get(t);if(e)return e;const n=k(t,{});return A().set(t,n),j.set(t,n),z(t,{},!0),n}function B(t){return A().get(t)}function F(){const t=A();for(const e of t.keys())j.delete(e);t.clear()}function $(t){A().delete(t),j.delete(t)}function z(t,e,n){const i=globalThis;i.__esengine_registerComponent&&i.__esengine_registerComponent(t,e,n)}function I(t){return!0===t._builtin}const j=new Map;function O(t,e){j.set(t,e)}function D(t){return j.get(t)??B(t)}function U(t,e){const n={_id:Symbol(`Builtin_${t}`),_name:t,_cppName:t,_builtin:!0,_default:e};return j.set(t,n),n}const q={Perspective:0,Orthographic:1},N={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},H={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},W=U("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}}),V=W,L=W,G=U("Sprite",{texture:y,color:{r:1,g:1,b:1,a:1},size:{x:s.x,y:s.y},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),X=U("Camera",{projectionType:q.Orthographic,fov:60,orthoSize:540,nearPlane:.1,farPlane:1e3,aspectRatio:1.77,isActive:!0,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:N.ColorAndDepth}),K=U("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:H.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Y=U("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),J=U("Parent",{entity:0}),Q=U("Children",{entities:[]}),Z=U("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:w,enabled:!0}),tt=U("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},nt={World:0,Local:1},it={Linear:0,EaseIn:1,EaseOut:2,EaseInOut:3},st=U("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:it.Linear,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:it.Linear,rotationMin:0,rotationMax:0,angularVelocityMin:0,angularVelocityMax:0,gravity:{x:0,y:0},damping:0,texture:y,spriteColumns:1,spriteRows:1,spriteFPS:10,spriteLoop:!0,blendMode:1,layer:0,material:0,simulationSpace:nt.World,enabled:!0}),rt=E("Name",{value:""}),ot=E("SceneOwner",{scene:"",persistent:!1}),at=E("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0});function ct(t){const e=D(t);return e?T(e._default):null}const lt=U("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ht=U("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=U("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),dt=U("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1,enabled:!0,categoryBits:1,maskBits:65535}),_t={Static:0,Kinematic:1,Dynamic:2};let pt=0;function ft(t,e){const n=++pt;return{_id:Symbol(`Resource_${n}_${e??""}`),_name:e??`Resource_${n}`,_default:t}}function mt(t){return{_type:"res",_resource:t}}function gt(t){return{_type:"res_mut",_resource:t}}class yt{constructor(t,e){this.value_=t,this.setter_=e}get(){return this.value_}set(t){this.value_=t,this.setter_(t)}modify(t){t(this.value_),this.setter_(this.value_)}updateValue(t){this.value_=t}}class wt{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(t,e){this.resources_.set(t._id,e)}get(t){return this.resources_.has(t._id)||this.resources_.set(t._id,t._default),this.resources_.get(t._id)}set(t,e){this.resources_.set(t._id,e)}has(t){return this.resources_.has(t._id)}remove(t){this.resources_.delete(t._id),this.resMutPool_.delete(t._id)}getResMut(t){let e=this.resMutPool_.get(t._id);return e?(e.updateValue(this.get(t)),e):(e=new yt(this.get(t),e=>this.set(t,e)),this.resMutPool_.set(t._id,e),e)}}const vt=ft({delta:0,elapsed:0,frameCount:0},"Time");function bt(t,e,n){const i=[];for(const[t,s]of Object.entries(n)){if(!(t in e)){i.push({field:t,expected:"field to exist in component definition",actual:"unknown field",value:s});continue}const n=xt(e[t]),r=xt(s);"null"!==n&&"undefined"!==n&&(n!==r&&null!=s&&i.push({field:t,expected:n,actual:r,value:s}))}return i}function xt(t){return null===t?"null":void 0===t?"undefined":Array.isArray(t)?"array":typeof t}function Ct(t,e){const n=[`Invalid component data for "${t}":`];for(const t of e)n.push(` - Field "${t.field}": expected ${t.expected}, got ${t.actual} (${JSON.stringify(t.value)})`);return n.join("\n")}let Mt=null;function Rt(t){Mt=t}function Tt(t,e){console.error(`[ESEngine] WASM error in ${e}:`,t),Mt&&Mt(t,e)}function St(t){let e=!1;for(const n of Object.keys(t)){const i=t[n];if(null!=i&&"object"==typeof i&&!Array.isArray(i)){if("r"in i&&"g"in i&&"b"in i&&"a"in i&&!("x"in i)){e=!0;break}}}if(!e)return t;const n={};for(const e of Object.keys(t)){const i=t[e];if(null==i||"object"!=typeof i||Array.isArray(i))n[e]=i;else{const t=i;n[e]="r"in t&&"g"in t&&"b"in t&&"a"in t&&!("x"in t)?{x:t.r,y:t.g,z:t.b,w:t.a}:i}}return n}let kt=1;const At=new WeakMap;function Et(t){let e=At.get(t);return void 0===e&&(e=kt++,At.set(t,e)),e}const Pt=[];function Bt(t,e=[],n=[]){Pt.length=0;for(const e of t)Pt.push(Et(e));Pt.sort((t,e)=>t-e);let i=Pt.join(",");if(e.length>0){Pt.length=0;for(const t of e)Pt.push(Et(t));Pt.sort((t,e)=>t-e),i+="|+"+Pt.join(",")}if(n.length>0){Pt.length=0;for(const t of n)Pt.push(Et(t));Pt.sort((t,e)=>t-e),i+="|-"+Pt.join(",")}return i}class Ft{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(t,e){this.cppRegistry_=t,this.module_=e??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 t;if(this.cppRegistry_)try{t=this.cppRegistry_.create()}catch(t){throw Tt(t,"spawn"),t}else t=++this.nextEntityId_;let e=0;if(this.module_&&this.cppRegistry_)try{e=this.module_.registry_getGeneration(this.cppRegistry_,t)}catch{}else e=++this.nextGeneration_;this.entities_.set(t,e),this.worldVersion_++;for(const e of this.spawnCallbacks_)try{e(t)}catch{}return t}despawn(t){if(this.isIterating())throw new Error("Cannot despawn entity during query iteration. Use Commands to defer entity destruction until after iteration completes.");for(const e of this.despawnCallbacks_)try{e(t)}catch{}if(this.cppRegistry_)try{this.cppRegistry_.destroy(t)}catch(e){Tt(e,`despawn(entity=${t})`)}this.entities_.delete(t),this.worldVersion_++;const e=this.entityComponents_.get(t);if(e){for(const n of e){this.tsStorage_.get(n)?.delete(t),this.componentAddedTicks_.get(n)?.delete(t),this.componentChangedTicks_.get(n)?.delete(t);let e=this.componentRemovedBuffer_.get(n);e||(e=[],this.componentRemovedBuffer_.set(n,e)),e.push({entity:t,tick:this.worldTick_})}this.entityComponents_.delete(t)}}onSpawn(t){return this.spawnCallbacks_.push(t),()=>{const e=this.spawnCallbacks_.indexOf(t);-1!==e&&this.spawnCallbacks_.splice(e,1)}}onDespawn(t){return this.despawnCallbacks_.push(t),()=>{const e=this.despawnCallbacks_.indexOf(t);-1!==e&&this.despawnCallbacks_.splice(e,1)}}valid(t){return this.cppRegistry_?this.cppRegistry_.valid(t):this.entities_.has(t)}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(t,e){if(this.cppRegistry_)try{this.cppRegistry_.setParent(t,e)}catch(n){Tt(n,`setParent(child=${t}, parent=${e})`)}}removeParent(t){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(t)}catch(e){Tt(e,`removeParent(entity=${t})`)}}insert(t,e,n){return I(e)?this.insertBuiltin(t,e,n):this.insertScript(t,e,n)}set(t,e,n){if(I(e)){if(this.cppRegistry_)try{const i=e._default,s=n;let r=s;for(const t of Object.keys(s))t in i||(r===s&&(r={...s}),delete r[t]);this.getBuiltinMethods(e._cppName).add(t,St(r))}catch(n){Tt(n,`set(${e._name}, entity=${t})`)}this.recordChangedTick_(e,t)}else this.getStorage(e).set(t,n),this.recordChangedTick_(e,t)}get(t,e){return I(e)?this.getBuiltin(t,e):this.getScript(t,e)}has(t,e){return I(e)?this.hasBuiltin(t,e):this.hasScript(t,e)}tryGet(t,e){if(I(e)){if(!this.cppRegistry_)return null;try{const n=this.getBuiltinMethods(e._cppName);return n.has(t)?n.get(t):null}catch(n){return Tt(n,`tryGet(${e._name}, entity=${t})`),null}}return this.hasScript(t,e)?this.getScript(t,e):null}remove(t,e){if(this.isIterating())throw new Error("Cannot remove component during query iteration. Use Commands to defer component removal until after iteration completes.");I(e)?this.removeBuiltin(t,e):this.removeScript(t,e)}getBuiltinMethods(t){let e=this.builtinMethodCache_.get(t);if(e)return e;const n=this.cppRegistry_,i=n[`add${t}`],s=n[`get${t}`],r=n[`has${t}`],o=n[`remove${t}`];if("function"!=typeof i||"function"!=typeof s||"function"!=typeof r||"function"!=typeof o)throw new Error(`C++ Registry missing methods for component "${t}". Expected: add${t}, get${t}, has${t}, remove${t}`);return e={add:i.bind(n),get:s.bind(n),has:r.bind(n),remove:o.bind(n)},this.builtinMethodCache_.set(t,e),e}insertBuiltin(t,e,n){const i=e._default,s={};if(null!=n&&"object"==typeof n){for(const[t,e]of Object.entries(n))void 0!==e&&t in i&&(s[t]=e);const t=bt(e._name,i,s);if(t.length>0)throw new Error(Ct(e._name,t))}const r={...e._default,...s};let o=!0;if(this.cppRegistry_)try{const n=this.getBuiltinMethods(e._cppName);o=!n.has(t),n.add(t,St(r))}catch(n){Tt(n,`insertBuiltin(${e._name}, entity=${t})`)}return o&&(this.worldVersion_++,this.recordAddedTick_(e,t)),this.recordChangedTick_(e,t),r}getBuiltin(t,e){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return function(t,e){let n=!1;for(const i of Object.keys(e)){const s=e[i];if(null!=s&&"object"==typeof s&&!Array.isArray(s)&&"r"in s&&"g"in s&&"b"in s&&"a"in s){const e=t[i];if(null!=e&&"object"==typeof e&&"x"in e&&!("r"in e)){n=!0;break}}}if(!n)return t;const i={};for(const n of Object.keys(t)){const s=t[n],r=e[n];if(null==s||"object"!=typeof s||Array.isArray(s)||null==r||"object"!=typeof r||Array.isArray(r))i[n]=s;else{const t=s,e=r;i[n]="r"in e&&"g"in e&&"b"in e&&"a"in e&&"x"in t&&!("r"in t)?{r:t.x,g:t.y,b:t.z,a:t.w}:s}}return i}(this.getBuiltinMethods(e._cppName).get(t),e._default)}catch(n){return Tt(n,`getBuiltin(${e._name}, entity=${t})`),{...e._default}}}hasBuiltin(t,e){if(!this.cppRegistry_)return!1;try{return this.getBuiltinMethods(e._cppName).has(t)}catch(n){return Tt(n,`hasBuiltin(${e._name}, entity=${t})`),!1}}removeBuiltin(t,e){if(this.cppRegistry_){try{this.getBuiltinMethods(e._cppName).remove(t)}catch(n){Tt(n,`removeBuiltin(${e._name}, entity=${t})`)}this.recordRemovedTick_(e,t),this.worldVersion_++}}insertScript(t,e,n){let i;if(null!=n&&"object"==typeof n){const t={};for(const[e,i]of Object.entries(n))void 0!==i&&(t[e]=i);const s=bt(e._name,e._default,t);if(s.length>0)throw new Error(Ct(e._name,s));i=t}const s=e.create(i),r=this.getStorage(e),o=!r.has(t);r.set(t,s);let a=this.entityComponents_.get(t);return a||(a=[],this.entityComponents_.set(t,a)),-1===a.indexOf(e._id)&&a.push(e._id),o&&(this.worldVersion_++,this.recordAddedTick_(e,t)),this.recordChangedTick_(e,t),s}getScript(t,e){const n=this.tsStorage_.get(e._id);if(!n)throw new Error(`Component not found: ${e._name}`);return n.get(t)}hasScript(t,e){const n=this.tsStorage_.get(e._id);return n?.has(t)??!1}removeScript(t,e){const n=this.tsStorage_.get(e._id);n?.delete(t),this.recordRemovedTick_(e,t),this.worldVersion_++;const i=this.entityComponents_.get(t);if(i){const t=i.indexOf(e._id);-1!==t&&i.splice(t,1)}}getStorage(t){let e=this.tsStorage_.get(t._id);return e||(e=new Map,this.tsStorage_.set(t._id,e)),e}resetQueryPool(){this.queryPoolIdx_=0}getComponentTypes(t){const e=new Set;for(const[n,i]of this.builtinMethodCache_)try{i.has(t)&&e.add(n)}catch{}if(this.cppRegistry_)for(const[n,i]of j)if(I(i)&&!e.has(n))try{this.getBuiltinMethods(i._cppName).has(t)&&e.add(n)}catch{}const n=this.entityComponents_.get(t);if(n){const t=A();for(const i of n)for(const[n,s]of t)if(s._id===i){e.add(n);break}}return Array.from(e)}getEntitiesWithComponents(t,e=[],n=[],i){if(0===t.length&&0===e.length&&0===n.length)return this.getAllEntities();const s=i??Bt(t,e,n),r=this.queryCache_.get(s);if(r&&r.version===this.worldVersion_)return r.result;let o=null,a=1/0;for(const e of t)if(!I(e)){const t=this.tsStorage_.get(e._id),n=t?t.size:0;n<a&&(a=n,o=t??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const c=this.queryPool_[this.queryPoolIdx_++];c.length=0;const l=o?o.keys():this.entities_.keys();for(const i of l){let s=!0;for(const e of t)if(!this.has(i,e)){s=!1;break}if(s)for(const t of e)if(!this.has(i,t)){s=!1;break}if(s)for(const t of n)if(this.has(i,t)){s=!1;break}s&&c.push(i)}return this.queryCache_.set(s,{version:this.worldVersion_,result:c.slice()}),c}advanceTick(){this.worldTick_++}getWorldTick(){return this.worldTick_}isAddedSince(t,e,n){const i=this.componentAddedTicks_.get(e._id);if(!i)return!1;const s=i.get(t);return void 0!==s&&s>n}isChangedSince(t,e,n){const i=this.componentChangedTicks_.get(e._id);if(!i)return!1;const s=i.get(t);return void 0!==s&&s>n}getRemovedEntitiesSince(t,e){const n=this.componentRemovedBuffer_.get(t._id);if(!n)return[];const i=[];for(const t of n)t.tick>e&&i.push(t.entity);return i}cleanRemovedBuffer(t){for(const[e,n]of this.componentRemovedBuffer_){let i=0;for(let e=0;e<n.length;e++)n[e].tick>=t&&(n[i++]=n[e]);n.length=i,0===i&&this.componentRemovedBuffer_.delete(e)}}recordAddedTick_(t,e){let n=this.componentAddedTicks_.get(t._id);n||(n=new Map,this.componentAddedTicks_.set(t._id,n)),n.set(e,this.worldTick_)}recordChangedTick_(t,e){let n=this.componentChangedTicks_.get(t._id);n||(n=new Map,this.componentChangedTicks_.set(t._id,n)),n.set(e,this.worldTick_)}recordRemovedTick_(t,e){let n=this.componentRemovedBuffer_.get(t._id);n||(n=[],this.componentRemovedBuffer_.set(t._id,n)),n.push({entity:e,tick:this.worldTick_}),this.componentAddedTicks_.get(t._id)?.delete(e),this.componentChangedTicks_.get(t._id)?.delete(e)}}function $t(t){return{_type:"mut",_component:t}}function zt(t){return"object"==typeof t&&null!==t&&"_type"in t&&"mut"===t._type}function It(t){return{_filterType:"added",_component:t}}function jt(t){return{_filterType:"changed",_component:t}}function Ot(t){return"object"==typeof t&&null!==t&&"_filterType"in t&&"added"===t._filterType}function Dt(t){return"object"==typeof t&&null!==t&&"_filterType"in t&&"changed"===t._filterType}function Ut(t){return zt(t)||Ot(t)||Dt(t)?t._component:t}function qt(t,e=[],n=[]){const i=[],s=[],r=[];return t.forEach((t,e)=>{zt(t)&&i.push(e),Ot(t)?s.push({index:e,component:t._component}):Dt(t)&&r.push({index:e,component:t._component})}),{_type:"query",_components:t,_mutIndices:i,_with:e,_without:n,_addedFilters:s,_changedFilters:r,with:(...i)=>qt(t,[...e,...i],n),without:(...i)=>qt(t,e,[...n,...i])}}function Nt(...t){return qt(t)}class Ht{constructor(t,e,n=-1){this.world_=t,this.descriptor_=e,this.lastRunTick_=n,this.actualComponents_=e._components.map(Ut),this.allRequired_=this.actualComponents_.concat(e._with),this.result_=new Array(this.actualComponents_.length+1),this.mutData_=e._mutIndices.map(t=>({component:this.actualComponents_[t],data:null})),this.cacheKey_=Bt(this.allRequired_,e._with,e._without)}passesChangeFilters_(t){const{_addedFilters:e,_changedFilters:n}=this.descriptor_;if(0===e.length&&0===n.length)return!0;const i=this.lastRunTick_;for(const n of e)if(!this.world_.isAddedSince(t,n.component,i))return!1;for(const e of n)if(!this.world_.isChangedSince(t,e.component,i))return!1;return!0}*[Symbol.iterator](){const{_mutIndices:t}=this.descriptor_,e=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without,this.cacheKey_),i=e.length,s=t.length>0,r=this.descriptor_._addedFilters.length>0||this.descriptor_._changedFilters.length>0,o=this.result_,a=this.mutData_,c=a.length;let l=null;this.world_.beginIteration();try{for(const h of n)if(!r||this.passesChangeFilters_(h)){if(null!==l&&s)for(let t=0;t<c;t++){const e=a[t];this.world_.set(l,e.component,e.data)}o[0]=h;for(let t=0;t<i;t++)o[t+1]=this.world_.get(h,e[t]);if(s){for(let e=0;e<c;e++)a[e].data=o[t[e]+1];l=h}yield o}}finally{if(this.world_.endIteration(),null!==l&&s)for(let t=0;t<c;t++){const e=a[t];this.world_.set(l,e.component,e.data)}}}forEach(t){for(const[e,...n]of this)t(e,...n)}single(){for(const t of this)return t;return null}isEmpty(){return null===this.single()}count(){return this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without).length}toArray(){const t=[];for(const e of this)t.push([...e]);return t}}function Wt(t){return{_type:"removed",_component:t}}class Vt{constructor(t,e,n){this.world_=t,this.component_=e,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 Lt(){return{_type:"commands"}}class Gt{constructor(t,e){this.components_=[],this.commands_=t,null===e?(this.entityRef_={entity:0},this.isNew_=!0):(this.entityRef_={entity:e},this.isNew_=!1)}insert(t,e){let n;return n=I(t)?{...t._default,...e}:t.create(e),this.isNew_?this.components_.push({component:t,data:n}):this.commands_.queueInsert(this.entityRef_.entity,t,n),this}remove(t){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,t),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 Xt{constructor(t,e){this.pending_=[],this.spawned_=[],this.world_=t,this.resources_=e}spawn(){const t=new Gt(this,null);return this.spawned_.push(t),t}entity(t){return new Gt(this,t)}despawn(t){return this.pending_.push({type:"despawn",entity:t}),this}insertResource(t,e){return this.pending_.push({type:"insert_resource",resource:t,value:e}),this}queueInsert(t,e,n){this.pending_.push({type:"insert",entity:t,component:e,data:n})}queueRemove(t,e){this.pending_.push({type:"remove",entity:t,component:e})}spawnImmediate(t,e){const n=this.world_.spawn();e.entity=n;for(const e of t)this.world_.insert(n,e.component,e.data)}flush(){for(const t of this.spawned_)t.finalize();this.spawned_.length=0;for(const t of this.pending_)this.executeCommand(t);this.pending_.length=0}executeCommand(t){switch(t.type){case"despawn":if(!this.world_.valid(t.entity)){console.warn(`[Commands] despawn skipped: entity ${t.entity} is already invalid`);break}this.world_.despawn(t.entity);break;case"insert":if(!this.world_.valid(t.entity)){console.warn(`[Commands] insert skipped: entity ${t.entity} is invalid`);break}this.world_.insert(t.entity,t.component,t.data);break;case"remove":if(!this.world_.valid(t.entity)){console.warn(`[Commands] remove skipped: entity ${t.entity} is invalid`);break}this.world_.remove(t.entity,t.component);break;case"insert_resource":this.resources_.insert(t.resource,t.value)}}}function Kt(t){return{_id:Symbol(`Event_${t}`),_name:t}}class Yt{constructor(){this.readBuffer_=[],this.writeBuffer_=[]}send(t){this.writeBuffer_.push(t)}getReadBuffer(){return this.readBuffer_}swap(){const t=this.readBuffer_;this.readBuffer_=this.writeBuffer_,this.writeBuffer_=t,this.writeBuffer_.length=0}}class Jt{constructor(){this.buses_=new Map}register(t){this.buses_.has(t._id)||this.buses_.set(t._id,new Yt)}getBus(t){let e=this.buses_.get(t._id);return e||(e=new Yt,this.buses_.set(t._id,e)),e}swapAll(){for(const t of this.buses_.values())t.swap()}}function Qt(t){return{_type:"event_writer",_event:t}}function Zt(t){return{_type:"event_reader",_event:t}}class te{constructor(t){this.bus_=t}send(t){this.bus_.send(t)}}class ee{constructor(t){this.bus_=t}*[Symbol.iterator](){yield*this.bus_.getReadBuffer()}isEmpty(){return 0===this.bus_.getReadBuffer().length}toArray(){return[...this.bus_.getReadBuffer()]}}var ne;function ie(){return{_type:"get_world"}}!function(t){t[t.Startup=0]="Startup",t[t.First=1]="First",t[t.PreUpdate=2]="PreUpdate",t[t.Update=3]="Update",t[t.PostUpdate=4]="PostUpdate",t[t.Last=5]="Last",t[t.FixedPreUpdate=10]="FixedPreUpdate",t[t.FixedUpdate=11]="FixedUpdate",t[t.FixedPostUpdate=12]="FixedPostUpdate"}(ne||(ne={}));let se=0;function re(t,e,n){const i=++se;return{_id:Symbol(`System_${i}_${n?.name??""}`),_params:t,_fn:e,_name:n?.name??`System_${i}`}}function oe(){const t=globalThis;return t.__esengine_pendingSystems??(t.__esengine_pendingSystems=[])}function ae(t){oe().push({schedule:ne.Update,system:t})}function ce(t){oe().push({schedule:ne.Startup,system:t})}function le(t,e){oe().push({schedule:t,system:e})}class he{constructor(t,e,n){this.argsCache_=new Map,this.systemTicks_=new Map,this.currentLastRunTick_=-1,this.timings_=null,this.world_=t,this.resources_=e,this.eventRegistry_=n??null}setTimingEnabled(t){this.timings_=t?new Map:null}getTimings(){return this.timings_}run(t){let e=this.argsCache_.get(t._id);e||(e=new Array(t._params.length),this.argsCache_.set(t._id,e)),this.currentLastRunTick_=this.systemTicks_.get(t._id)??-1;for(let n=0;n<t._params.length;n++)e[n]=this.resolveParam(t._params[n]);const n=this.timings_?performance.now():0;try{t._fn(...e);for(let t=0;t<e.length;t++)e[t]instanceof Xt&&e[t].flush()}finally{this.timings_&&this.timings_.set(t._name,performance.now()-n),this.world_.resetIterationDepth(),this.systemTicks_.set(t._id,this.world_.getWorldTick())}}resolveParam(t){switch(t._type){case"query":return new Ht(this.world_,t,this.currentLastRunTick_);case"res":return this.resources_.get(t._resource);case"res_mut":return this.resources_.getResMut(t._resource);case"commands":return new Xt(this.world_,this.resources_);case"event_writer":{const e=t,n=this.eventRegistry_?this.eventRegistry_.getBus(e._event):(()=>{throw new Error("EventRegistry not available")})();return new te(n)}case"event_reader":{const e=t,n=this.eventRegistry_?this.eventRegistry_.getBus(e._event):(()=>{throw new Error("EventRegistry not available")})();return new ee(n)}case"removed":{const e=t;return new Vt(this.world_,e._component,this.currentLastRunTick_)}case"get_world":return this.world_;default:throw new Error("Unknown system parameter type")}}}var ue;function de(t){return"object"==typeof t&&null!==t&&"__textureRef"in t}!function(t){t[t.Normal=0]="Normal",t[t.Additive=1]="Additive",t[t.Multiply=2]="Multiply",t[t.Screen=3]="Screen",t[t.PremultipliedAlpha=4]="PremultipliedAlpha"}(ue||(ue={}));let _e=null,pe=null,fe=1;const me=new Map;function ge(t){_e=t,pe=t.getResourceManager(),Se()}function ye(){0!==xe&&_e&&(_e._free(xe),xe=0),me.clear(),fe=1,be=!1,Me.clear(),Re=null,pe=null,_e=null}function we(){if(!pe)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return pe}const ve={createShader:(t,e)=>we().createShader(t,e),releaseShader(t){t>0&&we().releaseShader(t)},create(t){const e=fe++,n={shader:t.shader,uniforms:new Map,blendMode:t.blendMode??ue.Normal,depthTest:t.depthTest??!1,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};if(t.uniforms)for(const[e,i]of Object.entries(t.uniforms))n.uniforms.set(e,i);return me.set(e,n),e},get:t=>me.get(t),setUniform(t,e,n){const i=me.get(t);i&&(i.uniforms.set(e,n),i.dirty_=!0,_e?.invalidateMaterialCache(t))},getUniform(t,e){const n=me.get(t);return n?.uniforms.get(e)},setBlendMode(t,e){const n=me.get(t);n&&(n.blendMode=e,_e?.invalidateMaterialCache(t))},getBlendMode(t){const e=me.get(t);return e?.blendMode??ue.Normal},setDepthTest(t,e){const n=me.get(t);n&&(n.depthTest=e,_e?.invalidateMaterialCache(t))},getShader(t){const e=me.get(t);return e?.shader??0},release(t){me.delete(t),_e?.invalidateMaterialCache(t)},isValid:t=>me.has(t),releaseAll(){me.clear(),_e?.clearMaterialCache()},createFromAsset(t,e){const n={};for(const[e,i]of Object.entries(t.properties))if("number"==typeof i)n[e]=i;else if("object"==typeof i&&null!==i){const t=i;"a"in t?n[e]={x:t.r??0,y:t.g??0,z:t.b??0,w:t.a??0}:"w"in t?n[e]={x:t.x??0,y:t.y??0,z:t.z??0,w:t.w??0}:"z"in t?n[e]={x:t.x??0,y:t.y??0,z:t.z??0}:"y"in t&&(n[e]={x:t.x??0,y:t.y??0})}return this.create({shader:e,uniforms:n,blendMode:t.blendMode??ue.Normal,depthTest:t.depthTest??!1})},createInstance(t){const e=me.get(t);if(!e)throw new Error(`Invalid source material: ${t}`);const n=fe++,i={shader:e.shader,uniforms:new Map(e.uniforms),blendMode:e.blendMode,depthTest:e.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return me.set(n,i),n},toAssetData(t,e){const n=me.get(t);if(!n)return null;const i={};for(const[t,e]of n.uniforms)i[t]=e;return{version:"1.0",type:"material",shader:e,blendMode:n.blendMode,depthTest:n.depthTest,properties:i}},getUniforms(t){const e=me.get(t);return e?new Map(e.uniforms):new Map},tex:(t,e)=>({__textureRef:!0,textureId:t,slot:e})};let be=!1,xe=0;const Ce=16384,Me=new Map;let Re=null;function Te(t){const e=(0===xe&&_e&&(xe=_e._malloc(Ce)),xe);if(0===e||!_e)return{ptr:0,count:0};let n=0,i=0;const s=_e.HEAPU8,r=_e.HEAPU32,o=_e.HEAPF32;for(const[a,c]of t){if(de(c))continue;let t=Me.get(a);t||(Re||(Re=new TextEncoder),t=Re.encode(a),Me.set(a,t));const l=t.length,h=4*Math.ceil(l/4);if(n+(4+h+4+16)>Ce){console.warn(`[ESEngine] Material uniform buffer full (${n}/${Ce} bytes), skipping remaining uniforms`);break}r[e+n>>2]=l,n+=4,s.set(t,e+n),n+=h;let u=0,d=[0,0,0,0];if("number"==typeof c)u=0,d[0]=c;else if(Array.isArray(c)){u=Math.min(c.length-1,3);for(let t=0;t<Math.min(c.length,4);t++)d[t]=c[t]}else"w"in c?(u=3,d=[c.x,c.y,c.z,c.w]):"z"in c?(u=2,d=[c.x,c.y,c.z,0]):"y"in c&&(u=1,d=[c.x,c.y,0,0]);r[e+n>>2]=u,n+=4;for(let t=0;t<4;t++)o[e+n>>2]=d[t],n+=4;i++}return{ptr:e,count:i}}function Se(){if(!_e||be)return;_e.materialDataProvider=(t,e,n,i,s)=>{const r=me.get(t);if(!r)return _e.HEAPU32[e>>2]=0,_e.HEAPU32[n>>2]=0,_e.HEAPU32[i>>2]=0,void(_e.HEAPU32[s>>2]=0);_e.HEAPU32[e>>2]=r.shader,_e.HEAPU32[n>>2]=r.blendMode;const{ptr:o,count:a}=Te(r.uniforms);_e.HEAPU32[i>>2]=o,_e.HEAPU32[s>>2]=a},be=!0}const ke={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"};export{jt as $,Q as A,_t as B,ut as C,u as D,Jt as E,h as F,c as G,l as H,g as I,K as J,n as K,N as L,ve as M,rt as N,t as O,at as P,Nt as Q,_ as R,ne as S,W as T,e as U,L as V,Ft as W,ie as X,It as Y,ue as Z,dt as _,tt as a,Lt as a0,Xt as a1,r as a2,o as a3,a as a4,d as a5,s as a6,i as a7,et as a8,Gt as a9,B as aA,I as aB,de as aC,R as aD,Se as aE,$ as aF,b as aG,x as aH,C as aI,Zt as aa,ee as ab,Qt as ac,te as ad,w as ae,v as af,V as ag,$t as ah,it as ai,st as aj,Ht as ak,Wt as al,Vt as am,ke as an,nt as ao,Y as ap,ce as aq,ae as ar,le as as,m as at,p as au,F as av,M as aw,Kt as ax,P as ay,ct as az,E as b,G as c,ft as d,lt as e,ht as f,D as g,X as h,re as i,Tt as j,ot as k,Z as l,gt as m,mt as n,vt as o,wt as p,he as q,ge as r,ye as s,q as t,H as u,Rt as v,U as w,J as x,y,O as z};
+//# sourceMappingURL=material.js.map
diff --git a/desktop/public/sdk/esm/shared/material.js.map b/desktop/public/sdk/esm/shared/material.js.map
new file mode 100644
index 000000000..daea9b378
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/material.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"material.js","sources":["../../src/defaults.ts","../../src/types.ts","../../src/component.ts","../../src/physics/PhysicsComponents.ts","../../src/resource.ts","../../src/validation.ts","../../src/wasmError.ts","../../src/world.ts","../../src/query.ts","../../src/commands.ts","../../src/event.ts","../../src/system.ts","../../src/blend.ts","../../src/material.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["DEFAULT_DESIGN_WIDTH","DEFAULT_DESIGN_HEIGHT","DEFAULT_PIXELS_PER_UNIT","DEFAULT_TEXT_CANVAS_SIZE","DEFAULT_SPRITE_SIZE","x","y","DEFAULT_FONT_FAMILY","DEFAULT_FONT_SIZE","DEFAULT_LINE_HEIGHT","DEFAULT_MAX_DELTA_TIME","DEFAULT_FALLBACK_DT","DEFAULT_GRAVITY","DEFAULT_FIXED_TIMESTEP","DEFAULT_SPINE_SKIN","RuntimeConfig","sceneTransitionDuration","sceneTransitionColor","r","g","b","a","defaultFontFamily","canvasScaleMode","canvasMatchWidthOrHeight","maxDeltaTime","maxFixedSteps","textCanvasSize","assetLoadTimeout","assetFailureCooldown","applyRuntimeConfig","components","Text","_default","fontFamily","TextInput","Canvas","scaleMode","matchWidthOrHeight","CANVAS_SCALE_MODE_MAP","FixedWidth","FixedHeight","Expand","Shrink","Match","applyBuildRuntimeConfig","app","config","undefined","setMaxDeltaTime","setMaxFixedSteps","hex","replace","parseInt","substring","INVALID_ENTITY","INVALID_TEXTURE","INVALID_FONT","INVALID_MATERIAL","vec2","vec3","z","vec4","w","color","quat","deepClone","value","Array","isArray","map","result","key","componentCounter","createComponentDef","name","defaults","id","needsDeepClone","obj","val","hasNestedObjects","_id","Symbol","_name","_builtin","create","data","getComponentRegistry","globalThis","__esengine_componentRegistry","Map","defineComponent","existing","componentRegistry","get","def","set","registerToEditor","defineTag","getUserComponent","clearUserComponents","userRegistry","keys","delete","clear","unregisterComponent","isTag","__esengine_registerComponent","isBuiltinComponent","comp","registerComponent","getComponent","defineBuiltin","_cppName","ProjectionType","Perspective","Orthographic","ClearFlags","None","ColorOnly","DepthOnly","ColorAndDepth","ScaleMode","Transform","position","rotation","scale","worldPosition","worldRotation","worldScale","LocalTransform","WorldTransform","Sprite","texture","size","uvOffset","uvScale","layer","flipX","flipY","material","enabled","Camera","projectionType","fov","orthoSize","nearPlane","farPlane","aspectRatio","isActive","priority","showFrustum","viewportX","viewportY","viewportW","viewportH","clearFlags","designResolution","pixelsPerUnit","backgroundColor","Velocity","linear","angular","Parent","entity","Children","entities","BitmapText","text","fontSize","align","spacing","font","SpineAnimation","skeletonPath","atlasPath","skin","animation","timeScale","loop","playing","skeletonScale","EmitterShape","Point","Circle","Rectangle","Cone","SimulationSpace","World","Local","ParticleEasing","Linear","EaseIn","EaseOut","EaseInOut","ParticleEmitter","rate","burstCount","burstInterval","duration","looping","playOnStart","maxParticles","lifetimeMin","lifetimeMax","shape","shapeRadius","shapeSize","shapeAngle","speedMin","speedMax","angleSpreadMin","angleSpreadMax","startSizeMin","startSizeMax","endSizeMin","endSizeMax","sizeEasing","startColor","endColor","colorEasing","rotationMin","rotationMax","angularVelocityMin","angularVelocityMax","gravity","damping","spriteColumns","spriteRows","spriteFPS","spriteLoop","blendMode","simulationSpace","Name","SceneOwner","scene","persistent","PostProcessVolume","effects","isGlobal","weight","blendDistance","getComponentDefaults","typeName","RigidBody","bodyType","gravityScale","linearDamping","angularDamping","fixedRotation","bullet","BoxCollider","halfExtents","offset","density","friction","restitution","isSensor","categoryBits","maskBits","CircleCollider","radius","CapsuleCollider","halfHeight","BodyType","Static","Kinematic","Dynamic","resourceCounter","defineResource","defaultValue","Res","resource","_type","_resource","ResMut","ResMutInstance","constructor","setter","this","value_","setter_","modify","fn","updateValue","ResourceStorage","resources_","resMutPool_","insert","has","remove","getResMut","instance","v","Time","delta","elapsed","frameCount","validateComponentData","componentName","errors","field","Object","entries","push","expected","actual","expectedType","getType","actualType","formatValidationErrors","lines","err","JSON","stringify","join","errorHandler","setWasmErrorHandler","handler","handleWasmError","error","context","console","convertForWasm","needsConversion","rec","nextCompNumId_","compNumIds_","WeakMap","getCompNumId","_keyIds","computeQueryCacheKey","withFilters","withoutFilters","length","c","sort","cppRegistry_","module_","entities_","tsStorage_","entityComponents_","queryPool_","queryPoolIdx_","worldVersion_","queryCache_","builtinMethodCache_","iterationDepth_","nextEntityId_","nextGeneration_","spawnCallbacks_","despawnCallbacks_","worldTick_","componentAddedTicks_","componentChangedTicks_","componentRemovedBuffer_","connectCpp","cppRegistry","module","disconnectCpp","hasCpp","getCppRegistry","spawn","isIterating","Error","e","generation","registry_getGeneration","cb","despawn","destroy","ids","buffer","tick","onSpawn","callback","idx","indexOf","splice","onDespawn","valid","entityCount","getWorldVersion","beginIteration","endIteration","warn","resetIterationDepth","getAllEntities","from","setParent","child","parent","removeParent","component","insertBuiltin","insertScript","raw","wasmData","k","getBuiltinMethods","add","recordChangedTick_","getStorage","getBuiltin","getScript","hasBuiltin","hasScript","tryGet","methods","removeBuiltin","removeScript","cppName","reg","addFn","getFn","hasFn","removeFn","bind","filtered","merged","isNew","recordAddedTick_","valRec","defRec","convertFromWasm","recordRemovedTick_","clean","storage","resetQueryPool","getComponentTypes","types","Set","registry","getEntitiesWithComponents","precomputedKey","cacheKey","cached","version","smallestPool","smallestSize","Infinity","candidates","match","slice","advanceTick","getWorldTick","isAddedSince","sinceTick","isChangedSince","getRemovedEntitiesSince","entry","cleanRemovedBuffer","beforeTick","writeIdx","i","Mut","_component","isMutWrapper","Added","_filterType","Changed","isAddedWrapper","isChangedWrapper","unwrapComponent","createQueryDescriptor","mutIndices","addedFilters","changedFilters","forEach","index","_components","_mutIndices","_with","_without","_addedFilters","_changedFilters","with","extraWith","without","extraWithout","Query","QueryInstance","world","descriptor","lastRunTick","world_","descriptor_","lastRunTick_","actualComponents_","allRequired_","concat","result_","mutData_","cacheKey_","passesChangeFilters_","f","iterator","actualComponents","compCount","hasMut","hasChangeFilters","mutData","mutCount","prevEntity","mut","single","isEmpty","count","toArray","arr","row","Removed","RemovedQueryInstance","component_","Commands","EntityCommands","commands","components_","commands_","entityRef_","isNew_","queueInsert","queueRemove","finalize","spawnImmediate","CommandsInstance","resources","pending_","spawned_","ec","type","insertResource","entityRef","flush","cmd","executeCommand","defineEvent","EventBus","readBuffer_","writeBuffer_","send","event","getReadBuffer","swap","tmp","EventRegistry","buses_","register","getBus","bus","swapAll","values","EventWriter","_event","EventReader","EventWriterInstance","bus_","EventReaderInstance","Schedule","GetWorld","systemCounter","defineSystem","params","options","_params","_fn","getPendingSystems","__esengine_pendingSystems","addSystem","system","schedule","Update","addStartupSystem","Startup","addSystemToSchedule","SystemRunner","eventRegistry","argsCache_","systemTicks_","currentLastRunTick_","timings_","eventRegistry_","setTimingEnabled","getTimings","run","args","resolveParam","t0","performance","now","param","desc","BlendMode","isTextureRef","resourceManager","nextMaterialId","materials","initMaterialAPI","wasmModule","getResourceManager","registerMaterialCallback","shutdownMaterialAPI","uniformBuffer","_free","materialCallbackRegistered","encodedNameCache","encoder","Material","createShader","vertexSrc","fragmentSrc","releaseShader","shader","handle","uniforms","Normal","depthTest","dirty_","cachedBuffer_","cachedIdx_","setUniform","invalidateMaterialCache","getUniform","setBlendMode","mode","getBlendMode","setDepthTest","getShader","release","isValid","releaseAll","clearMaterialCache","createFromAsset","shaderHandle","properties","createInstance","source","sourceData","toAssetData","shaderPath","getUniforms","tex","textureId","slot","__textureRef","UNIFORM_BUFFER_SIZE","serializeUniforms","bufferPtr","_malloc","ptr","heap8","HEAPU8","heap32","HEAPU32","heapF32","HEAPF32","nameBytes","TextEncoder","encode","nameLen","namePadded","Math","ceil","min","materialDataProvider","materialId","outShaderIdPtr","outBlendModePtr","outUniformBufferPtr","outUniformCountPtr","ShaderSources","SPRITE_VERTEX","SPRITE_FRAGMENT","COLOR_VERTEX","COLOR_FRAGMENT"],"mappings":"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"}
\ No newline at end of file
diff --git a/desktop/public/sdk/esm/shared/wasm.d.ts b/desktop/public/sdk/esm/shared/wasm.d.ts
new file mode 100644
index 000000000..11fd8b641
--- /dev/null
+++ b/desktop/public/sdk/esm/shared/wasm.d.ts
@@ -0,0 +1,562 @@
+/**
+ * @file types.ts
+ * @brief Core type definitions for ESEngine SDK
+ */
+type Entity = number;
+declare const INVALID_ENTITY: Entity;
+type TextureHandle = number;
+declare const INVALID_TEXTURE: TextureHandle;
+type FontHandle = number;
+declare const INVALID_FONT: FontHandle;
+declare const INVALID_MATERIAL = 0;
+interface Vec2 {
+ x: number;
+ y: number;
+}
+interface Vec3 {
+ x: number;
+ y: number;
+ z: number;
+}
+interface Vec4 {
+ x: number;
+ y: number;
+ z: number;
+ w: number;
+}
+interface Quat {
+ w: number;
+ x: number;
+ y: number;
+ z: number;
+}
+interface Color {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+declare const vec2: (x?: number, y?: number) => Vec2;
+declare const vec3: (x?: number, y?: number, z?: number) => Vec3;
+declare const vec4: (x?: number, y?: number, z?: number, w?: number) => Vec4;
+declare const color: (r?: number, g?: number, b?: number, a?: number) => Color;
+declare const quat: (w?: number, x?: number, y?: number, z?: number) => Quat;
+
+/**
+ * @file wasm.generated.ts
+ * @brief ESEngine WASM Bindings TypeScript Definitions
+ * @details Generated by EHT - DO NOT EDIT
+ */
+
+interface UVec2 {
+ x: number;
+ y: number;
+}
+interface VectorEntity {
+ size(): number;
+ get(index: number): number;
+ push_back(value: number): void;
+ set(index: number, value: number): boolean;
+ delete(): void;
+}
+interface UIRect {
+ anchorMin: Vec2;
+ anchorMax: Vec2;
+ offsetMin: Vec2;
+ offsetMax: Vec2;
+ size: Vec2;
+ pivot: Vec2;
+}
+interface FlexItem {
+ flexGrow: number;
+ flexShrink: number;
+ flexBasis: number;
+ order: number;
+}
+interface BoxCollider {
+ halfExtents: Vec2;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
+}
+interface CircleCollider {
+ radius: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
+}
+interface CapsuleCollider {
+ radius: number;
+ halfHeight: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
+}
+interface ParticleEmitter {
+ rate: number;
+ burstCount: number;
+ burstInterval: number;
+ duration: number;
+ looping: boolean;
+ playOnStart: boolean;
+ maxParticles: number;
+ lifetimeMin: number;
+ lifetimeMax: number;
+ shape: number;
+ shapeRadius: number;
+ shapeSize: Vec2;
+ shapeAngle: number;
+ speedMin: number;
+ speedMax: number;
+ angleSpreadMin: number;
+ angleSpreadMax: number;
+ startSizeMin: number;
+ startSizeMax: number;
+ endSizeMin: number;
+ endSizeMax: number;
+ sizeEasing: number;
+ startColor: Vec4;
+ endColor: Vec4;
+ colorEasing: number;
+ rotationMin: number;
+ rotationMax: number;
+ angularVelocityMin: number;
+ angularVelocityMax: number;
+ gravity: Vec2;
+ damping: number;
+ texture: number;
+ spriteColumns: number;
+ spriteRows: number;
+ spriteFPS: number;
+ spriteLoop: boolean;
+ blendMode: number;
+ layer: number;
+ material: number;
+ simulationSpace: number;
+ enabled: boolean;
+}
+interface Transform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+ worldPosition: Vec3;
+ worldRotation: Quat;
+ worldScale: Vec3;
+}
+interface Velocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+interface SpineAnimation {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Vec4;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+ enabled: boolean;
+}
+interface Interactable {
+ enabled: boolean;
+ blockRaycast: boolean;
+ raycastTarget: boolean;
+}
+interface UIInteraction {
+ hovered: boolean;
+ pressed: boolean;
+ justPressed: boolean;
+ justReleased: boolean;
+}
+interface RigidBody {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+ enabled: boolean;
+}
+interface BitmapText {
+ text: string;
+ color: Vec4;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+ enabled: boolean;
+}
+interface Sprite {
+ texture: number;
+ color: Vec4;
+ size: Vec2;
+ uvOffset: Vec2;
+ uvScale: Vec2;
+ layer: number;
+ flipX: boolean;
+ flipY: boolean;
+ material: number;
+ enabled: boolean;
+}
+interface UIMask {
+ enabled: boolean;
+ mode: number;
+}
+interface FlexContainer {
+ direction: number;
+ wrap: number;
+ justifyContent: number;
+ alignItems: number;
+ gap: Vec2;
+ padding: Vec4;
+}
+interface Parent {
+ entity: number;
+}
+interface Children {
+ entities: VectorEntity;
+}
+interface ScreenSpace {
+}
+interface Canvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+interface Camera {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
+}
+interface Registry {
+ create(): Entity;
+ destroy(entity: Entity): void;
+ valid(entity: Entity): boolean;
+ entityCount(): number;
+ hasUIRect(entity: Entity): boolean;
+ getUIRect(entity: Entity): UIRect;
+ addUIRect(entity: Entity, component: UIRect): void;
+ removeUIRect(entity: Entity): void;
+ hasFlexItem(entity: Entity): boolean;
+ getFlexItem(entity: Entity): FlexItem;
+ addFlexItem(entity: Entity, component: FlexItem): void;
+ removeFlexItem(entity: Entity): void;
+ hasBoxCollider(entity: Entity): boolean;
+ getBoxCollider(entity: Entity): BoxCollider;
+ addBoxCollider(entity: Entity, component: BoxCollider): void;
+ removeBoxCollider(entity: Entity): void;
+ hasCircleCollider(entity: Entity): boolean;
+ getCircleCollider(entity: Entity): CircleCollider;
+ addCircleCollider(entity: Entity, component: CircleCollider): void;
+ removeCircleCollider(entity: Entity): void;
+ hasCapsuleCollider(entity: Entity): boolean;
+ getCapsuleCollider(entity: Entity): CapsuleCollider;
+ addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
+ removeCapsuleCollider(entity: Entity): void;
+ hasParticleEmitter(entity: Entity): boolean;
+ getParticleEmitter(entity: Entity): ParticleEmitter;
+ addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
+ removeParticleEmitter(entity: Entity): void;
+ hasTransform(entity: Entity): boolean;
+ getTransform(entity: Entity): Transform;
+ addTransform(entity: Entity, component: Transform): void;
+ removeTransform(entity: Entity): void;
+ hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): Velocity;
+ addVelocity(entity: Entity, component: Velocity): void;
+ removeVelocity(entity: Entity): void;
+ hasSpineAnimation(entity: Entity): boolean;
+ getSpineAnimation(entity: Entity): SpineAnimation;
+ addSpineAnimation(entity: Entity, component: SpineAnimation): void;
+ removeSpineAnimation(entity: Entity): void;
+ hasInteractable(entity: Entity): boolean;
+ getInteractable(entity: Entity): Interactable;
+ addInteractable(entity: Entity, component: Interactable): void;
+ removeInteractable(entity: Entity): void;
+ hasUIInteraction(entity: Entity): boolean;
+ getUIInteraction(entity: Entity): UIInteraction;
+ addUIInteraction(entity: Entity, component: UIInteraction): void;
+ removeUIInteraction(entity: Entity): void;
+ hasRigidBody(entity: Entity): boolean;
+ getRigidBody(entity: Entity): RigidBody;
+ addRigidBody(entity: Entity, component: RigidBody): void;
+ removeRigidBody(entity: Entity): void;
+ hasBitmapText(entity: Entity): boolean;
+ getBitmapText(entity: Entity): BitmapText;
+ addBitmapText(entity: Entity, component: BitmapText): void;
+ removeBitmapText(entity: Entity): void;
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): Sprite;
+ addSprite(entity: Entity, component: Sprite): void;
+ removeSprite(entity: Entity): void;
+ hasUIMask(entity: Entity): boolean;
+ getUIMask(entity: Entity): UIMask;
+ addUIMask(entity: Entity, component: UIMask): void;
+ removeUIMask(entity: Entity): void;
+ hasFlexContainer(entity: Entity): boolean;
+ getFlexContainer(entity: Entity): FlexContainer;
+ addFlexContainer(entity: Entity, component: FlexContainer): void;
+ removeFlexContainer(entity: Entity): void;
+ hasParent(entity: Entity): boolean;
+ getParent(entity: Entity): Parent;
+ addParent(entity: Entity, component: Parent): void;
+ removeParent(entity: Entity): void;
+ hasChildren(entity: Entity): boolean;
+ getChildren(entity: Entity): Children;
+ addChildren(entity: Entity, component: Children): void;
+ removeChildren(entity: Entity): void;
+ hasScreenSpace(entity: Entity): boolean;
+ getScreenSpace(entity: Entity): ScreenSpace;
+ addScreenSpace(entity: Entity, component: ScreenSpace): void;
+ removeScreenSpace(entity: Entity): void;
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): Canvas;
+ addCanvas(entity: Entity, component: Canvas): void;
+ removeCanvas(entity: Entity): void;
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): Camera;
+ addCamera(entity: Entity, component: Camera): void;
+ removeCamera(entity: Entity): void;
+ setParent(child: Entity, parent: Entity): void;
+}
+
+/**
+ * @file wasm.ts
+ * @brief WASM module type definitions
+ */
+
+interface CppRegistry extends Registry {
+ delete(): void;
+ removeParent(entity: Entity): void;
+ [key: string]: Function | undefined;
+}
+interface CppResourceManager {
+ createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
+ createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
+ createShader(vertSrc: string, fragSrc: string): number;
+ registerExternalTexture(glTextureId: number, width: number, height: number): number;
+ getTextureGLId(handle: number): number;
+ releaseTexture(handle: number): void;
+ releaseShader(handle: number): void;
+ setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
+ registerTextureWithPath(handle: number, path: string): void;
+ loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
+ createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
+ releaseBitmapFont(handle: number): void;
+ measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
+ width: number;
+ height: number;
+ };
+}
+interface EmscriptenFS {
+ writeFile(path: string, data: string | Uint8Array): void;
+ readFile(path: string, opts?: {
+ encoding?: string;
+ }): string | Uint8Array;
+ mkdir(path: string): void;
+ mkdirTree(path: string): void;
+ unlink(path: string): void;
+ stat(path: string): {
+ mode: number;
+ size: number;
+ };
+ isFile(mode: number): boolean;
+ isDir(mode: number): boolean;
+ analyzePath(path: string): {
+ exists: boolean;
+ parentExists: boolean;
+ };
+}
+interface SpineBounds {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ valid: boolean;
+}
+interface ESEngineModule {
+ Registry: new () => CppRegistry;
+ HEAPU8: Uint8Array;
+ HEAPU32: Uint32Array;
+ HEAPF32: Float32Array;
+ FS: EmscriptenFS;
+ materialDataProvider?: (materialId: number, outShaderIdPtr: number, outBlendModePtr: number, outUniformBufferPtr: number, outUniformCountPtr: number) => void;
+ initRenderer(): void;
+ initRendererWithCanvas(canvasSelector: string): boolean;
+ initRendererWithContext(contextHandle: number): boolean;
+ shutdownRenderer(): void;
+ GL: {
+ registerContext(ctx: WebGLRenderingContext | WebGL2RenderingContext, options: {
+ majorVersion: number;
+ minorVersion: number;
+ enableExtensionsByDefault?: boolean;
+ }): number;
+ };
+ renderFrame(registry: CppRegistry, width: number, height: number): void;
+ renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;
+ getResourceManager(): CppResourceManager;
+ getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;
+ invalidateMaterialCache(materialId: number): void;
+ clearMaterialCache(): void;
+ draw_begin(matrixPtr: number): void;
+ draw_end(): void;
+ draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
+ draw_rect(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
+ draw_rectOutline(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
+ draw_circle(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
+ draw_circleOutline(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
+ draw_texture(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
+ draw_textureRotated(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
+ draw_setLayer(layer: number): void;
+ draw_setDepth(depth: number): void;
+ draw_getDrawCallCount(): number;
+ draw_getPrimitiveCount(): number;
+ draw_setBlendMode(mode: number): void;
+ draw_setDepthTest(enabled: boolean): void;
+ draw_mesh(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
+ draw_meshWithUniforms(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
+ geometry_create(): number;
+ geometry_init(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
+ geometry_setIndices16(handle: number, indicesPtr: number, indexCount: number): void;
+ geometry_setIndices32(handle: number, indicesPtr: number, indexCount: number): void;
+ geometry_updateVertices(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
+ geometry_release(handle: number): void;
+ geometry_isValid(handle: number): boolean;
+ postprocess_init(width: number, height: number): boolean;
+ postprocess_shutdown(): void;
+ postprocess_resize(width: number, height: number): void;
+ postprocess_addPass(name: string, shaderHandle: number): number;
+ postprocess_removePass(name: string): void;
+ postprocess_setPassEnabled(name: string, enabled: boolean): void;
+ postprocess_isPassEnabled(name: string): boolean;
+ postprocess_setUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
+ postprocess_begin(): void;
+ postprocess_end(): void;
+ postprocess_getPassCount(): number;
+ postprocess_isInitialized(): boolean;
+ postprocess_setBypass(bypass: boolean): void;
+ postprocess_isBypassed(): boolean;
+ postprocess_clearPasses(): void;
+ postprocess_setOutputTarget(fboId: number): void;
+ postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
+ postprocess_beginScreenCapture(): void;
+ postprocess_endScreenCapture(): void;
+ postprocess_executeScreenPasses(): void;
+ postprocess_addScreenPass(name: string, shaderHandle: number): number;
+ postprocess_clearScreenPasses(): void;
+ postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
+ renderer_init(width: number, height: number): void;
+ renderer_resize(width: number, height: number): void;
+ renderer_begin(matrixPtr: number, targetHandle: number): void;
+ renderer_flush(): void;
+ renderer_end(): void;
+ renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitBitmapText(registry: CppRegistry): void;
+ renderer_submitSpine?(registry: CppRegistry): void;
+ renderer_submitParticles?(registry: CppRegistry): void;
+ renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
+ particle_update?(registry: CppRegistry, dt: number): void;
+ particle_play?(registry: CppRegistry, entity: number): void;
+ particle_stop?(registry: CppRegistry, entity: number): void;
+ particle_reset?(registry: CppRegistry, entity: number): void;
+ particle_getAliveCount?(entity: number): number;
+ tilemap_initLayer?(entity: number, width: number, height: number, tileWidth: number, tileHeight: number): void;
+ tilemap_destroyLayer?(entity: number): void;
+ tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
+ tilemap_getTile?(entity: number, x: number, y: number): number;
+ tilemap_fillRect?(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
+ tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
+ tilemap_hasLayer?(entity: number): boolean;
+ tilemap_submitLayer?(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
+ renderer_setStage(stage: number): void;
+ renderer_createTarget(width: number, height: number, flags: number): number;
+ renderer_releaseTarget(handle: number): void;
+ renderer_getTargetTexture(handle: number): number;
+ renderer_getTargetDepthTexture(handle: number): number;
+ renderer_getDrawCalls(): number;
+ renderer_getTriangles(): number;
+ renderer_getSprites(): number;
+ renderer_getText(): number;
+ renderer_getSpine?(): number;
+ renderer_getMeshes(): number;
+ renderer_getCulled(): number;
+ renderer_setClearColor(r: number, g: number, b: number, a: number): void;
+ renderer_setViewport(x: number, y: number, w: number, h: number): void;
+ renderer_setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
+ renderer_clearBuffers(flags: number): void;
+ renderer_setEntityClipRect(entity: number, x: number, y: number, w: number, h: number): void;
+ renderer_clearEntityClipRect(entity: number): void;
+ renderer_clearAllClipRects(): void;
+ renderer_clearStencil(): void;
+ renderer_setEntityStencilMask(entity: number, refValue: number): void;
+ renderer_setEntityStencilTest(entity: number, refValue: number): void;
+ renderer_clearEntityStencilMask(entity: number): void;
+ renderer_clearAllStencilMasks(): void;
+ registry_getCanvasEntity(registry: CppRegistry): number;
+ registry_getCameraEntities(registry: CppRegistry): number[];
+ getChildEntities(registry: CppRegistry, entity: number): number[];
+ registry_getGeneration(registry: CppRegistry, entity: number): number;
+ registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;
+ gl_enableErrorCheck(enabled: boolean): void;
+ gl_checkErrors(context: string): number;
+ renderer_diagnose(): void;
+ uiLayout_update(registry: CppRegistry, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
+ uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
+ uiHitTest_getHitEntity(): number;
+ uiHitTest_getHitEntityPrev(): number;
+ uiRenderOrder_update(registry: CppRegistry): void;
+ uiFlexLayout_update(registry: CppRegistry): void;
+ getUIRectComputedWidth(registry: CppRegistry, entity: number): number;
+ getUIRectComputedHeight(registry: CppRegistry, entity: number): number;
+ transform_update(registry: CppRegistry): void;
+ _anim_createTween(registry: CppRegistry, entity: number, targetProp: number, from: number, to: number, duration: number, easing: number, delay: number, loopMode: number, loopCount: number): number;
+ _anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
+ _anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
+ _anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
+ _anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
+ _anim_setTweenBezier(registry: CppRegistry, tweenEntity: number, p1x: number, p1y: number, p2x: number, p2y: number): void;
+ _anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
+ _anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
+ _anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
+ _malloc(size: number): number;
+ _free(ptr: number): void;
+}
+
+export { INVALID_ENTITY as I, INVALID_FONT as f, INVALID_MATERIAL as g, INVALID_TEXTURE as h, color as i, vec3 as j, vec4 as k, quat as q, vec2 as v };
+export type { Color as C, ESEngineModule as E, FontHandle as F, Quat as Q, SpineBounds as S, TextureHandle as T, Vec2 as V, Entity as a, Vec3 as b, CppRegistry as c, Vec4 as d, CppResourceManager as e, EmscriptenFS as l };
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index a1a637489..78f675545 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -1,1111 +1,6 @@
-/**
- * @file resource.ts
- * @brief Resource system for global singleton data
- */
-interface ResourceDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _default: T;
-}
-interface ResDescriptor<T> {
- readonly _type: 'res';
- readonly _resource: ResourceDef<T>;
-}
-interface ResMutDescriptor<T> {
- readonly _type: 'res_mut';
- readonly _resource: ResourceDef<T>;
-}
-
-/**
- * @file types.ts
- * @brief Core type definitions for ESEngine SDK
- */
-type Entity = number;
-interface Vec2 {
- x: number;
- y: number;
-}
-interface Vec3 {
- x: number;
- y: number;
- z: number;
-}
-interface Vec4 {
- x: number;
- y: number;
- z: number;
- w: number;
-}
-interface Quat {
- w: number;
- x: number;
- y: number;
- z: number;
-}
-
-/**
- * @file component.ts
- * @brief Component definition and builtin components
- */
-
-interface ComponentDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _default: T;
- readonly _builtin: false;
- create(data?: Partial<T>): T;
-}
-interface BuiltinComponentDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _cppName: string;
- readonly _builtin: true;
- readonly _default: T;
-}
-type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;
-type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
-
-/**
- * @file wasm.generated.ts
- * @brief ESEngine WASM Bindings TypeScript Definitions
- * @details Generated by EHT - DO NOT EDIT
- */
-
-interface UVec2 {
- x: number;
- y: number;
-}
-interface VectorEntity {
- size(): number;
- get(index: number): number;
- push_back(value: number): void;
- set(index: number, value: number): boolean;
- delete(): void;
-}
-interface UIRect {
- anchorMin: Vec2;
- anchorMax: Vec2;
- offsetMin: Vec2;
- offsetMax: Vec2;
- size: Vec2;
- pivot: Vec2;
-}
-interface FlexItem {
- flexGrow: number;
- flexShrink: number;
- flexBasis: number;
- order: number;
-}
-interface BoxCollider {
- halfExtents: Vec2;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CircleCollider {
- radius: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CapsuleCollider {
- radius: number;
- halfHeight: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface ParticleEmitter {
- rate: number;
- burstCount: number;
- burstInterval: number;
- duration: number;
- looping: boolean;
- playOnStart: boolean;
- maxParticles: number;
- lifetimeMin: number;
- lifetimeMax: number;
- shape: number;
- shapeRadius: number;
- shapeSize: Vec2;
- shapeAngle: number;
- speedMin: number;
- speedMax: number;
- angleSpreadMin: number;
- angleSpreadMax: number;
- startSizeMin: number;
- startSizeMax: number;
- endSizeMin: number;
- endSizeMax: number;
- sizeEasing: number;
- startColor: Vec4;
- endColor: Vec4;
- colorEasing: number;
- rotationMin: number;
- rotationMax: number;
- angularVelocityMin: number;
- angularVelocityMax: number;
- gravity: Vec2;
- damping: number;
- texture: number;
- spriteColumns: number;
- spriteRows: number;
- spriteFPS: number;
- spriteLoop: boolean;
- blendMode: number;
- layer: number;
- material: number;
- simulationSpace: number;
- enabled: boolean;
-}
-interface Transform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
- worldPosition: Vec3;
- worldRotation: Quat;
- worldScale: Vec3;
-}
-interface Velocity {
- linear: Vec3;
- angular: Vec3;
-}
-interface SpineAnimation {
- skeletonPath: string;
- atlasPath: string;
- skin: string;
- animation: string;
- timeScale: number;
- loop: boolean;
- playing: boolean;
- flipX: boolean;
- flipY: boolean;
- color: Vec4;
- layer: number;
- skeletonScale: number;
- material: number;
- enabled: boolean;
-}
-interface Interactable {
- enabled: boolean;
- blockRaycast: boolean;
- raycastTarget: boolean;
-}
-interface UIInteraction {
- hovered: boolean;
- pressed: boolean;
- justPressed: boolean;
- justReleased: boolean;
-}
-interface RigidBody {
- bodyType: number;
- gravityScale: number;
- linearDamping: number;
- angularDamping: number;
- fixedRotation: boolean;
- bullet: boolean;
- enabled: boolean;
-}
-interface BitmapText {
- text: string;
- color: Vec4;
- fontSize: number;
- align: number;
- spacing: number;
- layer: number;
- font: number;
- enabled: boolean;
-}
-interface Sprite {
- texture: number;
- color: Vec4;
- size: Vec2;
- uvOffset: Vec2;
- uvScale: Vec2;
- layer: number;
- flipX: boolean;
- flipY: boolean;
- material: number;
- enabled: boolean;
-}
-interface UIMask {
- enabled: boolean;
- mode: number;
-}
-interface FlexContainer {
- direction: number;
- wrap: number;
- justifyContent: number;
- alignItems: number;
- gap: Vec2;
- padding: Vec4;
-}
-interface Parent {
- entity: number;
-}
-interface Children {
- entities: VectorEntity;
-}
-interface ScreenSpace {
-}
-interface Canvas {
- designResolution: UVec2;
- pixelsPerUnit: number;
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: Vec4;
-}
-interface Camera {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- aspectRatio: number;
- isActive: boolean;
- priority: number;
- viewportX: number;
- viewportY: number;
- viewportW: number;
- viewportH: number;
- clearFlags: number;
-}
-interface Registry {
- create(): Entity;
- destroy(entity: Entity): void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- hasUIRect(entity: Entity): boolean;
- getUIRect(entity: Entity): UIRect;
- addUIRect(entity: Entity, component: UIRect): void;
- removeUIRect(entity: Entity): void;
- hasFlexItem(entity: Entity): boolean;
- getFlexItem(entity: Entity): FlexItem;
- addFlexItem(entity: Entity, component: FlexItem): void;
- removeFlexItem(entity: Entity): void;
- hasBoxCollider(entity: Entity): boolean;
- getBoxCollider(entity: Entity): BoxCollider;
- addBoxCollider(entity: Entity, component: BoxCollider): void;
- removeBoxCollider(entity: Entity): void;
- hasCircleCollider(entity: Entity): boolean;
- getCircleCollider(entity: Entity): CircleCollider;
- addCircleCollider(entity: Entity, component: CircleCollider): void;
- removeCircleCollider(entity: Entity): void;
- hasCapsuleCollider(entity: Entity): boolean;
- getCapsuleCollider(entity: Entity): CapsuleCollider;
- addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
- removeCapsuleCollider(entity: Entity): void;
- hasParticleEmitter(entity: Entity): boolean;
- getParticleEmitter(entity: Entity): ParticleEmitter;
- addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
- removeParticleEmitter(entity: Entity): void;
- hasTransform(entity: Entity): boolean;
- getTransform(entity: Entity): Transform;
- addTransform(entity: Entity, component: Transform): void;
- removeTransform(entity: Entity): void;
- hasVelocity(entity: Entity): boolean;
- getVelocity(entity: Entity): Velocity;
- addVelocity(entity: Entity, component: Velocity): void;
- removeVelocity(entity: Entity): void;
- hasSpineAnimation(entity: Entity): boolean;
- getSpineAnimation(entity: Entity): SpineAnimation;
- addSpineAnimation(entity: Entity, component: SpineAnimation): void;
- removeSpineAnimation(entity: Entity): void;
- hasInteractable(entity: Entity): boolean;
- getInteractable(entity: Entity): Interactable;
- addInteractable(entity: Entity, component: Interactable): void;
- removeInteractable(entity: Entity): void;
- hasUIInteraction(entity: Entity): boolean;
- getUIInteraction(entity: Entity): UIInteraction;
- addUIInteraction(entity: Entity, component: UIInteraction): void;
- removeUIInteraction(entity: Entity): void;
- hasRigidBody(entity: Entity): boolean;
- getRigidBody(entity: Entity): RigidBody;
- addRigidBody(entity: Entity, component: RigidBody): void;
- removeRigidBody(entity: Entity): void;
- hasBitmapText(entity: Entity): boolean;
- getBitmapText(entity: Entity): BitmapText;
- addBitmapText(entity: Entity, component: BitmapText): void;
- removeBitmapText(entity: Entity): void;
- hasSprite(entity: Entity): boolean;
- getSprite(entity: Entity): Sprite;
- addSprite(entity: Entity, component: Sprite): void;
- removeSprite(entity: Entity): void;
- hasUIMask(entity: Entity): boolean;
- getUIMask(entity: Entity): UIMask;
- addUIMask(entity: Entity, component: UIMask): void;
- removeUIMask(entity: Entity): void;
- hasFlexContainer(entity: Entity): boolean;
- getFlexContainer(entity: Entity): FlexContainer;
- addFlexContainer(entity: Entity, component: FlexContainer): void;
- removeFlexContainer(entity: Entity): void;
- hasParent(entity: Entity): boolean;
- getParent(entity: Entity): Parent;
- addParent(entity: Entity, component: Parent): void;
- removeParent(entity: Entity): void;
- hasChildren(entity: Entity): boolean;
- getChildren(entity: Entity): Children;
- addChildren(entity: Entity, component: Children): void;
- removeChildren(entity: Entity): void;
- hasScreenSpace(entity: Entity): boolean;
- getScreenSpace(entity: Entity): ScreenSpace;
- addScreenSpace(entity: Entity, component: ScreenSpace): void;
- removeScreenSpace(entity: Entity): void;
- hasCanvas(entity: Entity): boolean;
- getCanvas(entity: Entity): Canvas;
- addCanvas(entity: Entity, component: Canvas): void;
- removeCanvas(entity: Entity): void;
- hasCamera(entity: Entity): boolean;
- getCamera(entity: Entity): Camera;
- addCamera(entity: Entity, component: Camera): void;
- removeCamera(entity: Entity): void;
- setParent(child: Entity, parent: Entity): void;
-}
-
-/**
- * @file wasm.ts
- * @brief WASM module type definitions
- */
-
-interface CppRegistry extends Registry {
- delete(): void;
- removeParent(entity: Entity): void;
- [key: string]: Function | undefined;
-}
-interface CppResourceManager {
- createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
- createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
- createShader(vertSrc: string, fragSrc: string): number;
- registerExternalTexture(glTextureId: number, width: number, height: number): number;
- getTextureGLId(handle: number): number;
- releaseTexture(handle: number): void;
- releaseShader(handle: number): void;
- setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
- registerTextureWithPath(handle: number, path: string): void;
- loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
- createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
- releaseBitmapFont(handle: number): void;
- measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
- width: number;
- height: number;
- };
-}
-interface EmscriptenFS {
- writeFile(path: string, data: string | Uint8Array): void;
- readFile(path: string, opts?: {
- encoding?: string;
- }): string | Uint8Array;
- mkdir(path: string): void;
- mkdirTree(path: string): void;
- unlink(path: string): void;
- stat(path: string): {
- mode: number;
- size: number;
- };
- isFile(mode: number): boolean;
- isDir(mode: number): boolean;
- analyzePath(path: string): {
- exists: boolean;
- parentExists: boolean;
- };
-}
-interface SpineBounds {
- x: number;
- y: number;
- width: number;
- height: number;
- valid: boolean;
-}
-interface ESEngineModule {
- Registry: new () => CppRegistry;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- HEAPF32: Float32Array;
- FS: EmscriptenFS;
- materialDataProvider?: (materialId: number, outShaderIdPtr: number, outBlendModePtr: number, outUniformBufferPtr: number, outUniformCountPtr: number) => void;
- initRenderer(): void;
- initRendererWithCanvas(canvasSelector: string): boolean;
- initRendererWithContext(contextHandle: number): boolean;
- shutdownRenderer(): void;
- GL: {
- registerContext(ctx: WebGLRenderingContext | WebGL2RenderingContext, options: {
- majorVersion: number;
- minorVersion: number;
- enableExtensionsByDefault?: boolean;
- }): number;
- };
- renderFrame(registry: CppRegistry, width: number, height: number): void;
- renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;
- getResourceManager(): CppResourceManager;
- getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;
- invalidateMaterialCache(materialId: number): void;
- clearMaterialCache(): void;
- draw_begin(matrixPtr: number): void;
- draw_end(): void;
- draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_rect(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
- draw_rectOutline(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_circle(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
- draw_circleOutline(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
- draw_texture(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_textureRotated(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_setLayer(layer: number): void;
- draw_setDepth(depth: number): void;
- draw_getDrawCallCount(): number;
- draw_getPrimitiveCount(): number;
- draw_setBlendMode(mode: number): void;
- draw_setDepthTest(enabled: boolean): void;
- draw_mesh(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
- draw_meshWithUniforms(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
- geometry_create(): number;
- geometry_init(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
- geometry_setIndices16(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_setIndices32(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_updateVertices(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
- geometry_release(handle: number): void;
- geometry_isValid(handle: number): boolean;
- postprocess_init(width: number, height: number): boolean;
- postprocess_shutdown(): void;
- postprocess_resize(width: number, height: number): void;
- postprocess_addPass(name: string, shaderHandle: number): number;
- postprocess_removePass(name: string): void;
- postprocess_setPassEnabled(name: string, enabled: boolean): void;
- postprocess_isPassEnabled(name: string): boolean;
- postprocess_setUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- postprocess_begin(): void;
- postprocess_end(): void;
- postprocess_getPassCount(): number;
- postprocess_isInitialized(): boolean;
- postprocess_setBypass(bypass: boolean): void;
- postprocess_isBypassed(): boolean;
- postprocess_clearPasses(): void;
- postprocess_setOutputTarget(fboId: number): void;
- postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
- postprocess_beginScreenCapture(): void;
- postprocess_endScreenCapture(): void;
- postprocess_executeScreenPasses(): void;
- postprocess_addScreenPass(name: string, shaderHandle: number): number;
- postprocess_clearScreenPasses(): void;
- postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- renderer_init(width: number, height: number): void;
- renderer_resize(width: number, height: number): void;
- renderer_begin(matrixPtr: number, targetHandle: number): void;
- renderer_flush(): void;
- renderer_end(): void;
- renderer_submitSprites(registry: CppRegistry): void;
- renderer_submitBitmapText(registry: CppRegistry): void;
- renderer_submitSpine?(registry: CppRegistry): void;
- renderer_submitParticles?(registry: CppRegistry): void;
- renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
- particle_update?(registry: CppRegistry, dt: number): void;
- particle_play?(registry: CppRegistry, entity: number): void;
- particle_stop?(registry: CppRegistry, entity: number): void;
- particle_reset?(registry: CppRegistry, entity: number): void;
- particle_getAliveCount?(entity: number): number;
- tilemap_initLayer?(entity: number, width: number, height: number, tileWidth: number, tileHeight: number): void;
- tilemap_destroyLayer?(entity: number): void;
- tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
- tilemap_getTile?(entity: number, x: number, y: number): number;
- tilemap_fillRect?(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
- tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
- tilemap_hasLayer?(entity: number): boolean;
- tilemap_submitLayer?(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- renderer_setStage(stage: number): void;
- renderer_createTarget(width: number, height: number, flags: number): number;
- renderer_releaseTarget(handle: number): void;
- renderer_getTargetTexture(handle: number): number;
- renderer_getTargetDepthTexture(handle: number): number;
- renderer_getDrawCalls(): number;
- renderer_getTriangles(): number;
- renderer_getSprites(): number;
- renderer_getText(): number;
- renderer_getSpine?(): number;
- renderer_getMeshes(): number;
- renderer_getCulled(): number;
- renderer_setClearColor(r: number, g: number, b: number, a: number): void;
- renderer_setViewport(x: number, y: number, w: number, h: number): void;
- renderer_setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
- renderer_clearBuffers(flags: number): void;
- renderer_setEntityClipRect(entity: number, x: number, y: number, w: number, h: number): void;
- renderer_clearEntityClipRect(entity: number): void;
- renderer_clearAllClipRects(): void;
- renderer_clearStencil(): void;
- renderer_setEntityStencilMask(entity: number, refValue: number): void;
- renderer_setEntityStencilTest(entity: number, refValue: number): void;
- renderer_clearEntityStencilMask(entity: number): void;
- renderer_clearAllStencilMasks(): void;
- registry_getCanvasEntity(registry: CppRegistry): number;
- registry_getCameraEntities(registry: CppRegistry): number[];
- getChildEntities(registry: CppRegistry, entity: number): number[];
- registry_getGeneration(registry: CppRegistry, entity: number): number;
- registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;
- gl_enableErrorCheck(enabled: boolean): void;
- gl_checkErrors(context: string): number;
- renderer_diagnose(): void;
- uiLayout_update(registry: CppRegistry, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
- uiHitTest_getHitEntity(): number;
- uiHitTest_getHitEntityPrev(): number;
- uiRenderOrder_update(registry: CppRegistry): void;
- uiFlexLayout_update(registry: CppRegistry): void;
- getUIRectComputedWidth(registry: CppRegistry, entity: number): number;
- getUIRectComputedHeight(registry: CppRegistry, entity: number): number;
- transform_update(registry: CppRegistry): void;
- _anim_createTween(registry: CppRegistry, entity: number, targetProp: number, from: number, to: number, duration: number, easing: number, delay: number, loopMode: number, loopCount: number): number;
- _anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
- _anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_setTweenBezier(registry: CppRegistry, tweenEntity: number, p1x: number, p1y: number, p2x: number, p2y: number): void;
- _anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
- _anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
- _anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-
-/**
- * @file world.ts
- * @brief ECS World with C++ Registry integration
- */
-
-declare class World {
- private cppRegistry_;
- private module_;
- private entities_;
- private tsStorage_;
- private entityComponents_;
- private queryPool_;
- private queryPoolIdx_;
- private worldVersion_;
- private queryCache_;
- private builtinMethodCache_;
- private iterationDepth_;
- private nextEntityId_;
- private nextGeneration_;
- private spawnCallbacks_;
- private despawnCallbacks_;
- private worldTick_;
- private componentAddedTicks_;
- private componentChangedTicks_;
- private componentRemovedBuffer_;
- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void;
- disconnectCpp(): void;
- get hasCpp(): boolean;
- getCppRegistry(): CppRegistry | null;
- spawn(): Entity;
- despawn(entity: Entity): void;
- onSpawn(callback: (entity: Entity) => void): () => void;
- onDespawn(callback: (entity: Entity) => void): () => void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- getWorldVersion(): number;
- beginIteration(): void;
- endIteration(): void;
- resetIterationDepth(): void;
- isIterating(): boolean;
- getAllEntities(): Entity[];
- setParent(child: Entity, parent: Entity): void;
- removeParent(entity: Entity): void;
- insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C>;
- set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
- get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
- has(entity: Entity, component: AnyComponentDef): boolean;
- tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null;
- remove(entity: Entity, component: AnyComponentDef): void;
- private getBuiltinMethods;
- private insertBuiltin;
- private getBuiltin;
- private hasBuiltin;
- private removeBuiltin;
- private insertScript;
- private getScript;
- private hasScript;
- private removeScript;
- private getStorage;
- resetQueryPool(): void;
- getComponentTypes(entity: Entity): string[];
- getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[], precomputedKey?: string): Entity[];
- advanceTick(): void;
- getWorldTick(): number;
- isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
- isChangedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean;
- getRemovedEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[];
- cleanRemovedBuffer(beforeTick: number): void;
- private recordAddedTick_;
- private recordChangedTick_;
- private recordRemovedTick_;
-}
-
-/**
- * @file query.ts
- * @brief Component query system with mutable component support
- */
-
-interface MutWrapper<T extends AnyComponentDef> {
- readonly _type: 'mut';
- readonly _component: T;
-}
-interface AddedWrapper<T extends AnyComponentDef> {
- readonly _filterType: 'added';
- readonly _component: T;
-}
-interface ChangedWrapper<T extends AnyComponentDef> {
- readonly _filterType: 'changed';
- readonly _component: T;
-}
-type QueryArg$1 = AnyComponentDef | MutWrapper<AnyComponentDef> | AddedWrapper<AnyComponentDef> | ChangedWrapper<AnyComponentDef>;
-interface QueryDescriptor<C extends readonly QueryArg$1[]> {
- readonly _type: 'query';
- readonly _components: C;
- readonly _mutIndices: number[];
- readonly _with: AnyComponentDef[];
- readonly _without: AnyComponentDef[];
- readonly _addedFilters: Array<{
- index: number;
- component: AnyComponentDef;
- }>;
- readonly _changedFilters: Array<{
- index: number;
- component: AnyComponentDef;
- }>;
-}
-interface RemovedQueryDescriptor<T extends AnyComponentDef> {
- readonly _type: 'removed';
- readonly _component: T;
-}
-
-/**
- * @file commands.ts
- * @brief Deferred entity/component operations
- */
-
-interface CommandsDescriptor {
- readonly _type: 'commands';
-}
-
-/**
- * @file event.ts
- * @brief Event system with double-buffered event buses
- */
-interface EventDef<T> {
- readonly _id: symbol;
- readonly _name: string;
- readonly _phantom?: T;
-}
-interface EventWriterDescriptor<T> {
- readonly _type: 'event_writer';
- readonly _event: EventDef<T>;
-}
-interface EventReaderDescriptor<T> {
- readonly _type: 'event_reader';
- readonly _event: EventDef<T>;
-}
-
-/**
- * @file system.ts
- * @brief System definition and scheduling
- */
-
-declare enum Schedule {
- Startup = 0,
- First = 1,
- PreUpdate = 2,
- Update = 3,
- PostUpdate = 4,
- Last = 5,
- FixedPreUpdate = 10,
- FixedUpdate = 11,
- FixedPostUpdate = 12
-}
-interface GetWorldDescriptor {
- readonly _type: 'get_world';
-}
-type QueryArg = AnyComponentDef | MutWrapper<AnyComponentDef>;
-type SystemParam = QueryDescriptor<readonly QueryArg[]> | ResDescriptor<unknown> | ResMutDescriptor<unknown> | CommandsDescriptor | EventWriterDescriptor<unknown> | EventReaderDescriptor<unknown> | RemovedQueryDescriptor<AnyComponentDef> | GetWorldDescriptor;
-interface SystemDef {
- readonly _id: symbol;
- readonly _params: readonly SystemParam[];
- readonly _fn: (...args: never[]) => void;
- readonly _name: string;
-}
-
-/**
- * @file renderPipeline.ts
- * @brief Unified render pipeline for runtime and editor
- */
-
-interface RenderParams {
- registry: {
- _cpp: CppRegistry;
- };
- viewProjection: Float32Array;
- width: number;
- height: number;
- elapsed: number;
-}
-interface CameraRenderParams {
- registry: {
- _cpp: CppRegistry;
- };
- viewProjection: Float32Array;
- viewportPixels: {
- x: number;
- y: number;
- w: number;
- h: number;
- };
- clearFlags: number;
- elapsed: number;
- cameraEntity?: Entity;
-}
-type SpineRendererFn = (registry: {
- _cpp: CppRegistry;
-}, elapsed: number) => void;
-type TilemapRendererFn = () => void;
-type MaskProcessorFn = (registry: CppRegistry, vp: Float32Array, viewportX: number, viewportY: number, viewportW: number, viewportH: number) => void;
-declare class RenderPipeline {
- private spineRenderer_;
- private tilemapRenderer_;
- private maskProcessor_;
- private lastWidth_;
- private lastHeight_;
- private activeScenes_;
- get spineRenderer(): SpineRendererFn | null;
- setSpineRenderer(fn: SpineRendererFn | null): void;
- setTilemapRenderer(fn: TilemapRendererFn | null): void;
- get maskProcessor(): MaskProcessorFn | null;
- setMaskProcessor(fn: MaskProcessorFn | null): void;
- setActiveScenes(scenes: Set<string> | null): void;
- beginScreenCapture(): void;
- endScreenCapture(): void;
- render(params: RenderParams): void;
- renderCamera(params: CameraRenderParams): void;
- private executeDrawCallbacks;
-}
-
-/**
- * @file material.ts
- * @brief Material and Shader API for custom rendering
- * @details Provides shader creation and material management for custom visual effects.
- */
-
-type ShaderHandle = number;
-
-/**
- * @file SpineModuleLoader.ts
- * @brief Loads and initializes the standalone Spine WASM module
- */
-interface SpineWasmModule {
- _spine_loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: number, atlasLen: number, isBinary: number): number;
- _spine_unloadSkeleton(handle: number): void;
- _spine_getAtlasPageCount(handle: number): number;
- _spine_getAtlasPageTextureName(handle: number, pageIndex: number): number;
- _spine_setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
- _spine_createInstance(skeletonHandle: number): number;
- _spine_destroyInstance(instanceId: number): void;
- _spine_playAnimation(instanceId: number, name: number, loop: number, track: number): number;
- _spine_addAnimation(instanceId: number, name: number, loop: number, delay: number, track: number): number;
- _spine_setSkin(instanceId: number, name: number): void;
- _spine_update(instanceId: number, dt: number): void;
- _spine_getAnimations(instanceId: number): number;
- _spine_getSkins(instanceId: number): number;
- _spine_getBonePosition(instanceId: number, bone: number, outXPtr: number, outYPtr: number): number;
- _spine_getBoneRotation(instanceId: number, bone: number): number;
- _spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;
- _spine_getMeshBatchCount(instanceId: number): number;
- _spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
- _spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
- _spine_getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;
- cwrap(ident: string, returnType: string | null, argTypes: string[]): (...args: unknown[]) => unknown;
- UTF8ToString(ptr: number): string;
- stringToNewUTF8(str: string): number;
- HEAPF32: Float32Array;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-interface SpineWrappedAPI {
- loadSkeleton(skelDataPtr: number, skelDataLen: number, atlasText: string, atlasLen: number, isBinary: boolean): number;
- getLastError(): string;
- unloadSkeleton(handle: number): void;
- getAtlasPageCount(handle: number): number;
- getAtlasPageTextureName(handle: number, pageIndex: number): string;
- setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
- createInstance(skeletonHandle: number): number;
- destroyInstance(instanceId: number): void;
- playAnimation(instanceId: number, name: string, loop: boolean, track: number): boolean;
- addAnimation(instanceId: number, name: string, loop: boolean, delay: number, track: number): boolean;
- setSkin(instanceId: number, name: string): void;
- update(instanceId: number, dt: number): void;
- getAnimations(instanceId: number): string;
- getSkins(instanceId: number): string;
- getBonePosition(instanceId: number, bone: string, outXPtr: number, outYPtr: number): boolean;
- getBoneRotation(instanceId: number, bone: string): number;
- getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;
- getMeshBatchCount(instanceId: number): number;
- getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;
- getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;
- getMeshBatchData(instanceId: number, batchIndex: number, outVerticesPtr: number, outIndicesPtr: number, outTextureIdPtr: number, outBlendModePtr: number): void;
-}
-declare function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI;
-type SpineModuleFactory = (config?: Record<string, unknown>) => Promise<SpineWasmModule>;
-declare function loadSpineModule(wasmUrl: string, factory?: SpineModuleFactory): Promise<{
- raw: SpineWasmModule;
- api: SpineWrappedAPI;
-}>;
-
-/**
- * @file SpineController.ts
- * @brief Spine animation control for the modular Spine WASM module
- */
-
-type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'dispose' | 'event';
-type SpineEventCallback = (event: SpineEvent) => void;
-interface SpineEvent {
- type: SpineEventType;
- entity: Entity;
- track: number;
- animation: string | null;
- eventName?: string;
- intValue?: number;
- floatValue?: number;
- stringValue?: string;
-}
-declare class SpineModuleController {
- private raw_;
- private api_;
- private listeners_;
- constructor(raw: SpineWasmModule, api: SpineWrappedAPI);
- get raw(): SpineWasmModule;
- loadSkeleton(skelData: Uint8Array | string, atlasText: string, isBinary: boolean): number;
- getLastError(): string;
- unloadSkeleton(handle: number): void;
- getAtlasPageCount(handle: number): number;
- getAtlasPageTextureName(handle: number, pageIndex: number): string;
- setAtlasPageTexture(handle: number, pageIndex: number, textureId: number, width: number, height: number): void;
- createInstance(skeletonHandle: number): number;
- destroyInstance(instanceId: number): void;
- play(instanceId: number, animation: string, loop?: boolean, track?: number): boolean;
- addAnimation(instanceId: number, animation: string, loop?: boolean, delay?: number, track?: number): boolean;
- setSkin(instanceId: number, skinName: string): void;
- update(instanceId: number, dt: number): void;
- getAnimations(instanceId: number): string[];
- getSkins(instanceId: number): string[];
- getBonePosition(instanceId: number, boneName: string): Vec2 | null;
- getBoneRotation(instanceId: number, boneName: string): number;
- getBounds(instanceId: number): {
- x: number;
- y: number;
- width: number;
- height: number;
- };
- extractMeshBatches(instanceId: number): {
- vertices: Float32Array;
- indices: Uint16Array;
- textureId: number;
- blendMode: number;
- }[];
- on(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;
- off(entity: Entity, type: SpineEventType, callback: SpineEventCallback): void;
- removeAllListeners(entity: Entity): void;
-}
-
-/**
- * @file scene.ts
- * @brief Scene loading utilities
- */
-
-interface SceneEntityData {
- id: number;
- name: string;
- parent: number | null;
- children: number[];
- components: SceneComponentData[];
- visible?: boolean;
-}
-interface SceneComponentData {
- type: string;
- data: Record<string, unknown>;
-}
-interface SliceBorder {
- left: number;
- right: number;
- top: number;
- bottom: number;
-}
-interface TextureMetadata {
- version: string;
- type: 'texture';
- sliceBorder: SliceBorder;
-}
-interface SceneData {
- version: string;
- name: string;
- entities: SceneEntityData[];
- textureMetadata?: Record<string, TextureMetadata>;
-}
-
-/**
- * @file customDraw.ts
- * @brief Custom draw callback registration for the render pipeline
- */
-type DrawCallback = (elapsed: number) => void;
-
-interface PassConfig {
- name: string;
- shader: ShaderHandle;
- enabled: boolean;
- floatUniforms: Map<string, number>;
- vec4Uniforms: Map<string, Vec4>;
-}
-declare class PostProcessStack {
- readonly id: number;
- private passes_;
- private destroyed_;
- constructor();
- addPass(name: string, shader: ShaderHandle): this;
- removePass(name: string): this;
- setEnabled(name: string, enabled: boolean): this;
- setUniform(passName: string, uniform: string, value: number): this;
- setUniformVec4(passName: string, uniform: string, value: Vec4): this;
- setAllPassesEnabled(enabled: boolean): void;
- get passCount(): number;
- get enabledPassCount(): number;
- get passes(): readonly PassConfig[];
- get isDestroyed(): boolean;
- destroy(): void;
-}
-
-interface SceneConfig {
- name: string;
- path?: string;
- data?: SceneData;
- systems?: Array<{
- schedule: Schedule;
- system: SystemDef;
- }>;
- setup?: (ctx: SceneContext) => void | Promise<void>;
- cleanup?: (ctx: SceneContext) => void;
-}
-interface SceneContext {
- readonly name: string;
- readonly entities: ReadonlySet<Entity>;
- spawn(): Entity;
- despawn(entity: Entity): void;
- registerDrawCallback(id: string, fn: DrawCallback): void;
- bindPostProcess(camera: Entity, stack: PostProcessStack): void;
- unbindPostProcess(camera: Entity): void;
- setPersistent(entity: Entity, persistent: boolean): void;
-}
-
-/**
- * @file app.ts
- * @brief Application builder and web platform integration
- */
-
-type PluginDependency = string | ResourceDef<any>;
-interface Plugin {
- name?: string;
- dependencies?: PluginDependency[];
- build(app: App): void;
- finish?(app: App): void;
- cleanup?(app?: App): void;
-}
-declare class App {
- private readonly world_;
- private readonly resources_;
- private readonly systems_;
- private runner_;
- private running_;
- private lastTime_;
- private fixedTimestep_;
- private fixedAccumulator_;
- private maxDeltaTime_;
- private maxFixedSteps_;
- private module_;
- private pipeline_;
- private spineInitPromise_?;
- private physicsInitPromise_?;
- private physicsModule_?;
- private readonly installed_plugins_;
- private readonly installedPluginSet_;
- private readonly installedPluginNames_;
- private pluginsFinished_;
- private readonly eventRegistry_;
- private readonly sortedSystemsCache_;
- private error_handler_;
- private system_error_handler_;
- private statsEnabled_;
- private phaseTimings_;
- private frame_paused_;
- private user_paused_;
- private step_pending_;
- private play_speed_;
- private constructor();
- static new(): App;
- addPlugin(plugin: Plugin): this;
- addEvent<T>(event: EventDef<T>): this;
- addSystemToSchedule(schedule: Schedule, system: SystemDef, options?: {
- runBefore?: string[];
- runAfter?: string[];
- }): this;
- addSystem(system: SystemDef): this;
- addStartupSystem(system: SystemDef): this;
- removeSystem(systemId: symbol): boolean;
- connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this;
- get wasmModule(): ESEngineModule | null;
- get pipeline(): RenderPipeline | null;
- setPipeline(pipeline: RenderPipeline): void;
- setSpineRenderer(fn: SpineRendererFn | null): void;
- get spineInitPromise(): Promise<unknown> | undefined;
- set spineInitPromise(p: Promise<unknown> | undefined);
- get physicsInitPromise(): Promise<unknown> | undefined;
- set physicsInitPromise(p: Promise<unknown> | undefined);
- get physicsModule(): unknown;
- set physicsModule(m: unknown);
- get world(): World;
- setFixedTimestep(timestep: number): this;
- setMaxDeltaTime(v: number): this;
- setMaxFixedSteps(v: number): this;
- onError(handler: (error: unknown, systemName: string) => void): this;
- onSystemError(handler: (error: Error, systemName?: string) => 'continue' | 'pause'): this;
- onWasmError(handler: (error: unknown, context: string) => void): this;
- setPaused(paused: boolean): void;
- isPaused(): boolean;
- stepFrame(): void;
- setPlaySpeed(speed: number): void;
- getPlaySpeed(): number;
- enableStats(): this;
- getSystemTimings(): ReadonlyMap<string, number> | null;
- getPhaseTimings(): ReadonlyMap<string, number> | null;
- getEntityCount(): number;
- insertResource<T>(resource: ResourceDef<T>, value: T): this;
- getResource<T>(resource: ResourceDef<T>): T;
- hasResource<T>(resource: ResourceDef<T>): boolean;
- registerScene(config: SceneConfig): this;
- setInitialScene(name: string): this;
- tick(delta: number): void;
- run(): void;
- private mainLoop;
- quit(): void;
- private finishPlugins_;
- private sortSystems;
- private runSchedule;
- private updateTime;
-}
+import { P as Plugin, S as SpineModuleFactory, A as App, R as ResourceDef, a as SpineModuleController } from '../shared/app.js';
+export { b as SpineEvent, c as SpineEventCallback, d as SpineEventType, e as SpineWasmModule, f as SpineWrappedAPI, l as loadSpineModule, w as wrapSpineModule } from '../shared/app.js';
+import { E as ESEngineModule } from '../shared/wasm.js';
declare const SpineResource: ResourceDef<SpineModuleController | null>;
declare class SpinePlugin implements Plugin {
@@ -1121,5 +16,4 @@ declare function submitSpineMeshesToCore(coreModule: ESEngineModule, controller:
a: number;
}): void;
-export { SpineModuleController, SpinePlugin, SpineResource, loadSpineModule, submitSpineMeshesToCore, wrapSpineModule };
-export type { SpineEvent, SpineEventCallback, SpineEventType, SpineModuleFactory, SpineWasmModule, SpineWrappedAPI };
+export { SpineModuleController, SpineModuleFactory, SpinePlugin, SpineResource, submitSpineMeshesToCore };
diff --git a/desktop/public/sdk/esm/spine/index.js b/desktop/public/sdk/esm/spine/index.js
index b6b9256bd..4be17e17a 100644
--- a/desktop/public/sdk/esm/spine/index.js
+++ b/desktop/public/sdk/esm/spine/index.js
@@ -1,2 +1,2 @@
-let e=0;function t(t,n){const r=++e;return{_id:Symbol(`Resource_${r}_${n??""}`),_name:n??`Resource_${r}`,_default:t}}t({delta:0,elapsed:0,frameCount:0},"Time");const n=4294967295,r=100,i=100;function a(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(a);const t={};for(const n in e)t[n]=a(e[n]);return t}let s=0;function o(){const e=globalThis;return e.__esengine_componentRegistry??(e.__esengine_componentRegistry=new Map)}function l(e,t){const n=u.get(e)??o().get(e);if(n)return n;const r=function(e,t){const n=++s,r=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=>r?e?{...a(t),...e}:a(t):e?{...t,...e}:{...t}}}(e,t);return o().set(e,r),u.set(e,r),function(e,t,n){const r=globalThis;r.__esengine_registerComponent&&r.__esengine_registerComponent(e,t,n)}(e,t,!1),r}const u=new Map;function c(e,t){const n={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return u.set(e,n),n}const p=c("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}});c("Sprite",{texture:n,color:{r:1,g:1,b:1,a:1},size:{x:r,y:i},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0,enabled:!0}),c("Camera",{projectionType:1,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:3}),c("Canvas",{designResolution:{x:1920,y:1080},pixelsPerUnit:100,scaleMode:1,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),c("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),c("Parent",{entity:0}),c("Children",{entities:[]}),c("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:4294967295,enabled:!0});const d=c("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}),h=0;var m;c("ParticleEmitter",{rate:10,burstCount:0,burstInterval:1,duration:5,looping:!0,playOnStart:!0,maxParticles:1e3,lifetimeMin:5,lifetimeMax:5,shape:3,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:h,startColor:{r:1,g:1,b:1,a:1},endColor:{r:1,g:1,b:1,a:0},colorEasing:h,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:0,enabled:!0}),l("Name",{value:""}),l("SceneOwner",{scene:"",persistent:!1}),l("PostProcessVolume",{effects:[],isGlobal:!0,shape:"box",size:{x:5,y:5},priority:0,weight:1,blendDistance:0}),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"}(m||(m={}));const _=t(null,"Assets");function g(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"])}}async function b(e,t){if(!t)throw new Error("SpineModuleLoader: factory parameter is required. Pass the Spine WASM factory function explicitly via loadSpineModule(url, factory).");const n=await t();return{raw:n,api:g(n)}}class f{constructor(e,t){this.raw_=e,this.api_=t,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(e,t,n){let r,i;if("string"==typeof e){const t=(new TextEncoder).encode(e);i=t.length,r=this.raw_._malloc(i+1),this.raw_.HEAPU8.set(t,r),this.raw_.HEAPU8[r+i]=0}else i=e.length,r=this.raw_._malloc(i),this.raw_.HEAPU8.set(e,r);const a=this.api_.loadSkeleton(r,i,t,t.length,n);return this.raw_._free(r),a}getLastError(){return this.api_.getLastError()}unloadSkeleton(e){this.api_.unloadSkeleton(e)}getAtlasPageCount(e){return this.api_.getAtlasPageCount(e)}getAtlasPageTextureName(e,t){return this.api_.getAtlasPageTextureName(e,t)}setAtlasPageTexture(e,t,n,r,i){this.api_.setAtlasPageTexture(e,t,n,r,i)}createInstance(e){return this.api_.createInstance(e)}destroyInstance(e){this.api_.destroyInstance(e),this.listeners_.delete(e)}play(e,t,n=!0,r=0){return!!this.api_.playAnimation(e,t,n,r)}addAnimation(e,t,n=!0,r=0,i=0){return!!this.api_.addAnimation(e,t,n,r,i)}setSkin(e,t){this.api_.setSkin(e,t)}update(e,t){this.api_.update(e,t)}getAnimations(e){const t=this.api_.getAnimations(e);try{return JSON.parse(t)}catch{return[]}}getSkins(e){const t=this.api_.getSkins(e);try{return JSON.parse(t)}catch{return[]}}getBonePosition(e,t){const n=this.raw_._malloc(4),r=this.raw_._malloc(4);if(!this.api_.getBonePosition(e,t,n,r))return this.raw_._free(n),this.raw_._free(r),null;const i=this.raw_.HEAPF32[n>>2],a=this.raw_.HEAPF32[r>>2];return this.raw_._free(n),this.raw_._free(r),{x:i,y:a}}getBoneRotation(e,t){return this.api_.getBoneRotation(e,t)}getBounds(e){const t=this.raw_._malloc(16);this.api_.getBounds(e,t,t+4,t+8,t+12);const n=this.raw_.HEAPF32,r=t>>2,i={x:n[r],y:n[r+1],width:n[r+2],height:n[r+3]};return this.raw_._free(t),i}extractMeshBatches(e){const t=this.api_.getMeshBatchCount(e),n=[],r=this.raw_._malloc(8),i=r,a=r+4;for(let r=0;r<t;r++){const t=this.api_.getMeshBatchVertexCount(e,r),s=this.api_.getMeshBatchIndexCount(e,r);if(t<=0||s<=0)continue;const o=8*t*4,l=2*s,u=this.raw_._malloc(o),c=this.raw_._malloc(l);this.api_.getMeshBatchData(e,r,u,c,i,a);const p=new Float32Array(this.raw_.HEAPF32.buffer,u,8*t),d=new Uint16Array(this.raw_.HEAPU8.buffer,c,s);n.push({vertices:new Float32Array(p),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[i>>2],blendMode:this.raw_.HEAPU32[a>>2]}),this.raw_._free(u),this.raw_._free(c)}return this.raw_._free(r),n}on(e,t,n){this.listeners_.has(e)||this.listeners_.set(e,new Map);const r=this.listeners_.get(e);r.has(t)||r.set(t,new Set),r.get(t).add(n)}off(e,t,n){const r=this.listeners_.get(e);if(!r)return;const i=r.get(t);i&&i.delete(n)}removeAllListeners(e){this.listeners_.delete(e)}}const w=t(null,"SpineController"),y=new Float32Array(16);function S(e,t,n,r){const i=e.worldScale.x*t*(n?-1:1),a=e.worldScale.y*t*(r?-1:1),s=e.worldScale.z,o=e.worldRotation.x,l=e.worldRotation.y,u=e.worldRotation.z,c=e.worldRotation.w,p=o+o,d=l+l,h=u+u,m=o*p,_=o*d,g=o*h,b=l*d,f=l*h,w=u*h,S=c*p,x=c*d,P=c*h;return y[0]=(1-(b+w))*i,y[1]=(_+P)*i,y[2]=(g-x)*i,y[3]=0,y[4]=(_-P)*a,y[5]=(1-(m+w))*a,y[6]=(f+S)*a,y[7]=0,y[8]=(g+x)*s,y[9]=(f-S)*s,y[10]=(1-(m+b))*s,y[11]=0,y[12]=e.worldPosition.x,y[13]=e.worldPosition.y,y[14]=e.worldPosition.z,y[15]=1,y}class x{constructor(e,t){this.wasmUrl_=e,this.factory_=t}build(e){const t=e.wasmModule,n=b(this.wasmUrl_,this.factory_).then(({raw:n,api:r})=>{const i=new f(n,r);e.insertResource(w,i),e.hasResource(_)&&e.getResource(_).setSpineController(i);const a=new Map,s=new Map,o=new Map,l={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=e.world,n=e.hasResource(_)?e.getResource(_):null;if(!n)return;const r=t.getEntitiesWithComponents([d]),l=new Set;for(const e of r){l.add(e);const r=t.get(e,d),u=`${r.skeletonPath}:${r.atlasPath}`;if(!a.has(e)||s.get(e)!==u){a.has(e)&&(i.destroyInstance(a.get(e)),a.delete(e),s.delete(e),o.delete(e));const t=n.getSpineSkeletonHandle(r.skeletonPath,r.atlasPath);if(void 0===t)continue;const l=i.createInstance(t);if(l<0)continue;a.set(e,l),s.set(e,u),r.skin&&i.setSkin(l,r.skin),r.animation&&i.play(l,r.animation,r.loop),o.set(e,{animation:r.animation,skin:r.skin,loop:r.loop});continue}const c=o.get(e);if(!c)continue;const p=a.get(e);c.skin!==r.skin&&(i.setSkin(p,r.skin),c.skin=r.skin),c.animation===r.animation&&c.loop===r.loop||(r.animation&&i.play(p,r.animation,r.loop),c.animation=r.animation,c.loop=r.loop)}for(const[e,t]of a)l.has(e)||(i.destroyInstance(t),a.delete(e),s.delete(e),o.delete(e))}};if(e.addSystemToSchedule(m.PreUpdate,l),!e.pipeline?.spineRenderer){let n=0;e.setSpineRenderer((r,s)=>{let o=s-n;n=s,(o<=0||o>.5)&&(o=1/60);const l=e.world;for(const[e,n]of a){const r=l.has(e,d)?l.get(e,d):null,a=!1!==r?.playing,s=r?.timeScale??1;let u;if(a&&i.update(n,o*s),l.has(e,p)){u=S(l.get(e,p),r?.skeletonScale??1,r?.flipX??!1,r?.flipY??!1)}const c=r?.color;E(t,i,n,u,c)}})}return{controller:i,coreModule:t}});e.insertResource(w,null),n.catch(()=>{}),e.spineInitPromise=n}}let P=new Float32Array(0),A=0,M=0,k=0,B=0,C=0,U=null;function R(e,t,n,r){if(t&&n>=r)return[t,n];t&&e._free(t);const i=2*r;return[e._malloc(i),i]}function E(e,t,n,r,i){U&&U!==e&&U&&(A&&(U._free(A),A=0,M=0),k&&(U._free(k),k=0,B=0),C&&(U._free(C),C=0),U=null),U=e;const a=t.extractMeshBatches(n);r&&(C||(C=e._malloc(64)),e.HEAPF32.set(r,C>>2));const s=i&&(1!==i.r||1!==i.g||1!==i.b||1!==i.a);for(const t of a){let n=t.vertices;if(s){const e=t.blendMode>=4;P.length<n.length&&(P=new Float32Array(2*n.length)),P.set(n);const r=P.subarray(0,n.length);for(let t=0;t<r.length;t+=8)e?(r[t+4]*=i.r*i.a,r[t+5]*=i.g*i.a,r[t+6]*=i.b*i.a):(r[t+4]*=i.r,r[t+5]*=i.g,r[t+6]*=i.b),r[t+7]*=i.a;n=r}const a=n.byteLength,o=t.indices.byteLength;[A,M]=R(e,A,M,a),[k,B]=R(e,k,B,o),e.HEAPF32.set(n,A>>2),new Uint16Array(e.HEAPU8.buffer,k,t.indices.length).set(t.indices),e.renderer_submitTriangles(A,n.length/8,k,t.indices.length,t.textureId,t.blendMode,r?C:0)}}export{f as SpineModuleController,x as SpinePlugin,w as SpineResource,b as loadSpineModule,E as submitSpineMeshesToCore,g as wrapSpineModule};
+import{S as t,a as e,T as n,d as s}from"../shared/material.js";import{l as a,A as i}from"../shared/SpineModuleLoader.js";export{w as wrapSpineModule}from"../shared/SpineModuleLoader.js";class r{constructor(t,e){this.raw_=t,this.api_=e,this.listeners_=new Map}get raw(){return this.raw_}loadSkeleton(t,e,n){let s,a;if("string"==typeof t){const e=(new TextEncoder).encode(t);a=e.length,s=this.raw_._malloc(a+1),this.raw_.HEAPU8.set(e,s),this.raw_.HEAPU8[s+a]=0}else a=t.length,s=this.raw_._malloc(a),this.raw_.HEAPU8.set(t,s);const i=this.api_.loadSkeleton(s,a,e,e.length,n);return this.raw_._free(s),i}getLastError(){return this.api_.getLastError()}unloadSkeleton(t){this.api_.unloadSkeleton(t)}getAtlasPageCount(t){return this.api_.getAtlasPageCount(t)}getAtlasPageTextureName(t,e){return this.api_.getAtlasPageTextureName(t,e)}setAtlasPageTexture(t,e,n,s,a){this.api_.setAtlasPageTexture(t,e,n,s,a)}createInstance(t){return this.api_.createInstance(t)}destroyInstance(t){this.api_.destroyInstance(t),this.listeners_.delete(t)}play(t,e,n=!0,s=0){return!!this.api_.playAnimation(t,e,n,s)}addAnimation(t,e,n=!0,s=0,a=0){return!!this.api_.addAnimation(t,e,n,s,a)}setSkin(t,e){this.api_.setSkin(t,e)}update(t,e){this.api_.update(t,e)}getAnimations(t){const e=this.api_.getAnimations(t);try{return JSON.parse(e)}catch{return[]}}getSkins(t){const e=this.api_.getSkins(t);try{return JSON.parse(e)}catch{return[]}}getBonePosition(t,e){const n=this.raw_._malloc(4),s=this.raw_._malloc(4);if(!this.api_.getBonePosition(t,e,n,s))return this.raw_._free(n),this.raw_._free(s),null;const a=this.raw_.HEAPF32[n>>2],i=this.raw_.HEAPF32[s>>2];return this.raw_._free(n),this.raw_._free(s),{x:a,y:i}}getBoneRotation(t,e){return this.api_.getBoneRotation(t,e)}getBounds(t){const e=this.raw_._malloc(16);this.api_.getBounds(t,e,e+4,e+8,e+12);const n=this.raw_.HEAPF32,s=e>>2,a={x:n[s],y:n[s+1],width:n[s+2],height:n[s+3]};return this.raw_._free(e),a}extractMeshBatches(t){const e=this.api_.getMeshBatchCount(t),n=[],s=this.raw_._malloc(8),a=s,i=s+4;for(let s=0;s<e;s++){const e=this.api_.getMeshBatchVertexCount(t,s),r=this.api_.getMeshBatchIndexCount(t,s);if(e<=0||r<=0)continue;const o=8*e*4,l=2*r,c=this.raw_._malloc(o),h=this.raw_._malloc(l);this.api_.getMeshBatchData(t,s,c,h,a,i);const _=new Float32Array(this.raw_.HEAPF32.buffer,c,8*e),d=new Uint16Array(this.raw_.HEAPU8.buffer,h,r);n.push({vertices:new Float32Array(_),indices:new Uint16Array(d),textureId:this.raw_.HEAPU32[a>>2],blendMode:this.raw_.HEAPU32[i>>2]}),this.raw_._free(c),this.raw_._free(h)}return this.raw_._free(s),n}on(t,e,n){this.listeners_.has(t)||this.listeners_.set(t,new Map);const s=this.listeners_.get(t);s.has(e)||s.set(e,new Set),s.get(e).add(n)}off(t,e,n){const s=this.listeners_.get(t);if(!s)return;const a=s.get(e);a&&a.delete(n)}removeAllListeners(t){this.listeners_.delete(t)}}const o=s(null,"SpineController"),l=new Float32Array(16);function c(t,e,n,s){const a=t.worldScale.x*e*(n?-1:1),i=t.worldScale.y*e*(s?-1:1),r=t.worldScale.z,o=t.worldRotation.x,c=t.worldRotation.y,h=t.worldRotation.z,_=t.worldRotation.w,d=o+o,u=c+c,p=h+h,w=o*d,g=o*u,f=o*p,m=c*u,A=c*p,S=h*p,y=_*d,P=_*u,k=_*p;return l[0]=(1-(m+S))*a,l[1]=(g+k)*a,l[2]=(f-P)*a,l[3]=0,l[4]=(g-k)*i,l[5]=(1-(w+S))*i,l[6]=(A+y)*i,l[7]=0,l[8]=(f+P)*r,l[9]=(A-y)*r,l[10]=(1-(w+m))*r,l[11]=0,l[12]=t.worldPosition.x,l[13]=t.worldPosition.y,l[14]=t.worldPosition.z,l[15]=1,l}class h{constructor(t,e){this.wasmUrl_=t,this.factory_=e}build(s){const l=s.wasmModule,h=a(this.wasmUrl_,this.factory_).then(({raw:a,api:h})=>{const _=new r(a,h);s.insertResource(o,_),s.hasResource(i)&&s.getResource(i).setSpineController(_);const d=new Map,u=new Map,p=new Map,w={_id:Symbol("SpineAutoSystem"),_name:"SpineAutoSystem",_params:[],_fn:()=>{const t=s.world,n=s.hasResource(i)?s.getResource(i):null;if(!n)return;const a=t.getEntitiesWithComponents([e]),r=new Set;for(const s of a){r.add(s);const a=t.get(s,e),i=`${a.skeletonPath}:${a.atlasPath}`;if(!d.has(s)||u.get(s)!==i){d.has(s)&&(_.destroyInstance(d.get(s)),d.delete(s),u.delete(s),p.delete(s));const t=n.getSpineSkeletonHandle(a.skeletonPath,a.atlasPath);if(void 0===t)continue;const e=_.createInstance(t);if(e<0)continue;d.set(s,e),u.set(s,i),a.skin&&_.setSkin(e,a.skin),a.animation&&_.play(e,a.animation,a.loop),p.set(s,{animation:a.animation,skin:a.skin,loop:a.loop});continue}const o=p.get(s);if(!o)continue;const l=d.get(s);o.skin!==a.skin&&(_.setSkin(l,a.skin),o.skin=a.skin),o.animation===a.animation&&o.loop===a.loop||(a.animation&&_.play(l,a.animation,a.loop),o.animation=a.animation,o.loop=a.loop)}for(const[t,e]of d)r.has(t)||(_.destroyInstance(e),d.delete(t),u.delete(t),p.delete(t))}};if(s.addSystemToSchedule(t.PreUpdate,w),!s.pipeline?.spineRenderer){let t=0;s.setSpineRenderer((a,i)=>{let r=i-t;t=i,(r<=0||r>.5)&&(r=1/60);const o=s.world;for(const[t,s]of d){const a=o.has(t,e)?o.get(t,e):null,i=!1!==a?.playing,h=a?.timeScale??1;let d;if(i&&_.update(s,r*h),o.has(t,n)){d=c(o.get(t,n),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1)}const u=a?.color;S(l,_,s,d,u)}})}return{controller:_,coreModule:l}});s.insertResource(o,null),h.catch(()=>{}),s.spineInitPromise=h}}let _=new Float32Array(0),d=0,u=0,p=0,g=0,f=0,m=null;function A(t,e,n,s){if(e&&n>=s)return[e,n];e&&t._free(e);const a=2*s;return[t._malloc(a),a]}function S(t,e,n,s,a){m&&m!==t&&m&&(d&&(m._free(d),d=0,u=0),p&&(m._free(p),p=0,g=0),f&&(m._free(f),f=0),m=null),m=t;const i=e.extractMeshBatches(n);s&&(f||(f=t._malloc(64)),t.HEAPF32.set(s,f>>2));const r=a&&(1!==a.r||1!==a.g||1!==a.b||1!==a.a);for(const e of i){let n=e.vertices;if(r){const t=e.blendMode>=4;_.length<n.length&&(_=new Float32Array(2*n.length)),_.set(n);const s=_.subarray(0,n.length);for(let e=0;e<s.length;e+=8)t?(s[e+4]*=a.r*a.a,s[e+5]*=a.g*a.a,s[e+6]*=a.b*a.a):(s[e+4]*=a.r,s[e+5]*=a.g,s[e+6]*=a.b),s[e+7]*=a.a;n=s}const i=n.byteLength,o=e.indices.byteLength;[d,u]=A(t,d,u,i),[p,g]=A(t,p,g,o),t.HEAPF32.set(n,d>>2),new Uint16Array(t.HEAPU8.buffer,p,e.indices.length).set(e.indices),t.renderer_submitTriangles(d,n.length/8,p,e.indices.length,e.textureId,e.blendMode,s?f:0)}}export{r as SpineModuleController,h as SpinePlugin,o as SpineResource,a as loadSpineModule,S as submitSpineMeshesToCore};
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.ts
index c76f2a463..260f04bba 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -1,538 +1 @@
-/**
- * @file types.ts
- * @brief Core type definitions for ESEngine SDK
- */
-type Entity = number;
-interface Vec2 {
- x: number;
- y: number;
-}
-interface Vec3 {
- x: number;
- y: number;
- z: number;
-}
-interface Vec4 {
- x: number;
- y: number;
- z: number;
- w: number;
-}
-interface Quat {
- w: number;
- x: number;
- y: number;
- z: number;
-}
-
-/**
- * @file wasm.generated.ts
- * @brief ESEngine WASM Bindings TypeScript Definitions
- * @details Generated by EHT - DO NOT EDIT
- */
-
-interface UVec2 {
- x: number;
- y: number;
-}
-interface VectorEntity {
- size(): number;
- get(index: number): number;
- push_back(value: number): void;
- set(index: number, value: number): boolean;
- delete(): void;
-}
-interface UIRect {
- anchorMin: Vec2;
- anchorMax: Vec2;
- offsetMin: Vec2;
- offsetMax: Vec2;
- size: Vec2;
- pivot: Vec2;
-}
-interface FlexItem {
- flexGrow: number;
- flexShrink: number;
- flexBasis: number;
- order: number;
-}
-interface BoxCollider {
- halfExtents: Vec2;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CircleCollider {
- radius: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface CapsuleCollider {
- radius: number;
- halfHeight: number;
- offset: Vec2;
- density: number;
- friction: number;
- restitution: number;
- isSensor: boolean;
- enabled: boolean;
-}
-interface ParticleEmitter {
- rate: number;
- burstCount: number;
- burstInterval: number;
- duration: number;
- looping: boolean;
- playOnStart: boolean;
- maxParticles: number;
- lifetimeMin: number;
- lifetimeMax: number;
- shape: number;
- shapeRadius: number;
- shapeSize: Vec2;
- shapeAngle: number;
- speedMin: number;
- speedMax: number;
- angleSpreadMin: number;
- angleSpreadMax: number;
- startSizeMin: number;
- startSizeMax: number;
- endSizeMin: number;
- endSizeMax: number;
- sizeEasing: number;
- startColor: Vec4;
- endColor: Vec4;
- colorEasing: number;
- rotationMin: number;
- rotationMax: number;
- angularVelocityMin: number;
- angularVelocityMax: number;
- gravity: Vec2;
- damping: number;
- texture: number;
- spriteColumns: number;
- spriteRows: number;
- spriteFPS: number;
- spriteLoop: boolean;
- blendMode: number;
- layer: number;
- material: number;
- simulationSpace: number;
- enabled: boolean;
-}
-interface Transform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
- worldPosition: Vec3;
- worldRotation: Quat;
- worldScale: Vec3;
-}
-interface Velocity {
- linear: Vec3;
- angular: Vec3;
-}
-interface SpineAnimation {
- skeletonPath: string;
- atlasPath: string;
- skin: string;
- animation: string;
- timeScale: number;
- loop: boolean;
- playing: boolean;
- flipX: boolean;
- flipY: boolean;
- color: Vec4;
- layer: number;
- skeletonScale: number;
- material: number;
- enabled: boolean;
-}
-interface Interactable {
- enabled: boolean;
- blockRaycast: boolean;
- raycastTarget: boolean;
-}
-interface UIInteraction {
- hovered: boolean;
- pressed: boolean;
- justPressed: boolean;
- justReleased: boolean;
-}
-interface RigidBody {
- bodyType: number;
- gravityScale: number;
- linearDamping: number;
- angularDamping: number;
- fixedRotation: boolean;
- bullet: boolean;
- enabled: boolean;
-}
-interface BitmapText {
- text: string;
- color: Vec4;
- fontSize: number;
- align: number;
- spacing: number;
- layer: number;
- font: number;
- enabled: boolean;
-}
-interface Sprite {
- texture: number;
- color: Vec4;
- size: Vec2;
- uvOffset: Vec2;
- uvScale: Vec2;
- layer: number;
- flipX: boolean;
- flipY: boolean;
- material: number;
- enabled: boolean;
-}
-interface UIMask {
- enabled: boolean;
- mode: number;
-}
-interface FlexContainer {
- direction: number;
- wrap: number;
- justifyContent: number;
- alignItems: number;
- gap: Vec2;
- padding: Vec4;
-}
-interface Parent {
- entity: number;
-}
-interface Children {
- entities: VectorEntity;
-}
-interface ScreenSpace {
-}
-interface Canvas {
- designResolution: UVec2;
- pixelsPerUnit: number;
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: Vec4;
-}
-interface Camera {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- aspectRatio: number;
- isActive: boolean;
- priority: number;
- viewportX: number;
- viewportY: number;
- viewportW: number;
- viewportH: number;
- clearFlags: number;
-}
-interface Registry {
- create(): Entity;
- destroy(entity: Entity): void;
- valid(entity: Entity): boolean;
- entityCount(): number;
- hasUIRect(entity: Entity): boolean;
- getUIRect(entity: Entity): UIRect;
- addUIRect(entity: Entity, component: UIRect): void;
- removeUIRect(entity: Entity): void;
- hasFlexItem(entity: Entity): boolean;
- getFlexItem(entity: Entity): FlexItem;
- addFlexItem(entity: Entity, component: FlexItem): void;
- removeFlexItem(entity: Entity): void;
- hasBoxCollider(entity: Entity): boolean;
- getBoxCollider(entity: Entity): BoxCollider;
- addBoxCollider(entity: Entity, component: BoxCollider): void;
- removeBoxCollider(entity: Entity): void;
- hasCircleCollider(entity: Entity): boolean;
- getCircleCollider(entity: Entity): CircleCollider;
- addCircleCollider(entity: Entity, component: CircleCollider): void;
- removeCircleCollider(entity: Entity): void;
- hasCapsuleCollider(entity: Entity): boolean;
- getCapsuleCollider(entity: Entity): CapsuleCollider;
- addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
- removeCapsuleCollider(entity: Entity): void;
- hasParticleEmitter(entity: Entity): boolean;
- getParticleEmitter(entity: Entity): ParticleEmitter;
- addParticleEmitter(entity: Entity, component: ParticleEmitter): void;
- removeParticleEmitter(entity: Entity): void;
- hasTransform(entity: Entity): boolean;
- getTransform(entity: Entity): Transform;
- addTransform(entity: Entity, component: Transform): void;
- removeTransform(entity: Entity): void;
- hasVelocity(entity: Entity): boolean;
- getVelocity(entity: Entity): Velocity;
- addVelocity(entity: Entity, component: Velocity): void;
- removeVelocity(entity: Entity): void;
- hasSpineAnimation(entity: Entity): boolean;
- getSpineAnimation(entity: Entity): SpineAnimation;
- addSpineAnimation(entity: Entity, component: SpineAnimation): void;
- removeSpineAnimation(entity: Entity): void;
- hasInteractable(entity: Entity): boolean;
- getInteractable(entity: Entity): Interactable;
- addInteractable(entity: Entity, component: Interactable): void;
- removeInteractable(entity: Entity): void;
- hasUIInteraction(entity: Entity): boolean;
- getUIInteraction(entity: Entity): UIInteraction;
- addUIInteraction(entity: Entity, component: UIInteraction): void;
- removeUIInteraction(entity: Entity): void;
- hasRigidBody(entity: Entity): boolean;
- getRigidBody(entity: Entity): RigidBody;
- addRigidBody(entity: Entity, component: RigidBody): void;
- removeRigidBody(entity: Entity): void;
- hasBitmapText(entity: Entity): boolean;
- getBitmapText(entity: Entity): BitmapText;
- addBitmapText(entity: Entity, component: BitmapText): void;
- removeBitmapText(entity: Entity): void;
- hasSprite(entity: Entity): boolean;
- getSprite(entity: Entity): Sprite;
- addSprite(entity: Entity, component: Sprite): void;
- removeSprite(entity: Entity): void;
- hasUIMask(entity: Entity): boolean;
- getUIMask(entity: Entity): UIMask;
- addUIMask(entity: Entity, component: UIMask): void;
- removeUIMask(entity: Entity): void;
- hasFlexContainer(entity: Entity): boolean;
- getFlexContainer(entity: Entity): FlexContainer;
- addFlexContainer(entity: Entity, component: FlexContainer): void;
- removeFlexContainer(entity: Entity): void;
- hasParent(entity: Entity): boolean;
- getParent(entity: Entity): Parent;
- addParent(entity: Entity, component: Parent): void;
- removeParent(entity: Entity): void;
- hasChildren(entity: Entity): boolean;
- getChildren(entity: Entity): Children;
- addChildren(entity: Entity, component: Children): void;
- removeChildren(entity: Entity): void;
- hasScreenSpace(entity: Entity): boolean;
- getScreenSpace(entity: Entity): ScreenSpace;
- addScreenSpace(entity: Entity, component: ScreenSpace): void;
- removeScreenSpace(entity: Entity): void;
- hasCanvas(entity: Entity): boolean;
- getCanvas(entity: Entity): Canvas;
- addCanvas(entity: Entity, component: Canvas): void;
- removeCanvas(entity: Entity): void;
- hasCamera(entity: Entity): boolean;
- getCamera(entity: Entity): Camera;
- addCamera(entity: Entity, component: Camera): void;
- removeCamera(entity: Entity): void;
- setParent(child: Entity, parent: Entity): void;
-}
-
-/**
- * @file wasm.ts
- * @brief WASM module type definitions
- */
-
-interface CppRegistry extends Registry {
- delete(): void;
- removeParent(entity: Entity): void;
- [key: string]: Function | undefined;
-}
-interface CppResourceManager {
- createTexture(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean): number;
- createTextureEx(width: number, height: number, pixels: number, pixelsLen: number, format: number, flipY: boolean, filterMode: number, wrapMode: number): number;
- createShader(vertSrc: string, fragSrc: string): number;
- registerExternalTexture(glTextureId: number, width: number, height: number): number;
- getTextureGLId(handle: number): number;
- releaseTexture(handle: number): void;
- releaseShader(handle: number): void;
- setTextureMetadata(handle: number, left: number, right: number, top: number, bottom: number): void;
- registerTextureWithPath(handle: number, path: string): void;
- loadBitmapFont(fntContent: string, textureHandle: number, texWidth: number, texHeight: number): number;
- createLabelAtlasFont(textureHandle: number, texWidth: number, texHeight: number, chars: string, charWidth: number, charHeight: number): number;
- releaseBitmapFont(handle: number): void;
- measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): {
- width: number;
- height: number;
- };
-}
-interface EmscriptenFS {
- writeFile(path: string, data: string | Uint8Array): void;
- readFile(path: string, opts?: {
- encoding?: string;
- }): string | Uint8Array;
- mkdir(path: string): void;
- mkdirTree(path: string): void;
- unlink(path: string): void;
- stat(path: string): {
- mode: number;
- size: number;
- };
- isFile(mode: number): boolean;
- isDir(mode: number): boolean;
- analyzePath(path: string): {
- exists: boolean;
- parentExists: boolean;
- };
-}
-interface SpineBounds {
- x: number;
- y: number;
- width: number;
- height: number;
- valid: boolean;
-}
-interface ESEngineModule {
- Registry: new () => CppRegistry;
- HEAPU8: Uint8Array;
- HEAPU32: Uint32Array;
- HEAPF32: Float32Array;
- FS: EmscriptenFS;
- materialDataProvider?: (materialId: number, outShaderIdPtr: number, outBlendModePtr: number, outUniformBufferPtr: number, outUniformCountPtr: number) => void;
- initRenderer(): void;
- initRendererWithCanvas(canvasSelector: string): boolean;
- initRendererWithContext(contextHandle: number): boolean;
- shutdownRenderer(): void;
- GL: {
- registerContext(ctx: WebGLRenderingContext | WebGL2RenderingContext, options: {
- majorVersion: number;
- minorVersion: number;
- enableExtensionsByDefault?: boolean;
- }): number;
- };
- renderFrame(registry: CppRegistry, width: number, height: number): void;
- renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;
- getResourceManager(): CppResourceManager;
- getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;
- invalidateMaterialCache(materialId: number): void;
- clearMaterialCache(): void;
- draw_begin(matrixPtr: number): void;
- draw_end(): void;
- draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_rect(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
- draw_rectOutline(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
- draw_circle(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
- draw_circleOutline(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
- draw_texture(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_textureRotated(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
- draw_setLayer(layer: number): void;
- draw_setDepth(depth: number): void;
- draw_getDrawCallCount(): number;
- draw_getPrimitiveCount(): number;
- draw_setBlendMode(mode: number): void;
- draw_setDepthTest(enabled: boolean): void;
- draw_mesh(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
- draw_meshWithUniforms(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
- geometry_create(): number;
- geometry_init(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
- geometry_setIndices16(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_setIndices32(handle: number, indicesPtr: number, indexCount: number): void;
- geometry_updateVertices(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
- geometry_release(handle: number): void;
- geometry_isValid(handle: number): boolean;
- postprocess_init(width: number, height: number): boolean;
- postprocess_shutdown(): void;
- postprocess_resize(width: number, height: number): void;
- postprocess_addPass(name: string, shaderHandle: number): number;
- postprocess_removePass(name: string): void;
- postprocess_setPassEnabled(name: string, enabled: boolean): void;
- postprocess_isPassEnabled(name: string): boolean;
- postprocess_setUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- postprocess_begin(): void;
- postprocess_end(): void;
- postprocess_getPassCount(): number;
- postprocess_isInitialized(): boolean;
- postprocess_setBypass(bypass: boolean): void;
- postprocess_isBypassed(): boolean;
- postprocess_clearPasses(): void;
- postprocess_setOutputTarget(fboId: number): void;
- postprocess_setOutputViewport(x: number, y: number, w: number, h: number): void;
- postprocess_beginScreenCapture(): void;
- postprocess_endScreenCapture(): void;
- postprocess_executeScreenPasses(): void;
- postprocess_addScreenPass(name: string, shaderHandle: number): number;
- postprocess_clearScreenPasses(): void;
- postprocess_setScreenUniformFloat(passName: string, uniform: string, value: number): void;
- postprocess_setScreenUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
- renderer_init(width: number, height: number): void;
- renderer_resize(width: number, height: number): void;
- renderer_begin(matrixPtr: number, targetHandle: number): void;
- renderer_flush(): void;
- renderer_end(): void;
- renderer_submitSprites(registry: CppRegistry): void;
- renderer_submitBitmapText(registry: CppRegistry): void;
- renderer_submitSpine?(registry: CppRegistry): void;
- renderer_submitParticles?(registry: CppRegistry): void;
- renderer_submitTriangles(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number): void;
- particle_update?(registry: CppRegistry, dt: number): void;
- particle_play?(registry: CppRegistry, entity: number): void;
- particle_stop?(registry: CppRegistry, entity: number): void;
- particle_reset?(registry: CppRegistry, entity: number): void;
- particle_getAliveCount?(entity: number): number;
- tilemap_initLayer?(entity: number, width: number, height: number, tileWidth: number, tileHeight: number): void;
- tilemap_destroyLayer?(entity: number): void;
- tilemap_setTile?(entity: number, x: number, y: number, tileId: number): void;
- tilemap_getTile?(entity: number, x: number, y: number): number;
- tilemap_fillRect?(entity: number, x: number, y: number, w: number, h: number, tileId: number): void;
- tilemap_setTiles?(entity: number, tilesPtr: number, count: number): void;
- tilemap_hasLayer?(entity: number): boolean;
- tilemap_submitLayer?(entity: number, textureId: number, sortLayer: number, depth: number, tilesetColumns: number, uvTileWidth: number, uvTileHeight: number, originX: number, originY: number, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- renderer_setStage(stage: number): void;
- renderer_createTarget(width: number, height: number, flags: number): number;
- renderer_releaseTarget(handle: number): void;
- renderer_getTargetTexture(handle: number): number;
- renderer_getTargetDepthTexture(handle: number): number;
- renderer_getDrawCalls(): number;
- renderer_getTriangles(): number;
- renderer_getSprites(): number;
- renderer_getText(): number;
- renderer_getSpine?(): number;
- renderer_getMeshes(): number;
- renderer_getCulled(): number;
- renderer_setClearColor(r: number, g: number, b: number, a: number): void;
- renderer_setViewport(x: number, y: number, w: number, h: number): void;
- renderer_setScissor(x: number, y: number, w: number, h: number, enable: boolean): void;
- renderer_clearBuffers(flags: number): void;
- renderer_setEntityClipRect(entity: number, x: number, y: number, w: number, h: number): void;
- renderer_clearEntityClipRect(entity: number): void;
- renderer_clearAllClipRects(): void;
- renderer_clearStencil(): void;
- renderer_setEntityStencilMask(entity: number, refValue: number): void;
- renderer_setEntityStencilTest(entity: number, refValue: number): void;
- renderer_clearEntityStencilMask(entity: number): void;
- renderer_clearAllStencilMasks(): void;
- registry_getCanvasEntity(registry: CppRegistry): number;
- registry_getCameraEntities(registry: CppRegistry): number[];
- getChildEntities(registry: CppRegistry, entity: number): number[];
- registry_getGeneration(registry: CppRegistry, entity: number): number;
- registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;
- gl_enableErrorCheck(enabled: boolean): void;
- gl_checkErrors(context: string): number;
- renderer_diagnose(): void;
- uiLayout_update(registry: CppRegistry, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
- uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
- uiHitTest_getHitEntity(): number;
- uiHitTest_getHitEntityPrev(): number;
- uiRenderOrder_update(registry: CppRegistry): void;
- uiFlexLayout_update(registry: CppRegistry): void;
- getUIRectComputedWidth(registry: CppRegistry, entity: number): number;
- getUIRectComputedHeight(registry: CppRegistry, entity: number): number;
- transform_update(registry: CppRegistry): void;
- _anim_createTween(registry: CppRegistry, entity: number, targetProp: number, from: number, to: number, duration: number, easing: number, delay: number, loopMode: number, loopCount: number): number;
- _anim_cancelTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_cancelAllTweens(registry: CppRegistry, targetEntity: number): void;
- _anim_pauseTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_resumeTween(registry: CppRegistry, tweenEntity: number): void;
- _anim_setTweenBezier(registry: CppRegistry, tweenEntity: number, p1x: number, p1y: number, p2x: number, p2y: number): void;
- _anim_setSequenceNext(registry: CppRegistry, tweenEntity: number, nextEntity: number): void;
- _anim_updateTweens(registry: CppRegistry, deltaTime: number): void;
- _anim_getTweenState(registry: CppRegistry, tweenEntity: number): number;
- _malloc(size: number): number;
- _free(ptr: number): void;
-}
-
-export type { CppRegistry, CppResourceManager, ESEngineModule, EmscriptenFS, SpineBounds };
+export { c as CppRegistry, e as CppResourceManager, E as ESEngineModule, l as EmscriptenFS, S as SpineBounds } from './shared/wasm.js';
diff --git a/desktop/public/wasm/esengine.single.js b/desktop/public/wasm/esengine.single.js
index ec4f7e66f..f1291685d 100644
Binary files a/desktop/public/wasm/esengine.single.js and b/desktop/public/wasm/esengine.single.js differ
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 16c37b948..c0b7d27bb 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -443,6 +443,7 @@
gravity: { x: config.physicsGravityX ?? 0, y: config.physicsGravityY ?? -9.81 },
fixedTimestep: config.physicsFixedTimestep ?? 1 / 60,
subStepCount: config.physicsSubStepCount ?? 4,
+ collisionLayerMasks: config.collisionLayerMasks,
}, window.ESPhysicsModule);
} catch (e) {
console.warn('Physics module load skipped:', e);
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 450d1e18d..908a165a8 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -77,6 +77,15 @@ const SPINE_WASM_MAP: Record<string, string> = {
'4.2': '/wasm/spine42.js',
};
+async function loadPhysicsFactory(editor: Editor): Promise<void> {
+ try {
+ const factory = await loadUmdModule('/wasm/physics.js', 'ESPhysicsModule');
+ editor.setPhysicsFactory(factory);
+ } catch (e) {
+ console.warn('Failed to load physics module:', e);
+ }
+}
+
async function openEditor(container: HTMLElement, projectPath: string): Promise<void> {
const editor = createEditor(container, { projectPath });
console.log('ESEngine Editor opened project:', projectPath);
@@ -90,6 +99,9 @@ async function openEditor(container: HTMLElement, projectPath: string): Promise<
}
const config = await loadProjectConfig(projectPath);
+
+ await loadPhysicsFactory(editor);
+
const spineVersion = config?.spineVersion ?? '4.2';
await loadSpineModule(editor, spineVersion);
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index c1336ac5b..9fe6d610b 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -195,6 +195,10 @@ export class Editor {
this.panelManager_.setApp(app, this.bridge_);
}
+ setPhysicsFactory(factory: unknown): void {
+ getSharedRenderContext().setPhysicsFactory(factory);
+ }
+
setSpineModule(module: unknown, version: string): void {
this.spineModule_ = module;
this.spineVersion_ = version;
diff --git a/editor/src/PreviewManager.ts b/editor/src/PreviewManager.ts
index 6f3d48c6b..d3fc79003 100644
--- a/editor/src/PreviewManager.ts
+++ b/editor/src/PreviewManager.ts
@@ -1,6 +1,6 @@
import type { SceneData } from './types/SceneTypes';
import { PreviewService } from './preview';
-import { getSettingsValue } from './settings';
+import { getSettingsValue, MAX_COLLISION_LAYERS } from './settings';
import type { ScriptLoader } from './scripting';
export class PreviewManager {
@@ -85,11 +85,15 @@ export class PreviewManager {
private collectPreviewConfig(spineVersion: string) {
const enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;
+ const collisionLayerMasks = Array.from({ length: MAX_COLLISION_LAYERS }, (_, i) =>
+ getSettingsValue<number>(`physics.layerMask${i}`) ?? 0xFFFF
+ );
const physicsConfig = enablePhysics ? {
gravityX: getSettingsValue<number>('physics.gravityX') ?? 0,
gravityY: getSettingsValue<number>('physics.gravityY') ?? -9.81,
fixedTimestep: getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60,
subStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,
+ collisionLayerMasks,
} : undefined;
const previewSpineVersion = spineVersion === 'none' ? undefined : spineVersion;
const runtimeConfig = {
diff --git a/editor/src/builder/BuildService.ts b/editor/src/builder/BuildService.ts
index 5ce062b76..f51d24816 100644
--- a/editor/src/builder/BuildService.ts
+++ b/editor/src/builder/BuildService.ts
@@ -14,6 +14,7 @@ import { BuildProgressReporter, formatDuration } from './BuildProgress';
import { BuildHistory } from './BuildHistory';
import { getProjectDir } from '../utils/path';
import { getSettingsValue } from '../settings/SettingsRegistry';
+import { MAX_COLLISION_LAYERS } from '../settings/collisionLayers';
import { getEditorContext } from '../context/EditorContext';
// =============================================================================
@@ -50,6 +51,7 @@ export interface BuildContext {
physicsGravity?: { x: number; y: number };
physicsFixedTimestep?: number;
physicsSubStepCount?: number;
+ collisionLayerMasks?: number[];
runtimeConfig?: RuntimeBuildConfig;
progress?: BuildProgressReporter;
cache?: BuildCache;
@@ -102,6 +104,9 @@ export class BuildService {
},
physicsFixedTimestep: getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60,
physicsSubStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,
+ collisionLayerMasks: Array.from({ length: MAX_COLLISION_LAYERS }, (_, i) =>
+ getSettingsValue<number>(`physics.layerMask${i}`) ?? 0xFFFF
+ ),
runtimeConfig: {
sceneTransitionDuration: getSettingsValue<number>('runtime.sceneTransitionDuration') ?? 0.3,
sceneTransitionColor: getSettingsValue<string>('runtime.sceneTransitionColor') ?? '#000000',
diff --git a/editor/src/builder/PlayableEmitter.ts b/editor/src/builder/PlayableEmitter.ts
index b89bc011e..a98f9d2ad 100644
--- a/editor/src/builder/PlayableEmitter.ts
+++ b/editor/src/builder/PlayableEmitter.ts
@@ -420,6 +420,7 @@ const __plugins = [${pluginList}];
gravity: context.physicsGravity ?? { x: 0, y: -9.81 },
fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,
subStepCount: context.physicsSubStepCount ?? 4,
+ collisionLayerMasks: context.collisionLayerMasks,
});
const enableCTA = context.config.playableSettings?.enableBuiltinCTA ?? false;
diff --git a/editor/src/builder/WeChatEmitter.ts b/editor/src/builder/WeChatEmitter.ts
index d2da73940..2156862ba 100644
--- a/editor/src/builder/WeChatEmitter.ts
+++ b/editor/src/builder/WeChatEmitter.ts
@@ -230,6 +230,7 @@ export class WeChatEmitter implements PlatformEmitter {
gravity: context.physicsGravity ?? { x: 0, y: -9.81 },
fixedTimestep: context.physicsFixedTimestep ?? 1 / 60,
subStepCount: context.physicsSubStepCount ?? 4,
+ collisionLayerMasks: context.collisionLayerMasks,
});
const gameJs = generateWeChatGameJs({
diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.ts
index a36721802..9c0db4bbe 100644
--- a/editor/src/preview/PreviewService.ts
+++ b/editor/src/preview/PreviewService.ts
@@ -43,7 +43,7 @@ export class PreviewService {
this.previewDir_ = `${this.projectDir_}/.esengine/preview`;
}
- async startPreview(scene: SceneData, compiledScript?: string, spineVersion?: string, enablePhysics?: boolean, physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number }, runtimeConfig?: Record<string, unknown>): Promise<number | null> {
+ async startPreview(scene: SceneData, compiledScript?: string, spineVersion?: string, enablePhysics?: boolean, physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number; collisionLayerMasks?: number[] }, runtimeConfig?: Record<string, unknown>): Promise<number | null> {
const fs = this.getNativeFS();
const invoke = this.getTauriInvoke();
@@ -70,7 +70,7 @@ export class PreviewService {
return port;
}
- async startServer(scene: SceneData, compiledScript?: string, spineVersion?: string, enablePhysics?: boolean, physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number }, runtimeConfig?: Record<string, unknown>): Promise<number | null> {
+ async startServer(scene: SceneData, compiledScript?: string, spineVersion?: string, enablePhysics?: boolean, physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number; collisionLayerMasks?: number[] }, runtimeConfig?: Record<string, unknown>): Promise<number | null> {
const fs = this.getNativeFS();
const invoke = this.getTauriInvoke();
@@ -108,7 +108,7 @@ export class PreviewService {
compiledScript?: string,
spineVersion?: string,
enablePhysics?: boolean,
- physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number },
+ physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number; collisionLayerMasks?: number[] },
runtimeConfig?: Record<string, unknown>,
): Promise<void> {
const fs = this.getNativeFS();
@@ -123,7 +123,7 @@ export class PreviewService {
compiledScript?: string,
spineVersion?: string,
enablePhysics?: boolean,
- physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number },
+ physicsConfig?: { gravityX: number; gravityY: number; fixedTimestep: number; subStepCount: number; collisionLayerMasks?: number[] },
runtimeConfig?: Record<string, unknown>,
): Promise<void> {
await this.ensureDirectory(fs, this.previewDir_);
@@ -150,6 +150,7 @@ export class PreviewService {
physicsGravityY: physicsConfig?.gravityY ?? -9.81,
physicsFixedTimestep: physicsConfig?.fixedTimestep ?? 1 / 60,
physicsSubStepCount: physicsConfig?.subStepCount ?? 4,
+ collisionLayerMasks: physicsConfig?.collisionLayerMasks,
...runtimeConfig,
}));
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 8e618ad5a..c4053365e 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -18,6 +18,7 @@ import { createButtonTransitionEditor } from './buttonTransitionEditor';
import { openEntityPicker } from './EntityPicker';
import { setupDragLabel, colorToHex, hexToColor } from './editorUtils';
import { validateNumber, validateVec2, validateVec3, validateColor, showValidationError } from './validation';
+import { getNamedLayers, layerIndexFromBits, bitsFromLayerIndex } from '../settings/collisionLayers';
export { setupDragLabel, colorToHex, hexToColor };
// =============================================================================
@@ -2175,6 +2176,53 @@ function createTilemapFileEditor(
};
}
+// =============================================================================
+// Collision Layer Editor
+// =============================================================================
+
+function createCollisionLayerEditor(
+ container: HTMLElement,
+ ctx: PropertyEditorContext
+): PropertyEditorInstance {
+ const { value, onChange } = ctx;
+
+ const select = document.createElement('select');
+ select.className = 'es-input es-input-select';
+
+ function populateOptions(): void {
+ select.innerHTML = '';
+ const layers = getNamedLayers();
+ for (const layer of layers) {
+ const option = document.createElement('option');
+ option.value = String(layer.index);
+ option.textContent = `${layer.index}: ${layer.name}`;
+ select.appendChild(option);
+ }
+ }
+
+ populateOptions();
+ const currentIndex = layerIndexFromBits(value as number);
+ select.value = String(currentIndex);
+
+ select.addEventListener('change', () => {
+ const idx = parseInt(select.value, 10);
+ onChange(bitsFromLayerIndex(idx));
+ });
+
+ container.appendChild(select);
+
+ return {
+ update(newValue: unknown) {
+ populateOptions();
+ const idx = layerIndexFromBits(newValue as number);
+ select.value = String(idx);
+ },
+ dispose() {
+ select.remove();
+ },
+ };
+}
+
// =============================================================================
// Register All Editors
// =============================================================================
@@ -2204,4 +2252,5 @@ export function registerBuiltinEditors(): void {
registerPropertyEditor('anim-file', createAnimFileEditor);
registerPropertyEditor('audio-file', createAudioFileEditor);
registerPropertyEditor('tilemap-file', createTilemapFileEditor);
+ registerPropertyEditor('collision-layer', createCollisionLayerEditor);
}
diff --git a/editor/src/renderer/SharedRenderContext.ts b/editor/src/renderer/SharedRenderContext.ts
index 89e0e0ea3..03bdebda3 100644
--- a/editor/src/renderer/SharedRenderContext.ts
+++ b/editor/src/renderer/SharedRenderContext.ts
@@ -32,6 +32,7 @@ import {
tilemapPlugin,
sceneManagerPlugin,
} from 'esengine';
+import { PhysicsPlugin, type PhysicsPluginConfig } from 'esengine/physics';
import type { SpineModuleController } from 'esengine/spine';
import { EditorSceneManager } from '../scene/EditorSceneManager';
import { AssetPathResolver } from '../asset';
@@ -60,6 +61,7 @@ export class SharedRenderContext {
private animationId_: number | null = null;
private continuousRender_ = false;
private isDirty_ = true;
+ private physicsFactory_: unknown = null;
private sceneViewportW_ = 0;
private sceneViewportH_ = 0;
private gameViewportW_ = 0;
@@ -308,7 +310,23 @@ export class SharedRenderContext {
this.postTickCallback_?.();
}
- enterPlayMode(): void {
+ setPhysicsFactory(factory: unknown): void {
+ this.physicsFactory_ = factory;
+ }
+
+ async enterPlayMode(physicsConfig?: PhysicsPluginConfig): Promise<void> {
+ if (physicsConfig && this.app_) {
+ const plugin = new PhysicsPlugin(
+ '/wasm/physics.js',
+ physicsConfig,
+ this.physicsFactory_ as any,
+ );
+ this.app_.addPlugin(plugin);
+ if (this.app_.physicsInitPromise) {
+ await this.app_.physicsInitPromise;
+ }
+ }
+
this.playMode_ = true;
this.paused_ = false;
this.lastFrameTime_ = performance.now();
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index 66b22fad9..88b6f93c0 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -5,6 +5,7 @@
import type { PropertyMeta } from '../property/PropertyEditor';
import { getComponentDefaults } from 'esengine';
+import { getSettingsValue } from '../settings';
// =============================================================================
// Types
@@ -418,6 +419,7 @@ export const BoxColliderSchema: ComponentSchema = {
{ name: 'friction', type: 'number', min: 0, max: 1, step: 0.01 },
{ name: 'restitution', type: 'number', min: 0, max: 1, step: 0.01 },
{ name: 'isSensor', type: 'boolean' },
+ { name: 'categoryBits', type: 'collision-layer' },
],
};
@@ -431,6 +433,7 @@ export const CircleColliderSchema: ComponentSchema = {
{ name: 'friction', type: 'number', min: 0, max: 1, step: 0.01 },
{ name: 'restitution', type: 'number', min: 0, max: 1, step: 0.01 },
{ name: 'isSensor', type: 'boolean' },
+ { name: 'categoryBits', type: 'collision-layer' },
],
};
@@ -445,6 +448,7 @@ export const CapsuleColliderSchema: ComponentSchema = {
{ name: 'friction', type: 'number', min: 0, max: 1, step: 0.01 },
{ name: 'restitution', type: 'number', min: 0, max: 1, step: 0.01 },
{ name: 'isSensor', type: 'boolean' },
+ { name: 'categoryBits', type: 'collision-layer' },
],
};
@@ -1015,11 +1019,34 @@ const editorInitialOverrides: Record<string, Record<string, unknown>> = {
},
};
+function getDynamicOverrides(typeName: string): Record<string, unknown> | null {
+ switch (typeName) {
+ case 'Sprite': {
+ const w = getSettingsValue<number>('rendering.defaultSpriteWidth');
+ const h = getSettingsValue<number>('rendering.defaultSpriteHeight');
+ if (w != null || h != null) {
+ return { size: { x: w ?? 100, y: h ?? 100 } };
+ }
+ return null;
+ }
+ case 'Canvas': {
+ const ppu = getSettingsValue<number>('rendering.pixelsPerUnit');
+ if (ppu != null) {
+ return { pixelsPerUnit: ppu };
+ }
+ return null;
+ }
+ default:
+ return null;
+ }
+}
+
export function getInitialComponentData(typeName: string): Record<string, unknown> {
const defaults = getDefaultComponentData(typeName);
const overrides = editorInitialOverrides[typeName];
- if (overrides) {
- return { ...defaults, ...overrides };
+ const dynamic = getDynamicOverrides(typeName);
+ if (overrides || dynamic) {
+ return { ...defaults, ...overrides, ...dynamic };
}
return defaults;
}
diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.ts
index d743bf5a5..dad64cb60 100644
--- a/editor/src/services/PlayModeService.ts
+++ b/editor/src/services/PlayModeService.ts
@@ -1,5 +1,6 @@
import type { EntityData } from '../types/SceneTypes';
import { Assets, Name, Parent, Children, getComponent, getComponentAssetFields, Audio, audioPlugin, SceneManager } from 'esengine';
+import { getSettingsValue, MAX_COLLISION_LAYERS } from '../settings';
import type { Entity, World } from 'esengine';
import { getEditorStore, type SceneSnapshot } from '../store/EditorStore';
import { getSharedRenderContext } from '../renderer/SharedRenderContext';
@@ -80,7 +81,20 @@ class PlayModeService {
this.configureAssetBaseUrl(ctx);
this.registerProjectScenes(ctx);
await this.injectUserScripts(ctx);
- ctx.enterPlayMode();
+
+ const enablePhysics = getSettingsValue<boolean>('project.enablePhysics') ?? false;
+ const physicsConfig = enablePhysics ? {
+ gravity: {
+ x: getSettingsValue<number>('physics.gravityX') ?? 0,
+ y: getSettingsValue<number>('physics.gravityY') ?? -9.81,
+ },
+ fixedTimestep: getSettingsValue<number>('physics.fixedTimestep') ?? 1 / 60,
+ subStepCount: getSettingsValue<number>('physics.subStepCount') ?? 4,
+ collisionLayerMasks: Array.from({ length: MAX_COLLISION_LAYERS }, (_, i) =>
+ getSettingsValue<number>(`physics.layerMask${i}`) ?? 0xFFFF
+ ),
+ } : undefined;
+ await ctx.enterPlayMode(physicsConfig);
this.startSharedEntityTracking(ctx);
this.emitStateChange();
diff --git a/editor/src/settings/CollisionMatrixWidget.ts b/editor/src/settings/CollisionMatrixWidget.ts
new file mode 100644
index 000000000..702cfc71e
--- /dev/null
+++ b/editor/src/settings/CollisionMatrixWidget.ts
@@ -0,0 +1,102 @@
+import { getSettingsValue, setSettingsValue, onSettingsChange } from './SettingsRegistry';
+import { getNamedLayers, MAX_COLLISION_LAYERS } from './collisionLayers';
+
+export function renderCollisionMatrix(container: HTMLElement): (() => void) | void {
+ let unsubscribe: (() => void) | null = null;
+
+ function rebuild(): void {
+ container.innerHTML = '';
+ const layers = getNamedLayers();
+
+ if (layers.length === 0) {
+ const empty = document.createElement('div');
+ empty.className = 'es-collision-matrix-empty';
+ empty.textContent = 'No named collision layers. Add layer names above.';
+ container.appendChild(empty);
+ return;
+ }
+
+ const wrapper = document.createElement('div');
+ wrapper.className = 'es-collision-matrix';
+
+ const n = layers.length;
+ const grid = document.createElement('div');
+ grid.className = 'es-collision-matrix-grid';
+ grid.style.gridTemplateColumns = `120px repeat(${n}, 32px)`;
+ grid.style.gridTemplateRows = `48px repeat(${n}, 32px)`;
+
+ const cornerCell = document.createElement('div');
+ cornerCell.className = 'es-collision-matrix-corner';
+ grid.appendChild(cornerCell);
+
+ for (let col = 0; col < n; col++) {
+ const header = document.createElement('div');
+ header.className = 'es-collision-matrix-header';
+ const span = document.createElement('span');
+ span.textContent = layers[col].name;
+ header.appendChild(span);
+ grid.appendChild(header);
+ }
+
+ for (let row = 0; row < n; row++) {
+ const rowLabel = document.createElement('div');
+ rowLabel.className = 'es-collision-matrix-row-label';
+ rowLabel.textContent = layers[row].name;
+ grid.appendChild(rowLabel);
+
+ for (let col = 0; col < n; col++) {
+ const cell = document.createElement('div');
+ cell.className = 'es-collision-matrix-cell';
+
+ if (col > row) {
+ grid.appendChild(cell);
+ continue;
+ }
+
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ const rowIdx = layers[row].index;
+ const colIdx = layers[col].index;
+ const rowMask = getSettingsValue<number>(`physics.layerMask${rowIdx}`) ?? 0xFFFF;
+ checkbox.checked = (rowMask & (1 << colIdx)) !== 0;
+
+ checkbox.addEventListener('change', () => {
+ const checked = checkbox.checked;
+ toggleMask(rowIdx, colIdx, checked);
+ if (rowIdx !== colIdx) {
+ toggleMask(colIdx, rowIdx, checked);
+ }
+ });
+
+ cell.appendChild(checkbox);
+ grid.appendChild(cell);
+ }
+ }
+
+ wrapper.appendChild(grid);
+ container.appendChild(wrapper);
+ }
+
+ function toggleMask(layerA: number, layerB: number, enabled: boolean): void {
+ const key = `physics.layerMask${layerA}`;
+ let mask = getSettingsValue<number>(key) ?? 0xFFFF;
+ if (enabled) {
+ mask |= (1 << layerB);
+ } else {
+ mask &= ~(1 << layerB);
+ }
+ setSettingsValue(key, mask);
+ }
+
+ rebuild();
+
+ unsubscribe = onSettingsChange((id) => {
+ if (id.startsWith('physics.layerName') || id.startsWith('physics.layerMask')) {
+ rebuild();
+ }
+ });
+
+ return () => {
+ unsubscribe?.();
+ };
+}
diff --git a/editor/src/settings/ProjectSettingsSync.ts b/editor/src/settings/ProjectSettingsSync.ts
index 9ac73de93..19d42a4f0 100644
--- a/editor/src/settings/ProjectSettingsSync.ts
+++ b/editor/src/settings/ProjectSettingsSync.ts
@@ -3,6 +3,7 @@ import { loadProjectConfig } from '../launcher/ProjectService';
import { getEditorContext } from '../context/EditorContext';
import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT } from 'esengine';
import type { ProjectConfig, SpineVersion } from '../types/ProjectTypes';
+import { MAX_COLLISION_LAYERS } from './collisionLayers';
type SettingMapping = {
settingId: string;
@@ -147,6 +148,22 @@ const SETTINGS_TO_PROJECT_MAP: SettingMapping[] = [
read: c => c.assetFailureCooldown ?? 5000,
write: (c, v) => { c.assetFailureCooldown = v as number; },
},
+ ...Array.from({ length: MAX_COLLISION_LAYERS }, (_, i): SettingMapping => ({
+ settingId: `physics.layerName${i}`,
+ read: c => c.collisionLayerNames?.[i] ?? (i === 0 ? 'Default' : ''),
+ write: (c, v) => {
+ if (!c.collisionLayerNames) c.collisionLayerNames = Array.from({ length: MAX_COLLISION_LAYERS }, (_, j) => j === 0 ? 'Default' : '');
+ c.collisionLayerNames[i] = v as string;
+ },
+ })),
+ ...Array.from({ length: MAX_COLLISION_LAYERS }, (_, i): SettingMapping => ({
+ settingId: `physics.layerMask${i}`,
+ read: c => c.collisionLayerMasks?.[i] ?? 0xFFFF,
+ write: (c, v) => {
+ if (!c.collisionLayerMasks) c.collisionLayerMasks = Array(MAX_COLLISION_LAYERS).fill(0xFFFF);
+ c.collisionLayerMasks[i] = v as number;
+ },
+ })),
];
const SYNC_PREFIXES = ['project.', 'physics.', 'build.', 'runtime.', 'rendering.', 'asset.'];
diff --git a/editor/src/settings/SettingsDialog.ts b/editor/src/settings/SettingsDialog.ts
index 6c0a67147..ba38dd7b4 100644
--- a/editor/src/settings/SettingsDialog.ts
+++ b/editor/src/settings/SettingsDialog.ts
@@ -63,6 +63,7 @@ export function showSettingsDialog(): void {
const inputElements = new Map<string, HTMLInputElement | HTMLSelectElement>();
const itemRows = new Map<string, HTMLElement>();
const collapsedGroups = new Set<string>();
+ const customDisposers: (() => void)[] = [];
for (const section of sections) {
for (const group of getSectionGroups(section.id)) {
@@ -129,6 +130,8 @@ export function showSettingsDialog(): void {
}
function buildContent(): void {
+ for (const dispose of customDisposers) dispose();
+ customDisposers.length = 0;
content.innerHTML = '';
itemRows.clear();
inputElements.clear();
@@ -282,9 +285,20 @@ export function showSettingsDialog(): void {
}
function renderItem(container: HTMLElement, item: SettingsItemDescriptor): void {
+ if (item.hidden) return;
+
const value = getSettingsValue(item.id);
switch (item.type) {
+ case 'custom': {
+ if (item.render) {
+ const dispose = item.render(container);
+ if (dispose) {
+ customDisposers.push(dispose);
+ }
+ }
+ break;
+ }
case 'boolean': {
const label = document.createElement('label');
label.className = 'es-settings-checkbox-row';
@@ -488,5 +502,7 @@ export function showSettingsDialog(): void {
dialog.open().then(() => {
unsubscribe();
+ for (const dispose of customDisposers) dispose();
+ customDisposers.length = 0;
});
}
diff --git a/editor/src/settings/SettingsRegistry.ts b/editor/src/settings/SettingsRegistry.ts
index b55be1db1..3abf98f01 100644
--- a/editor/src/settings/SettingsRegistry.ts
+++ b/editor/src/settings/SettingsRegistry.ts
@@ -1,4 +1,4 @@
-export type SettingsItemType = 'boolean' | 'number' | 'string' | 'color' | 'select' | 'range';
+export type SettingsItemType = 'boolean' | 'number' | 'string' | 'color' | 'select' | 'range' | 'custom';
export interface SettingsSectionDescriptor {
id: string;
@@ -32,6 +32,8 @@ export interface SettingsItemDescriptor {
group?: string;
tags?: string[];
projectSync?: boolean;
+ hidden?: boolean;
+ render?: (container: HTMLElement) => (() => void) | void;
}
type SettingsChangeListener = (id: string, value: unknown) => void;
@@ -171,6 +173,7 @@ export function getUngroupedSectionItems(sectionId: string): SettingsItemDescrip
export function searchSettings(query: string): SettingsItemDescriptor[] {
const q = query.toLowerCase();
return [...items_.values()].filter(item => {
+ if (item.hidden) return false;
if (item.label.toLowerCase().includes(q)) return true;
if (item.description?.toLowerCase().includes(q)) return true;
if (item.tags?.some(t => t.toLowerCase().includes(q))) return true;
diff --git a/editor/src/settings/builtinSettings.ts b/editor/src/settings/builtinSettings.ts
index 4a8e83968..3135bb350 100644
--- a/editor/src/settings/builtinSettings.ts
+++ b/editor/src/settings/builtinSettings.ts
@@ -1,5 +1,7 @@
-import { registerSettingsSection, registerSettingsGroup, registerSettingsItem } from './SettingsRegistry';
+import { registerSettingsSection, registerSettingsGroup, registerSettingsItem, type SettingsItemType } from './SettingsRegistry';
import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT } from 'esengine';
+import { renderCollisionMatrix } from './CollisionMatrixWidget';
+import { MAX_COLLISION_LAYERS } from './collisionLayers';
export function registerBuiltinSettings(): void {
// =========================================================================
@@ -459,6 +461,65 @@ export function registerBuiltinSettings(): void {
// Physics
// =========================================================================
+ // =========================================================================
+ // Physics — Collision Layers group
+ // =========================================================================
+
+ registerSettingsGroup({
+ id: 'physics.collision-layers',
+ section: 'physics',
+ label: 'Collision Layers',
+ order: 10,
+ collapsed: true,
+ });
+
+ registerSettingsGroup({
+ id: 'physics.collision-matrix',
+ section: 'physics',
+ label: 'Collision Matrix',
+ order: 11,
+ });
+
+ const COLLISION_LAYER_DEFAULTS = [
+ 'Default', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '',
+ ];
+
+ for (let i = 0; i < MAX_COLLISION_LAYERS; i++) {
+ registerSettingsItem({
+ id: `physics.layerName${i}`,
+ section: 'physics',
+ group: 'physics.collision-layers',
+ label: `Layer ${i}`,
+ type: 'string',
+ defaultValue: COLLISION_LAYER_DEFAULTS[i],
+ order: i,
+ projectSync: true,
+ tags: ['collision', 'layer'],
+ });
+
+ registerSettingsItem({
+ id: `physics.layerMask${i}`,
+ section: 'physics',
+ label: `Layer ${i} Mask`,
+ type: 'number',
+ defaultValue: 0xFFFF,
+ hidden: true,
+ projectSync: true,
+ });
+ }
+
+ registerSettingsItem({
+ id: 'physics.collisionMatrix',
+ section: 'physics',
+ group: 'physics.collision-matrix',
+ label: 'Collision Matrix',
+ type: 'custom' as SettingsItemType,
+ defaultValue: null,
+ render: renderCollisionMatrix,
+ tags: ['collision', 'matrix', 'layer'],
+ });
+
registerSettingsItem({
id: 'physics.gravityX',
section: 'physics',
diff --git a/editor/src/settings/collisionLayers.ts b/editor/src/settings/collisionLayers.ts
new file mode 100644
index 000000000..e8688d633
--- /dev/null
+++ b/editor/src/settings/collisionLayers.ts
@@ -0,0 +1,33 @@
+import { getSettingsValue } from './SettingsRegistry';
+
+export const MAX_COLLISION_LAYERS = 16;
+
+export function getLayerName(index: number): string {
+ return getSettingsValue<string>(`physics.layerName${index}`) ?? '';
+}
+
+export function getNamedLayers(): { index: number; name: string }[] {
+ const result: { index: number; name: string }[] = [];
+ for (let i = 0; i < MAX_COLLISION_LAYERS; i++) {
+ const name = getLayerName(i);
+ if (name) {
+ result.push({ index: i, name });
+ }
+ }
+ return result;
+}
+
+export function layerIndexFromBits(bits: number): number {
+ for (let i = 0; i < MAX_COLLISION_LAYERS; i++) {
+ if (bits === (1 << i)) return i;
+ }
+ return 0;
+}
+
+export function bitsFromLayerIndex(index: number): number {
+ return 1 << index;
+}
+
+export function getLayerMask(layerIndex: number): number {
+ return getSettingsValue<number>(`physics.layerMask${layerIndex}`) ?? 0xFFFF;
+}
diff --git a/editor/src/settings/index.ts b/editor/src/settings/index.ts
index 05234b17a..62568f5c1 100644
--- a/editor/src/settings/index.ts
+++ b/editor/src/settings/index.ts
@@ -28,3 +28,10 @@ export {
export { showSettingsDialog } from './SettingsDialog';
export { registerBuiltinSettings } from './builtinSettings';
export { ProjectSettingsSync } from './ProjectSettingsSync';
+export {
+ MAX_COLLISION_LAYERS,
+ getLayerName,
+ getNamedLayers,
+ layerIndexFromBits,
+ bitsFromLayerIndex,
+} from './collisionLayers';
diff --git a/editor/src/styles/dialogs.css b/editor/src/styles/dialogs.css
index 93cf2688a..9c8a2e266 100644
--- a/editor/src/styles/dialogs.css
+++ b/editor/src/styles/dialogs.css
@@ -240,6 +240,9 @@
.es-dialog {
width: 100%;
max-width: 480px;
+ max-height: 90vh;
+ display: flex;
+ flex-direction: column;
background: var(--es-bg-secondary);
border: 1px solid var(--es-border);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
@@ -278,6 +281,9 @@
.es-dialog-body {
padding: 20px;
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
}
.es-dialog-field {
@@ -495,7 +501,9 @@
.es-settings-dialog-body {
display: flex;
flex-direction: column;
+ flex: 1;
min-height: 480px;
+ overflow: hidden;
}
.es-settings-search {
@@ -856,3 +864,75 @@
min-height: 0;
overflow: hidden;
}
+
+/* =============================================================================
+ * Collision Matrix Widget
+ * ============================================================================= */
+
+.es-collision-matrix {
+ padding: 4px 0;
+ overflow-x: auto;
+}
+
+.es-collision-matrix-empty {
+ color: var(--es-text-secondary);
+ font-size: 12px;
+ font-style: italic;
+ padding: 8px 0;
+}
+
+.es-collision-matrix-grid {
+ display: grid;
+ gap: 2px;
+ align-items: center;
+ justify-items: center;
+ width: fit-content;
+}
+
+.es-collision-matrix-corner {
+ width: 120px;
+}
+
+.es-collision-matrix-header {
+ width: 32px;
+ height: 48px;
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+ overflow: visible;
+}
+
+.es-collision-matrix-header span {
+ display: block;
+ transform: rotate(-45deg);
+ transform-origin: center center;
+ white-space: nowrap;
+ font-size: 11px;
+ color: var(--es-text-secondary);
+}
+
+.es-collision-matrix-row-label {
+ width: 120px;
+ text-align: right;
+ padding-right: 8px;
+ font-size: 12px;
+ color: var(--es-text-secondary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.es-collision-matrix-cell {
+ width: 32px;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.es-collision-matrix-cell input[type="checkbox"] {
+ width: 16px;
+ height: 16px;
+ cursor: pointer;
+ accent-color: var(--es-accent-gold);
+}
diff --git a/editor/src/styles/inspector.css b/editor/src/styles/inspector.css
index 1488e506b..b16b8b726 100644
--- a/editor/src/styles/inspector.css
+++ b/editor/src/styles/inspector.css
@@ -1692,3 +1692,4 @@
.es-pp-add-menu-item:hover {
background: var(--es-bg-hover);
}
+
diff --git a/editor/src/types/ProjectTypes.ts b/editor/src/types/ProjectTypes.ts
index 5b079709d..6e6a541e0 100644
--- a/editor/src/types/ProjectTypes.ts
+++ b/editor/src/types/ProjectTypes.ts
@@ -38,6 +38,8 @@ export interface ProjectConfig {
pixelsPerUnit?: number;
assetLoadTimeout?: number;
assetFailureCooldown?: number;
+ collisionLayerNames?: string[];
+ collisionLayerMasks?: number[];
}
// =============================================================================
diff --git a/sdk/rollup.config.js b/sdk/rollup.config.js
index a6f5d3052..d2dce4302 100644
--- a/sdk/rollup.config.js
+++ b/sdk/rollup.config.js
@@ -2,11 +2,6 @@ import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';
import dts from 'rollup-plugin-dts';
-const tsPlugin = typescript({
- tsconfig: './tsconfig.json',
- declaration: false,
-});
-
const ENTRY_FILES = ['/index.ts', '/index.wechat.ts'];
const treeshake = {
moduleSideEffects: (id) => ENTRY_FILES.some(e => id.endsWith(e)),
@@ -14,9 +9,22 @@ const treeshake = {
const esmBuilds = [
{
- input: 'src/index.ts',
- output: { file: 'dist/index.js', format: 'esm', sourcemap: true },
- plugins: [tsPlugin, terser()],
+ input: {
+ 'index': 'src/index.ts',
+ 'physics/index': 'src/physics/index.ts',
+ 'spine/index': 'src/spine/index.ts',
+ 'wasm': 'src/wasm.ts',
+ },
+ output: {
+ dir: 'dist',
+ format: 'esm',
+ sourcemap: true,
+ chunkFileNames: 'shared/[name].js',
+ },
+ plugins: [
+ typescript({ tsconfig: './tsconfig.json', declaration: false }),
+ terser(),
+ ],
treeshake,
},
{
@@ -31,45 +39,21 @@ const esmBuilds = [
plugins: [typescript({ tsconfig: './tsconfig.json', declaration: false }), terser()],
treeshake,
},
- {
- input: 'src/wasm.ts',
- output: { file: 'dist/wasm.js', format: 'esm', sourcemap: true },
- plugins: [typescript({ tsconfig: './tsconfig.json', declaration: false }), terser()],
- treeshake,
- },
- {
- input: 'src/spine/index.ts',
- output: { file: 'dist/spine/index.js', format: 'esm', sourcemap: true },
- plugins: [typescript({ tsconfig: './tsconfig.json', declaration: false }), terser()],
- treeshake,
- },
- {
- input: 'src/physics/index.ts',
- output: { file: 'dist/physics/index.js', format: 'esm', sourcemap: true },
- plugins: [typescript({ tsconfig: './tsconfig.json', declaration: false }), terser()],
- treeshake,
- },
];
const dtsBuilds = [
{
- input: 'src/index.ts',
- output: { file: 'dist/index.d.ts', format: 'esm' },
- plugins: [dts()],
- },
- {
- input: 'src/wasm.ts',
- output: { file: 'dist/wasm.d.ts', format: 'esm' },
- plugins: [dts()],
- },
- {
- input: 'src/spine/index.ts',
- output: { file: 'dist/spine/index.d.ts', format: 'esm' },
- plugins: [dts()],
- },
- {
- input: 'src/physics/index.ts',
- output: { file: 'dist/physics/index.d.ts', format: 'esm' },
+ input: {
+ 'index': 'src/index.ts',
+ 'physics/index': 'src/physics/index.ts',
+ 'spine/index': 'src/spine/index.ts',
+ 'wasm': 'src/wasm.ts',
+ },
+ output: {
+ dir: 'dist',
+ format: 'esm',
+ chunkFileNames: 'shared/[name].d.ts',
+ },
plugins: [dts()],
},
];
diff --git a/sdk/src/physics/PhysicsComponents.ts b/sdk/src/physics/PhysicsComponents.ts
index f510ccb20..10433f441 100644
--- a/sdk/src/physics/PhysicsComponents.ts
+++ b/sdk/src/physics/PhysicsComponents.ts
@@ -28,6 +28,8 @@ export interface BoxColliderData {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
export interface CircleColliderData {
@@ -38,6 +40,8 @@ export interface CircleColliderData {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
export interface CapsuleColliderData {
@@ -49,6 +53,8 @@ export interface CapsuleColliderData {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
// =============================================================================
@@ -72,7 +78,9 @@ export const BoxCollider = defineBuiltin<BoxColliderData>('BoxCollider', {
friction: 0.3,
restitution: 0.0,
isSensor: false,
- enabled: true
+ enabled: true,
+ categoryBits: 0x0001,
+ maskBits: 0xFFFF,
});
export const CircleCollider = defineBuiltin<CircleColliderData>('CircleCollider', {
@@ -82,7 +90,9 @@ export const CircleCollider = defineBuiltin<CircleColliderData>('CircleCollider'
friction: 0.3,
restitution: 0.0,
isSensor: false,
- enabled: true
+ enabled: true,
+ categoryBits: 0x0001,
+ maskBits: 0xFFFF,
});
export const CapsuleCollider = defineBuiltin<CapsuleColliderData>('CapsuleCollider', {
@@ -93,7 +103,9 @@ export const CapsuleCollider = defineBuiltin<CapsuleColliderData>('CapsuleCollid
friction: 0.3,
restitution: 0.0,
isSensor: false,
- enabled: true
+ enabled: true,
+ categoryBits: 0x0001,
+ maskBits: 0xFFFF,
});
// =============================================================================
diff --git a/sdk/src/physics/PhysicsModuleLoader.ts b/sdk/src/physics/PhysicsModuleLoader.ts
index 000f315db..1ab6f0672 100644
--- a/sdk/src/physics/PhysicsModuleLoader.ts
+++ b/sdk/src/physics/PhysicsModuleLoader.ts
@@ -15,13 +15,16 @@ export interface PhysicsWasmModule {
_physics_addBoxShape(entityId: number, halfW: number, halfH: number,
offX: number, offY: number,
- density: number, friction: number, restitution: number, isSensor: number): void;
+ density: number, friction: number, restitution: number, isSensor: number,
+ categoryBits: number, maskBits: number): void;
_physics_addCircleShape(entityId: number, radius: number,
offX: number, offY: number,
- density: number, friction: number, restitution: number, isSensor: number): void;
+ density: number, friction: number, restitution: number, isSensor: number,
+ categoryBits: number, maskBits: number): void;
_physics_addCapsuleShape(entityId: number, radius: number, halfHeight: number,
offX: number, offY: number,
- density: number, friction: number, restitution: number, isSensor: number): void;
+ density: number, friction: number, restitution: number, isSensor: number,
+ categoryBits: number, maskBits: number): void;
_physics_step(dt: number): void;
@@ -107,9 +110,9 @@ export async function loadPhysicsSideModule(
_physics_destroyBody: cwrap('physics_destroyBody', null, ['number']) as PhysicsWasmModule['_physics_destroyBody'],
_physics_hasBody: cwrap('physics_hasBody', 'number', ['number']) as PhysicsWasmModule['_physics_hasBody'],
- _physics_addBoxShape: cwrap('physics_addBoxShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addBoxShape'],
- _physics_addCircleShape: cwrap('physics_addCircleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCircleShape'],
- _physics_addCapsuleShape: cwrap('physics_addCapsuleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCapsuleShape'],
+ _physics_addBoxShape: cwrap('physics_addBoxShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addBoxShape'],
+ _physics_addCircleShape: cwrap('physics_addCircleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCircleShape'],
+ _physics_addCapsuleShape: cwrap('physics_addCapsuleShape', null, ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number']) as PhysicsWasmModule['_physics_addCapsuleShape'],
_physics_step: cwrap('physics_step', null, ['number']) as PhysicsWasmModule['_physics_step'],
diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.ts
index ee6377d2f..fb956bb73 100644
--- a/sdk/src/physics/PhysicsPlugin.ts
+++ b/sdk/src/physics/PhysicsPlugin.ts
@@ -9,12 +9,13 @@ import type { TransformData, ParentData, CanvasData } from '../component';
import { Transform, Parent, Canvas } from '../component';
import { defineResource, Res, Time, type TimeData } from '../resource';
import { Schedule, defineSystem } from '../system';
+import { isEditor, isPlayMode } from '../env';
import {
loadPhysicsModule,
type PhysicsWasmModule,
type PhysicsModuleFactory,
} from './PhysicsModuleLoader';
-import { RigidBody, BoxCollider, CircleCollider, CapsuleCollider, BodyType, type RigidBodyData } from './PhysicsComponents';
+import { RigidBody, BoxCollider, CircleCollider, CapsuleCollider, BodyType, type RigidBodyData, type BoxColliderData, type CircleColliderData, type CapsuleColliderData } from './PhysicsComponents';
import { setupPhysicsDebugDraw, PhysicsDebugDraw, type PhysicsDebugDrawConfig } from './PhysicsDebugDraw';
// =============================================================================
@@ -25,6 +26,7 @@ export interface PhysicsPluginConfig {
gravity?: Vec2;
fixedTimestep?: number;
subStepCount?: number;
+ collisionLayerMasks?: number[];
}
// =============================================================================
@@ -90,7 +92,7 @@ function readPixelsPerUnit(app: App): number {
}
export class PhysicsPlugin implements Plugin {
- private config_: Required<PhysicsPluginConfig>;
+ private config_: Required<Omit<PhysicsPluginConfig, 'collisionLayerMasks'>> & Pick<PhysicsPluginConfig, 'collisionLayerMasks'>;
private wasmUrl_: string;
private factory_?: PhysicsModuleFactory;
@@ -100,7 +102,8 @@ export class PhysicsPlugin implements Plugin {
this.config_ = {
gravity: config.gravity ?? { x: 0, y: -9.81 },
fixedTimestep: config.fixedTimestep ?? 1 / 60,
- subStepCount: config.subStepCount ?? 4
+ subStepCount: config.subStepCount ?? 4,
+ collisionLayerMasks: config.collisionLayerMasks,
};
}
@@ -142,6 +145,8 @@ export class PhysicsPlugin implements Plugin {
defineSystem(
[Res(Time)],
(time: TimeData) => {
+ if (isEditor() && !isPlayMode()) return;
+
const entities = world.getEntitiesWithComponents([RigidBody, Transform]);
const currentEntities = new Set<Entity>();
@@ -162,7 +167,7 @@ export class PhysicsPlugin implements Plugin {
rb.fixedRotation ? 1 : 0, rb.bullet ? 1 : 0
);
- addShapeForEntity(app, module, entity);
+ addShapeForEntity(app, module, entity, this.config_.collisionLayerMasks);
trackedEntities.add(entity);
cachedProps.set(entity, {
bodyType: rb.bodyType,
@@ -240,35 +245,54 @@ export class PhysicsPlugin implements Plugin {
// Internal helpers
// =============================================================================
-function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity): void {
+const MAX_COLLISION_LAYERS = 16;
+
+function resolveCollisionMask(categoryBits: number, maskBits: number, layerMasks?: number[]): number {
+ if (!layerMasks) return maskBits;
+ for (let i = 0; i < MAX_COLLISION_LAYERS; i++) {
+ if (categoryBits === (1 << i)) return layerMasks[i];
+ }
+ return maskBits;
+}
+
+function addShapeForEntity(app: App, module: PhysicsWasmModule, entity: Entity, layerMasks?: number[]): void {
const world = app.world;
if (world.has(entity, BoxCollider)) {
- const box = world.get(entity, BoxCollider) as { halfExtents: Vec2; offset: Vec2; density: number; friction: number; restitution: number; isSensor: boolean };
+ const box = world.get(entity, BoxCollider) as BoxColliderData;
+ const category = box.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, box.maskBits ?? 0xFFFF, layerMasks);
module._physics_addBoxShape(
entity, box.halfExtents.x, box.halfExtents.y,
box.offset.x, box.offset.y,
- box.density, box.friction, box.restitution, box.isSensor ? 1 : 0
+ box.density, box.friction, box.restitution, box.isSensor ? 1 : 0,
+ category, mask
);
return;
}
if (world.has(entity, CircleCollider)) {
- const circle = world.get(entity, CircleCollider) as { radius: number; offset: Vec2; density: number; friction: number; restitution: number; isSensor: boolean };
+ const circle = world.get(entity, CircleCollider) as CircleColliderData;
+ const category = circle.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, circle.maskBits ?? 0xFFFF, layerMasks);
module._physics_addCircleShape(
entity, circle.radius,
circle.offset.x, circle.offset.y,
- circle.density, circle.friction, circle.restitution, circle.isSensor ? 1 : 0
+ circle.density, circle.friction, circle.restitution, circle.isSensor ? 1 : 0,
+ category, mask
);
return;
}
if (world.has(entity, CapsuleCollider)) {
- const capsule = world.get(entity, CapsuleCollider) as { radius: number; halfHeight: number; offset: Vec2; density: number; friction: number; restitution: number; isSensor: boolean };
+ const capsule = world.get(entity, CapsuleCollider) as CapsuleColliderData;
+ const category = capsule.categoryBits ?? 0x0001;
+ const mask = resolveCollisionMask(category, capsule.maskBits ?? 0xFFFF, layerMasks);
module._physics_addCapsuleShape(
entity, capsule.radius, capsule.halfHeight,
capsule.offset.x, capsule.offset.y,
- capsule.density, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0
+ capsule.density, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0,
+ category, mask
);
}
}
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index 51aebdcd5..3fe55fa6f 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -117,6 +117,8 @@ export interface BoxCollider {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
export interface CircleCollider {
@@ -127,6 +129,8 @@ export interface CircleCollider {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
export interface CapsuleCollider {
@@ -138,6 +142,8 @@ export interface CapsuleCollider {
restitution: number;
isSensor: boolean;
enabled: boolean;
+ categoryBits: number;
+ maskBits: number;
}
export interface ParticleEmitter {
diff --git a/src/esengine/bindings/PhysicsModuleEntry.cpp b/src/esengine/bindings/PhysicsModuleEntry.cpp
index bf77f5a25..0cb42f721 100644
--- a/src/esengine/bindings/PhysicsModuleEntry.cpp
+++ b/src/esengine/bindings/PhysicsModuleEntry.cpp
@@ -165,7 +165,8 @@ int physics_hasBody(uint32_t entityId) {
EMSCRIPTEN_KEEPALIVE
void physics_addBoxShape(uint32_t entityId, float halfW, float halfH,
float offX, float offY,
- float density, float friction, float restitution, int isSensor) {
+ float density, float friction, float restitution, int isSensor,
+ uint32_t categoryBits, uint32_t maskBits) {
auto it = g_entityToBody.find(entityId);
if (it == g_entityToBody.end()) return;
@@ -176,6 +177,8 @@ void physics_addBoxShape(uint32_t entityId, float halfW, float halfH,
shapeDef.isSensor = isSensor != 0;
shapeDef.enableContactEvents = true;
shapeDef.enableSensorEvents = isSensor != 0;
+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);
+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);
b2Polygon polygon = b2MakeOffsetBox(halfW, halfH, {offX, offY}, b2MakeRot(0.0f));
b2ShapeId shapeId = b2CreatePolygonShape(it->second, &shapeDef, &polygon);
@@ -185,7 +188,8 @@ void physics_addBoxShape(uint32_t entityId, float halfW, float halfH,
EMSCRIPTEN_KEEPALIVE
void physics_addCircleShape(uint32_t entityId, float radius,
float offX, float offY,
- float density, float friction, float restitution, int isSensor) {
+ float density, float friction, float restitution, int isSensor,
+ uint32_t categoryBits, uint32_t maskBits) {
auto it = g_entityToBody.find(entityId);
if (it == g_entityToBody.end()) return;
@@ -196,6 +200,8 @@ void physics_addCircleShape(uint32_t entityId, float radius,
shapeDef.isSensor = isSensor != 0;
shapeDef.enableContactEvents = true;
shapeDef.enableSensorEvents = isSensor != 0;
+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);
+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);
b2Circle circle;
circle.center = {offX, offY};
@@ -208,7 +214,8 @@ void physics_addCircleShape(uint32_t entityId, float radius,
EMSCRIPTEN_KEEPALIVE
void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,
float offX, float offY,
- float density, float friction, float restitution, int isSensor) {
+ float density, float friction, float restitution, int isSensor,
+ uint32_t categoryBits, uint32_t maskBits) {
auto it = g_entityToBody.find(entityId);
if (it == g_entityToBody.end()) return;
@@ -219,6 +226,8 @@ void physics_addCapsuleShape(uint32_t entityId, float radius, float halfHeight,
shapeDef.isSensor = isSensor != 0;
shapeDef.enableContactEvents = true;
shapeDef.enableSensorEvents = isSensor != 0;
+ shapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);
+ shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);
b2Capsule capsule;
capsule.center1 = {offX, offY + halfHeight};
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 4e3681000..7df1e214b 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -540,7 +540,9 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("friction", &esengine::ecs::BoxCollider::friction)
.field("restitution", &esengine::ecs::BoxCollider::restitution)
.field("isSensor", &esengine::ecs::BoxCollider::isSensor)
- .field("enabled", &esengine::ecs::BoxCollider::enabled);
+ .field("enabled", &esengine::ecs::BoxCollider::enabled)
+ .field("categoryBits", &esengine::ecs::BoxCollider::categoryBits)
+ .field("maskBits", &esengine::ecs::BoxCollider::maskBits);
value_object<esengine::ecs::CircleCollider>("CircleCollider")
.field("radius", &esengine::ecs::CircleCollider::radius)
@@ -549,7 +551,9 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("friction", &esengine::ecs::CircleCollider::friction)
.field("restitution", &esengine::ecs::CircleCollider::restitution)
.field("isSensor", &esengine::ecs::CircleCollider::isSensor)
- .field("enabled", &esengine::ecs::CircleCollider::enabled);
+ .field("enabled", &esengine::ecs::CircleCollider::enabled)
+ .field("categoryBits", &esengine::ecs::CircleCollider::categoryBits)
+ .field("maskBits", &esengine::ecs::CircleCollider::maskBits);
value_object<esengine::ecs::CapsuleCollider>("CapsuleCollider")
.field("radius", &esengine::ecs::CapsuleCollider::radius)
@@ -559,7 +563,9 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("friction", &esengine::ecs::CapsuleCollider::friction)
.field("restitution", &esengine::ecs::CapsuleCollider::restitution)
.field("isSensor", &esengine::ecs::CapsuleCollider::isSensor)
- .field("enabled", &esengine::ecs::CapsuleCollider::enabled);
+ .field("enabled", &esengine::ecs::CapsuleCollider::enabled)
+ .field("categoryBits", &esengine::ecs::CapsuleCollider::categoryBits)
+ .field("maskBits", &esengine::ecs::CapsuleCollider::maskBits);
value_object<ParticleEmitterJS>("ParticleEmitter")
.field("rate", &ParticleEmitterJS::rate)
diff --git a/src/esengine/ecs/components/Collider.hpp b/src/esengine/ecs/components/Collider.hpp
index c6e66cb6f..86b4e9c85 100644
--- a/src/esengine/ecs/components/Collider.hpp
+++ b/src/esengine/ecs/components/Collider.hpp
@@ -29,6 +29,12 @@ struct BoxCollider {
ES_PROPERTY()
bool enabled{true};
+ ES_PROPERTY()
+ u32 categoryBits{0x0001};
+
+ ES_PROPERTY()
+ u32 maskBits{0xFFFF};
+
BoxCollider() = default;
};
@@ -55,6 +61,12 @@ struct CircleCollider {
ES_PROPERTY()
bool enabled{true};
+ ES_PROPERTY()
+ u32 categoryBits{0x0001};
+
+ ES_PROPERTY()
+ u32 maskBits{0xFFFF};
+
CircleCollider() = default;
};
@@ -84,6 +96,12 @@ struct CapsuleCollider {
ES_PROPERTY()
bool enabled{true};
+ ES_PROPERTY()
+ u32 categoryBits{0x0001};
+
+ ES_PROPERTY()
+ u32 maskBits{0xFFFF};
+
CapsuleCollider() = default;
};