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.

fix: resolve play mode timeout and harden runtime inspector

esengined347ef241315
diff --git a/desktop/public/sdk/cjs/esengine.wechat.js b/desktop/public/sdk/cjs/esengine.wechat.js
index 093641eda..d5afdd79f 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}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function c(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(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 u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of u)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function g(e){return h.get(f(e))}function _(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function y(e){const t=g(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(y(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 b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(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){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},M=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function $(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map($);const t={};for(const s in e)t[s]=$(e[s]);return t}let U=0;function k(e,t){const s=++U;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...$(t),...e}:$(t)}}function D(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const s=D(),n=s.get(e);if(n)return n;const r=k(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=D(),s=t.get(e);if(s)return s;const n=k(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return D().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=X("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=X("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=X("Camera",{projectionType:G.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:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("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}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=L("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const ce=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),le=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ge(e){return{_type:"res",_resource:e}}function _e(e){return{_type:"res_mut",_resource:e}}class me{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ye{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const xe=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,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(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class be{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=H(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 Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Ce(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{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 Re=fe(new Me,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Me;e.insertResource(Re,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,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=$e(t[e]),o=$e(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function Ue(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 ke=null;function De(e){ke=e}function Le(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ke&&ke(e,t)}function We(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:We(e)}}return t}class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==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 Le(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Le(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.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Le(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Le(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Le(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.");H(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_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(Ue(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,We(r))}catch(s){Le(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Le(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 Le(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Le(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(Ue(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.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,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=o?o.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const Oe=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Ne=null,Ve=null,Xe=1;const Ge=new Map;function qe(e){Ne=e,Ve=e.getResourceManager(),rt()}function Ye(){0!==Ze&&Ne&&(Ne._free(Ze),Ze=0),Ge.clear(),Xe=1,Qe=!1,tt.clear(),st=null,Ve=null,Ne=null}function Je(){if(!Ve)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ve}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Xe++,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 Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},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=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Xe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.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=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Ne&&(Ze=Ne._malloc(et)),Ze);if(0===t||!Ne)return{ptr:0,count:0};let s=0,n=0;const r=Ne.HEAPU8,o=Ne.HEAPU32,i=Ne.HEAPF32;for(const[a,c]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);o[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof c)d=0,h[0]=c;else if(Array.isArray(c)){d=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)h[e]=c[e]}else"w"in c?(d=3,h=[c.x,c.y,c.z,c.w]):"z"in c?(d=2,h=[c.x,c.y,c.z,0]):"y"in c&&(d=1,h=[c.x,c.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Ne||Qe)return;Ne.materialDataProvider=(e,t,s,n,r)=>{const o=Ge.get(e);if(!o)return Ne.HEAPU32[t>>2]=0,Ne.HEAPU32[s>>2]=0,Ne.HEAPU32[n>>2]=0,void(Ne.HEAPU32[r>>2]=0);Ne.HEAPU32[t>>2]=o.shader,Ne.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Ne.HEAPU32[n>>2]=i,Ne.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,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&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(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:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ct=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function lt(e){return ct.get(e)?.fields??[]}function ut(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function dt(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ct.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const l=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);l.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=V(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=i(I.textCanvasSize,I.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ke.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),c=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===g(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=g(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(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 Ke.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://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=fe(null,"Assets");class gt{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const _t=new gt;async function mt(e,t,s){const{entities:n,rootId:r}=await xt(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await dt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const yt=10;async function xt(e,t,s,n,r,o=0){if(o>yt)throw new Error(`Prefab nesting depth exceeded ${yt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await xt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?i.get(n.parent)??null:null),c.push(...t.entities);continue}const l=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(d,t),c.push(d)}const l=i.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function wt(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 vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return mt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Tt=null,Ct=0,At=0,Et=0;const Mt=new Float32Array(256);function Rt(e){Tt=e,Ct=Tt._malloc(64),At=Tt._malloc(64),Et=Tt._malloc(1024)}function It(){Tt&&(Ct&&(Tt._free(Ct),Ct=0),At&&(Tt._free(At),At=0),Et&&(Tt._free(Et),Et=0)),Tt=null}function Ft(){if(!Tt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tt}const Bt={r:1,g:1,b:1,a:1},$t={begin(e){const t=Ft();try{t.HEAPF32.set(e,Ct/4),t.draw_begin(Ct)}catch(e){Le(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){Le(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Le(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Le(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Le(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Le(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Tt?Tt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tt?Tt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,At/4),n.draw_mesh(e,t,At)}catch(s){Le(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if($t.setBlendMode(r.blendMode),$t.setDepthTest(r.depthTest),0===r.uniforms.size)return void $t.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,At/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Dt(t);if(!(n<0)){if(je(s))Mt[o++]=10,Mt[o++]=n,Mt[o++]=s.slot??e++,Mt[o++]=s.textureId;else if("number"==typeof s)Mt[o++]=1,Mt[o++]=n,Mt[o++]=s;else if(Array.isArray(s)){Mt[o++]=s.length,Mt[o++]=n;for(let e=0;e<s.length;e++)Mt[o++]=s[e]}else"w"in s?(Mt[o++]=4,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y,Mt[o++]=s.z,Mt[o++]=s.w):"z"in s?(Mt[o++]=3,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y,Mt[o++]=s.z):(Mt[o++]=2,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Mt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,At);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Et/4),n.draw_meshWithUniforms(e,r.shader,At,Et,o)}catch(s){Le(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},Ut={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},kt=new Set;function Dt(e){const t=Ut[e];return void 0!==t?t:(kt.has(e)||(kt.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(Ut).join(", ")}`)),-1)}const Lt=new Map;function Wt(e,t,s){Lt.set(e,{fn:t,scene:s??""})}function zt(e){Lt.delete(e)}function Ot(){Lt.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Nt=0,Vt=0,Xt=0;function Gt(e){jt=e,Nt=jt._malloc(262144),Vt=jt._malloc(65536),Xt=jt._malloc(256)}function qt(){jt&&(Nt&&jt._free(Nt),Vt&&jt._free(Vt),Xt&&jt._free(Xt),Nt=0,Vt=0,Xt=0),jt=null}function Yt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=Yt(),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,Nt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Xt,r).set(o),t.geometry_init(s,Nt,n,Xt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Vt,n).set(e.indices),t.geometry_setIndices16(s,Vt,n)}else{new Uint32Array(t.HEAPU8.buffer,Vt,n).set(e.indices),t.geometry_setIndices32(s,Vt,n)}}return s},updateVertices(e,t,s=0){const n=Yt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Nt/4),n.geometry_updateVertices(e,Nt,r,s)},release(e){e>0&&Yt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return Le(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){Le(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){Le(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return Le(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){Le(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){Le(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return Le(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){Le(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Le(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){Le(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){Le(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return Le(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return Le(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){Le(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return Le(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(ss,"#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")},ss="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const cs={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){Le(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){Le(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){Le(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){Le(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){Le(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){Le(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ls=null;function us(e){ls=e}function ds(){ls=null}const hs={enable(){ls?.gl_enableErrorCheck(!0)},disable(){ls?.gl_enableErrorCheck(!1)},check:e=>ls?.gl_checkErrors(e)??0,diagnose(){ls?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(cs.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),cs.setViewport(0,0,n,r),cs.clearBuffers(3),cs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),cs.submitSprites(t),cs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):cs.submitSpine(t),cs.flush(),this.executeDrawCallbacks(s,o),cs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;cs.setViewport(n.x,n.y,n.w,n.h),cs.setScissor(n.x,n.y,n.w,n.h,!0),cs.clearBuffers(r),cs.setScissor(0,0,0,0,!1),cs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),cs.submitSprites(t),cs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):cs.submitSpine(t),cs.flush(),this.executeDrawCallbacks(s,o),cs.end()}executeDrawCallbacks(e,t){const s=Lt;if(s.size>0){$t.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}$t.end();for(const e of n)zt(e)}}}const fs="__scene_transition_overlay__";class gs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class _s{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,ae,{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),Wt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ms{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.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Wt(fs,()=>{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;$t.setLayer(9999),$t.setDepth(9999),$t.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,zt(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,zt(fs),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 gs(t);this.scenes_.set(e,s);const n=new _s(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new gs(t);this.scenes_.set(e,s);const n=new _s(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())zt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const ys=fe(null,"SceneManager");function xs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ys).getSceneStatus(t)&&s._fn(...n)}}}const ws=Ce([_e(ys),ge(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ms(e);e.insertResource(ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ys),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_);this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(exports.Schedule.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(exports.Schedule.FixedPreUpdate),this.runSchedule(exports.Schedule.FixedUpdate),this.runSchedule(exports.Schedule.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(exports.Schedule.PreUpdate),this.runSchedule(exports.Schedule.Update),this.runSchedule(exports.Schedule.PostUpdate),this.runSchedule(exports.Schedule.Last),requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return De(e),this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ys).register(e),this}setInitialScene(e){return this.getResource(ys).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[ds,as,Zt,qt,Ye,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}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(xe);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ts(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,c){h=Ps(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}d=h*a,u=As(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ms(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);l.push({entity:e,viewProjection:new Float32Array(Bs(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Cs=new Float32Array(16);function As(e,t,s,n,r,o){const i=Cs;i.fill(0);const a=t-e,c=n-s,l=o-r;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+s)/c,i[14]=-(o+r)/l,i[15]=1,i}const Es=new Float32Array(16);function Ms(e,t,s,n){const r=Es;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;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 Fs=new Float32Array(16);function Bs(e,t){const s=Fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var $s,Us,ks;exports.TextAlign=void 0,($s=exports.TextAlign||(exports.TextAlign={}))[$s.Left=0]="Left",$s[$s.Center=1]="Center",$s[$s.Right=2]="Right",exports.TextVerticalAlign=void 0,(Us=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[Us.Top=0]="Top",Us[Us.Middle=1]="Middle",Us[Us.Bottom=2]="Bottom",exports.TextOverflow=void 0,(ks=exports.TextOverflow||(exports.TextOverflow={}))[ks.Visible=0]="Visible",ks[ks.Clip=1]="Clip",ks[ks.Ellipsis=2]="Ellipsis";const Ds=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),Ls=L("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}});class Ws{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?o:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(c)),h=Math.ceil(c.length*l),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const g=Math.round(255*e.color.r),_=Math.round(255*e.color.g),m=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(${g}, ${_}, ${m}, ${y})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=c.length*l;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of c){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function zs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Os(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Hs{build(e){N("Text",Ds);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ws(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ds));for(const e of r.keys())n.valid(e)&&n.has(e,Ds)||r.delete(e);const e=n.getEntitiesWithComponents([Ds]);for(const t of e){const e=n.get(t,Ds),o=n.has(t,Ls)?n.get(t,Ls):null,i=r.get(t);if(i&&!Os(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),c=n.get(t,Q);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Q,c),r.set(t,zs(e,o))}}))}}const js=new Hs,Ns=L("UIMask",{enabled:!0});function Vs(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Xs(e,t,s,n,r,o,i,a,c,l,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function g(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[_,m]=g(d,p),[y,x]=g(h,f),w=Math.min(_,y),v=Math.max(_,y),b=Math.min(m,x),S=Math.max(m,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Gs(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],c=e[5],l=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],g=e[12],_=e[13],m=e[14],y=e[15],x=n*c-r*a,w=n*l-o*a,v=n*u-i*a,b=r*l-o*c,S=r*u-i*c,P=o*u-i*l,T=d*_-h*g,C=d*m-p*g,A=d*y-f*g,E=h*m-p*_,M=h*y-f*_,R=p*y-f*m;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(c*R-l*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(_*P-m*S+y*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(l*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(m*v-g*P-y*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-c*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(g*S-_*v+y*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(c*C-a*E-l*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(_*w-g*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function qs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,c=(t-r)/i*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],d=s[3]*a+s[7]*c+s[15];return{x:l/d,y:u/d}}function Ys(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function Js(e,t,s,n,r,o,i){if(!e.has(t,Ls)||!e.has(t,K))return null;const a=e.get(t,Ls),c=e.get(t,K),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Xs(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Ks(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Ns]);if(0!==c.length)try{!function(e,t,s,n,r,o,i,a,c){const l=new Set;for(const e of n){t.get(e,Ns).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(l.has(s)){const e=Js(t,s,r,o,i,a,c);e&&(n=Vs(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Js(t,e,r,o,i,a,c);s&&d(e,s)}}(e,t,s,c,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Qs{build(e){if(N("UIMask",Ns),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ks(e.wasmModule,e.world))}}const Zs=new Qs,en=L("Interactable",{enabled:!0}),tn=L("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var sn;exports.ButtonState=void 0,(sn=exports.ButtonState||(exports.ButtonState={}))[sn.Normal=0]="Normal",sn[sn.Hovered=1]="Hovered",sn[sn.Pressed=2]="Pressed",sn[sn.Disabled=3]="Disabled";const nn=L("Button",{state:exports.ButtonState.Normal,transition:null});class rn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}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 on=fe(new rn,"UIEvents"),an=W("ScreenSpace");function cn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,c=o.left+e.x*i,l=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,g;if(c===l&&u===d){const e=c+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,g=t+o}else h=c+s.x,p=u+s.y,f=l+n.x,g=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+g),width:f-h,height:g-p,rect:{left:h,bottom:p,right:f,top:g}}}function ln(e,t,s,n,r,o){if(!e.has(t,Ls))return;const i=e.get(t,Ls),a=cn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const c=e.get(t,J);if(o?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,J,c),!e.has(t,ne))return;const l=e.get(t,ne);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&ln(e,t,a.rect,a.centerX,a.centerY,!1)}class un{build(e){N("UIRect",Ls);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Oe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([an,Ls,J]);for(const e of o)ln(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const dn=new un,hn=new Float32Array(16),pn=new Float32Array(16);let fn=!0,gn=1;class _n{build(e){N("Interactable",en),N("Button",nn);const t=e.world,s=new rn;e.insertResource(on,s);let n=null,r=null;gn="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(Re),ge(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([tn]);for(const e of i){const s=t.get(e,tn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*gn,c=o.screenH-e.mouseY*gn;!function(e){let t=!1;for(let s=0;s<16;s++)if(pn[s]!==e[s]){t=!0;break}t&&(pn.set(e),fn=!0)}(o.viewProjection),fn&&(Gs(o.viewProjection,hn),fn=!1);const l=qs(a,c,hn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([en,Ls,K]);let d=null,h=-1/0;for(const e of u){t.has(e,tn)||t.insert(e,tn);if(!t.get(e,en).enabled)continue;const s=t.get(e,K),n=t.get(e,Ls),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Ys(l.x,l.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,tn)){t.get(n,tn).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,tn).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,tn);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,tn)){const e=t.get(r,tn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([nn]);for(const s of e){if(t.has(s,en)||t.insert(s,en,{enabled:!0}),!t.has(s,tn))continue;const e=t.get(s,tn),n=t.get(s,nn),r=t.get(s,en),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const mn=new _n,yn=L("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});class xn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",yn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,c=!1,l=!0,u=0,d=0;const h=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(!h)return;const p=h,f=()=>{c||null===a||x()},g=()=>{c=!0},_=()=>{c=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,yn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(on).emit(a,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==a&&s.valid(a)&&s.has(a,yn)){const e=s.get(a,yn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,yn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(on).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,yn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,yn)){const e=s.get(a,yn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){l=!0,u=0}function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=vn(Math.max(r.width,a)),r.height=vn(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),g=i.padding;if(i.multiline){const e=wn(o,h,a-2*g);let t=g;for(const s of e)o.fillText(s,g,t),t+=f}else{const e=(c-i.fontSize)/2;o.fillText(h,g,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=wn(o,i.value.substring(0,i.cursorPos),a-2*g),r=e.length>0?e[e.length-1]:"";t=g+o.measureText(r).width,s=g+(e.length-1)*f,n=f}else t=g+o.measureText(e).width,s=(c-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const _=o.getImageData(0,0,a,c),m=new Uint8Array(_.data.buffer),y=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&y.releaseTexture(w);const v=y.createTexture(a,c,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=c,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,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",g),p.addEventListener("compositionend",_),p.addEventListener("keydown",m),p.addEventListener("blur",y),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",g),p.removeEventListener("compositionend",_),p.removeEventListener("keydown",m),p.removeEventListener("blur",y),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([ge(on)],e=>{const t=s.getEntitiesWithComponents([yn,en]);for(const e of t){if(!s.has(e,tn))continue;if(s.get(e,tn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([en]);for(const t of e){if(s.has(t,yn))continue;if(!s.has(t,tn))continue;if(s.get(t,tn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,l=!l,null!==a&&s.valid(a)&&s.has(a,yn)))){s.get(a,yn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,yn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([yn,Ls]);for(const e of i){const t=s.get(e,yn);if(!t.dirty)continue;const n=s.get(e,Ls),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function wn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function vn(e){let t=1;for(;t<e;)t*=2;return t}const bn=new xn;async function Sn(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 Pn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Tn=fe(null,"PhysicsAPI");function Cn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function An(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class En{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(Pn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Sn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Ce([ge(xe)],a=>{const c=i.getEntitiesWithComponents([ce,J,K]),l=new Set;for(const r of c){l.add(r);const a=i.get(r,ce),c=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Cn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*o,c.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Mn(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=Cn(c.rotation);n._physics_setBodyTransform(r,c.position.x*o,c.position.y*o,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=c,p=l;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=Cn(s.rotation),r=a-s.position.x,o=c-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=l-n}}u.position.x=d,u.position.y=h;const f=An(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],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(Pn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Tn,Rn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Mn(e,t,s){const n=e.world;if(n.has(s,le)){const e=n.get(s,le);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,ue)){const e=n.get(s,ue);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,de)){const e=n.get(s,de);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 Rn{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(Rn.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)}}function In(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function Fn(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 Bn(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,d=a+a,h=c+c,p=l+l,f=a*d,g=a*h,_=a*p,m=c*h,y=c*p,x=l*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(g+b)*r,(_-v)*r,0,(g-b)*o,(1-(f+x))*o,(y+w)*o,0,(_+v)*i,(y-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function $n(e,t,s,n,r,o,i,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=In(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let u={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const c=r.resolvePath(i),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===g(c)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),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,u);if(t._free(d),p<0)continue;o[i]=p;const f=Fn(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=_+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=In(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){new En("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=g(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${i}`:i;t=await s.readText(c),o=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=o?`${o}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=In(e,l,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=lt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,h,p);const f=ut(e.world,s);if(c&&e.hasResource(ys))for(const t of f.values())e.world.insert(t,ae,{scene:c,persistent:!1});if(r&&d){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(d,s,u,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let c=a-o;o=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const o=Number(e),i=r[e],a=l.has(o,oe)?l.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,c*d);let h=0;if(l.has(o,K)){const e=Bn(l.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,c=2*o,l=s._malloc(a),u=s._malloc(c),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,l,u,d,p);const f=s.HEAPU32[d>>2],g=s.HEAPU32[p>>2],_=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(c);t.HEAPF32.set(_,y>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(y,r,x,o,f,g,h),t._free(y),t._free(x),s._free(l),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class Un{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===g(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=g(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const kn="__preview__";const Dn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=cs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:cs.getTargetTexture(s),width:e.width,height:e.height}},release(e){cs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(cs.releaseRenderTarget(e._handle),Dn.create({width:t,height:s,depth:!0})),begin(e,t){cs.begin(t,e._handle)},end(){cs.end()},getDepthTexture:e=>cs.getTargetDepthTexture(e._handle)};let Ln=!1;var Wn;exports.LogLevel=void 0,(Wn=exports.LogLevel||(exports.LogLevel={}))[Wn.Debug=0]="Debug",Wn[Wn.Info=1]="Info",Wn[Wn.Warn=2]="Warn",Wn[Wn.Error=3]="Error";class zn{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 On{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new zn)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Hn=new On;const jn=[js,Zs,dn,mn,bn];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await c(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E,exports.App=bs,exports.AssetPlugin=gt,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=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=le,exports.Button=nn,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=de,exports.Children=ne,exports.CircleCollider=ue,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.Draw=$t,exports.EntityCommands=be,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=en,exports.LocalTransform=J,exports.Logger=On,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Rn,exports.PhysicsEvents=Pn,exports.PhysicsPlugin=En,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(ys);t.register({name:kn,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(kn),this.loadPromise_=t.load(kn).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new Un(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await $n(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,kn)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).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([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(ys).getScene(kn),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth};e.insert(o,Z,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ys);await e.switchTo(kn),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.ProjectionType=G,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=Dn,exports.Renderer=cs,exports.Res=ge,exports.ResMut=_e,exports.RigidBody=ce,exports.RuntimeConfig=I,exports.ScaleMode=Y,exports.SceneManager=ys,exports.SceneManagerState=ms,exports.SceneOwner=ae,exports.ScreenSpace=an,exports.ShaderSources=ot,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Ds,exports.TextInput=yn,exports.TextInputPlugin=xn,exports.TextPlugin=Hs,exports.TextRenderer=Ws,exports.Time=xe,exports.UICameraInfo=Oe,exports.UIEventQueue=rn,exports.UIEvents=on,exports.UIInteraction=tn,exports.UIInteractionPlugin=_n,exports.UILayoutPlugin=un,exports.UIMask=Ns,exports.UIMaskPlugin=Qs,exports.UIRect=Ls,exports.Velocity=te,exports.WebAssetProvider=Un,exports.World=ze,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ae().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=_t,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){D().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=cn,exports.createMaskProcessor=Ks,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await $n(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),qe(e),Gt(e),Qt(e),is(e),us(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function c(t,r,o){o||(o=Ts(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();c(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;cs.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(cs.resize(t,l),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,l),s.hasResource(ys)){const e=s.getResource(ys).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ts(e,n,t,l,s.world,h);if(c(t,l,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:l,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}cs.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(_t),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:jn,...t})},exports.debug=function(e,t,s){Hn.debug(e,t,s)},exports.defineComponent=L,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){Hn.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return g(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=g,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=ct.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=V(e);return t?$(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return g(e)?.editorType??"unknown"},exports.getLogger=function(){return Hn},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Hn.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=us,exports.initGeometryAPI=Gt,exports.initMaterialAPI=qe,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=mt,exports.intersectRects=Vs,exports.invertMatrix4=Gs,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return Ln},exports.isKnownAssetExtension=_,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Ln},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=Sn,exports.loadRuntimeScene=$n,exports.loadSceneData=ut,exports.loadSceneWithAssets=dt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&_(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Ys,exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){ct.set(e,t)},exports.registerDrawCallback=Wt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=qs,exports.setEditorMode=function(e){Ln=e},exports.setLogLevel=function(e){Hn.setMinLevel(e)},exports.setWasmErrorHandler=De,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=ds,exports.shutdownGeometryAPI=qt,exports.shutdownMaterialAPI=Ye,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=bn,exports.textPlugin=js,exports.transitionTo=async function(e,t,s){const n=e.getResource(ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=mn,exports.uiLayoutPlugin=dn,exports.uiMaskPlugin=Zs,exports.uiPlugins=jn,exports.unregisterDrawCallback=zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Hn.warn(e,t,s)},exports.worldRectToScreen=Xs,exports.wrapSceneSystem=xs,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().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}async function s(e,s){return t().fetch(e,s)}async function n(e){return t().readFile(e)}async function r(e){return t().readTextFile(e)}async function o(e){return t().fileExists(e)}function i(e,s){return t().createCanvas(e,s)}function a(){return t().now()}function c(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function l(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 u=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},h=new Map,p=new Set;for(const e of u)for(const t of e.extensions)h.set(t,e),p.add(t);function f(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function _(e){return h.get(f(e))}function g(e){return p.has(e.toLowerCase())}function m(){const e=[];for(const t of u)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function y(e){const t=_(e);return t?.wechatPackInclude??!1}let x=null;function w(){return x||(x=wx.getFileSystemManager()),x}function v(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(y(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 b(e){return new Promise((t,s)=>{w().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error(v(e,t.errMsg)))}})})}function S(e,t="utf-8"){return new Promise((s,n)=>{w().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error(v(e,t.errMsg)))}})})}function P(e){return new Promise(t=>{w().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function T(e){return new Promise((t,s)=>{const n=wx.createImage();n.onload=()=>t(n),n.onerror=t=>s(new Error(`Failed to load image: ${e}, ${t}`)),n.src=e})}function C(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}let A=!1;const E=new class{constructor(){this.name="wechat"}async fetch(e,t){return c(e,t)}async readFile(e){return b(e)}async readTextFile(e){return S(e)}async fileExists(e){return P(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return l(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){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},M=1920,R=1080,I={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};const F=4294967295,B=4294967295;function $(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map($);const t={};for(const s in e)t[s]=$(e[s]);return t}let k=0;function U(e,t){const s=++k;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...$(t),...e}:$(t)}}function D(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function L(e,t){const s=D(),n=s.get(e);if(n)return n;const r=U(e,t);return s.set(e,r),O(e,t,!1),r}function W(e){const t=D(),s=t.get(e);if(s)return s;const n=U(e,{});return t.set(e,n),O(e,{},!0),n}function z(e){return D().get(e)}function O(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function H(e){return!0===e._builtin}const j=new Map;function N(e,t){j.set(e,t)}function V(e){return j.get(e)??z(e)}function X(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return j.set(e,s),s}const G={Perspective:0,Orthographic:1},q={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},Y={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},J=X("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),K=X("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Q=X("Sprite",{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Z=X("Camera",{projectionType:G.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:q.ColorAndDepth}),ee=X("Canvas",{designResolution:{x:M,y:R},pixelsPerUnit:100,scaleMode:Y.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),te=X("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),se=X("Parent",{entity:0}),ne=X("Children",{entities:[]}),re=X("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:B}),oe=X("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}),ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},ae=L("SceneOwner",{scene:"",persistent:!1});N("Name",ie);const ce=X("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),le=X("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ue=X("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),de=X("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),he={Static:0,Kinematic:1,Dynamic:2};let pe=0;function fe(e,t){const s=++pe;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function _e(e){return{_type:"res",_resource:e}}function ge(e){return{_type:"res_mut",_resource:e}}class me{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class ye{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new me(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const xe=fe({delta:0,elapsed:0,frameCount:0},"Time");function we(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}class ve{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>we(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,o=e.length>0,i=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let u=null;this.world_.beginIteration();try{for(const d of n){if(null!==u&&o)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,t.component,t.data)}if(i){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(d,t[s])){e=!0;break}if(e)continue}a[0]=d;for(let e=0;e<r;e++)a[e+1]=this.world_.get(d,s[e]);if(o){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];u=d}yield a}}finally{if(this.world_.endIteration(),null!==u&&o)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(u,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(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}class be{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=H(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 Se{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new be(this,null);return this.spawned_.push(e),e}entity(e){return new be(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Pe;exports.Schedule=void 0,(Pe=exports.Schedule||(exports.Schedule={}))[Pe.Startup=0]="Startup",Pe[Pe.First=1]="First",Pe[Pe.PreUpdate=2]="PreUpdate",Pe[Pe.Update=3]="Update",Pe[Pe.PostUpdate=4]="PostUpdate",Pe[Pe.Last=5]="Last",Pe[Pe.FixedPreUpdate=10]="FixedPreUpdate",Pe[Pe.FixedUpdate=11]="FixedUpdate",Pe[Pe.FixedPostUpdate=12]="FixedPostUpdate";let Te=0;function Ce(e,t,s){const n=++Te;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Ae(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}class Ee{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Se&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new ve(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Se(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Me{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 Re=fe(new Me,"Input");class Ie{constructor(e){this.target_=e??null}build(e){const s=new Me;e.insertResource(Re,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,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const Fe=new Ie;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=$e(t[e]),o=$e(r);"null"!==s&&"undefined"!==s&&(s!==o&&null!=r&&n.push({field:e,expected:s,actual:o,value:r}))}return n}function $e(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ke(e,t){const s=[`Invalid component data for "${e}":`];for(const e of t)s.push(` - Field "${e.field}": expected ${e.expected}, got ${e.actual} (${JSON.stringify(e.value)})`);return s.join("\n")}let Ue=null;function De(e){Ue=e}function Le(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Ue&&Ue(e,t)}function We(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:We(e)}}return t}class ze{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==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 Le(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Le(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.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Le(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Le(t,`removeParent(entity=${e})`)}}insert(e,t,s){return H(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return H(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return H(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(H(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Le(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.");H(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_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(ke(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,We(r))}catch(s){Le(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Le(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 Le(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Le(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(ke(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let o=this.entityComponents_.get(e);return o||(o=[],this.entityComponents_.set(e,o)),-1===o.indexOf(t._id)&&o.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.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,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_)for(const[s,n]of j)if(H(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let o=null,i=1/0;for(const t of e)if(!H(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<i&&(i=s,o=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=o?o.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const Oe=fe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var He;function je(e){return"object"==typeof e&&null!==e&&"__textureRef"in e}exports.BlendMode=void 0,(He=exports.BlendMode||(exports.BlendMode={}))[He.Normal=0]="Normal",He[He.Additive=1]="Additive",He[He.Multiply=2]="Multiply",He[He.Screen=3]="Screen",He[He.PremultipliedAlpha=4]="PremultipliedAlpha";let Ne=null,Ve=null,Xe=1;const Ge=new Map;function qe(e){Ne=e,Ve=e.getResourceManager(),rt()}function Ye(){0!==Ze&&Ne&&(Ne._free(Ze),Ze=0),Ge.clear(),Xe=1,Qe=!1,tt.clear(),st=null,Ve=null,Ne=null}function Je(){if(!Ve)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ve}const Ke={createShader:(e,t)=>Je().createShader(e,t),releaseShader(e){e>0&&Je().releaseShader(e)},create(e){const t=Xe++,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 Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??exports.BlendMode.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},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=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Xe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.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=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Qe=!1,Ze=0;const et=4096,tt=new Map;let st=null;function nt(e){const t=(0===Ze&&Ne&&(Ze=Ne._malloc(et)),Ze);if(0===t||!Ne)return{ptr:0,count:0};let s=0,n=0;const r=Ne.HEAPU8,o=Ne.HEAPU32,i=Ne.HEAPF32;for(const[a,c]of e){if(s+128>et)break;let e=tt.get(a);e||(st||(st=new TextEncoder),e=st.encode(a),tt.set(a,e));const l=e.length,u=4*Math.ceil(l/4);o[t+s>>2]=l,s+=4,r.set(e,t+s),s+=u;let d=0,h=[0,0,0,0];if("number"==typeof c)d=0,h[0]=c;else if(Array.isArray(c)){d=Math.min(c.length-1,3);for(let e=0;e<Math.min(c.length,4);e++)h[e]=c[e]}else"w"in c?(d=3,h=[c.x,c.y,c.z,c.w]):"z"in c?(d=2,h=[c.x,c.y,c.z,0]):"y"in c&&(d=1,h=[c.x,c.y,0,0]);o[t+s>>2]=d,s+=4;for(let e=0;e<4;e++)i[t+s>>2]=h[e],s+=4;n++}return{ptr:t,count:n}}function rt(){if(!Ne||Qe)return;Ne.materialDataProvider=(e,t,s,n,r)=>{const o=Ge.get(e);if(!o)return Ne.HEAPU32[t>>2]=0,Ne.HEAPU32[s>>2]=0,Ne.HEAPU32[n>>2]=0,void(Ne.HEAPU32[r>>2]=0);Ne.HEAPU32[t>>2]=o.shader,Ne.HEAPU32[s>>2]=o.blendMode;const{ptr:i,count:a}=nt(o.uniforms);Ne.HEAPU32[n>>2]=i,Ne.HEAPU32[r>>2]=a},Qe=!0}const ot={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class it{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const o={promise:null,aborted:!1};o.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{o.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return o.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,o);try{return await o.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class at{constructor(e,t=""){this.cache_=new it,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&&(Ke.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ke.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await o(t))throw new Error(`Material file not found: ${t}`);const s=await r(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:Ke.createFromAsset(n,a),shaderHandle:a,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ct=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function lt(e){return ct.get(e)?.fields??[]}function ut(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,ie,{value:n.name}),!1!==n.visible)for(const s of n.components)ht(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function dt(e,t,s){const n=new Map,r=s?.assetServer,o=s?.assetBaseUrl,i=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,o=new Set,i=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ct.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":o.add(t);break;case"font":i.add(t)}}}const l=new Map,u=new Map,d=new Map,h=[];for(const e of r)h.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,o=await t.loadTexture(r);l.set(e,o.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of o)h.push((async()=>{try{const n=await t.loadMaterial(e,s);u.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),u.set(e,0)}})());for(const e of i)h.push((async()=>{try{const n=await t.loadBitmapFont(e,s);d.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),d.set(e,0)}})());for(const e of a)h.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(h);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ct.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=u.get(t)??0;break;case"font":s[e.field]=d.get(t)??0}}}}(t,r,o,i);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,ie,{value:s.name}),!1!==s.visible)for(const n of s.components)ht(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=i.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function ht(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=V(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}class pt{constructor(e){this.textureCache_=new it,this.shaderCache_=new it,this.jsonCache_=new it,this.textCache_=new it,this.binaryCache_=new it,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new it,this.prefabCache_=new it,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=i(I.textCanvasSize,I.textCanvasSize),this.ctx_=this.canvas_.getContext("2d",{willReadFrequently:!0});const t={load:e=>this.loadShader(e),get:e=>this.shaderCache_.get(e)};this.materialLoader_=new at(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const o=(this.textureRefCounts_.get(n)??1)-1;o<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,o)}}releaseAll(){const e=this.module_.getResourceManager();for(const t of this.textureCache_.values())e.releaseTexture(t.handle);for(const t of this.fontCache_.values())e.releaseBitmapFont(t);if(this.materialLoader_.releaseAll(),Ke.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),o=await this.fetchText(r);if(!this.writeToVirtualFS(t,o))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const i=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(o),c=[];for(const e of a){const t=i?`${i}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),u="binary"===_(e)?.contentType,d=u?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,d))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(d,o,u);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=_(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),o=r?`${r}/${n}`:n,i=await this.loadTextureRaw(o);return this.module_.getResourceManager().loadBitmapFont(t,i.handle,i.width,i.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return dt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const o=t().createImage();o.crossOrigin="anonymous",o.onload=async()=>{if("undefined"!=typeof createImageBitmap)try{const e=await createImageBitmap(o,{premultiplyAlpha:"none",colorSpaceConversion:"none"});return void s(e)}catch{}s(o)},o.onerror=()=>n(new Error(`Failed to load image: ${e}`)),o.src=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const o=e.createTexture();e.bindTexture(e.TEXTURE_2D,o),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const i=this.module_.GL,a=i.getNewId(i.textures);i.textures[a]=o;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),o=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(o);const i=this.module_.getResourceManager(),a=this.module_._malloc(o.length);this.module_.HEAPU8.set(o,a);const c=i.createTexture(t,s,a,o.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ke.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await o(t))throw new Error(`Shader file not found: ${e}`);const n=await r(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 Ke.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://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await r(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return r(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await s(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 s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return n(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const r=await s(e);if(!r.ok)throw new Error(`Failed to fetch binary: ${e} (${r.status})`);return r.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const ft=fe(null,"Assets");class _t{build(e){const t=e.wasmModule;t?e.insertResource(ft,new pt(t)):console.warn("AssetPlugin: No WASM module available")}}const gt=new _t;async function mt(e,t,s){const{entities:n,rootId:r}=await xt(t,s?.overrides??[],s,void 0,new Set),o={version:t.version,name:t.name,entities:n.map(e=>({id:e.id,name:e.name,parent:e.parent,children:e.children,components:e.components,visible:e.visible}))},i=await dt(e,o,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=i.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:i}}const yt=10;async function xt(e,t,s,n,r,o=0){if(o>yt)throw new Error(`Prefab nesting depth exceeded ${yt}. Check for deep or circular nesting in: ${e.name}`);const i=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(i.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||i.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await xt(e,n.nestedPrefab.overrides,s,a,r,o+1);i.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?i.get(n.parent)??null:null),c.push(...t.entities);continue}const l=i.get(n.prefabEntityId),u=n.prefabEntityId===e.rootEntityId,d={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:u?null:null!==n.parent?i.get(n.parent)??null:null,children:n.children.map(e=>i.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};wt(d,t),c.push(d)}const l=i.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function wt(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 vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return mt(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const bt=fe(null,"Prefabs");class St{constructor(){this.name="PrefabsPlugin",this.dependencies=[ft]}build(e){const t=e.getResource(ft);e.insertResource(bt,new vt(e.world,t))}}const Pt=new St;let Tt=null,Ct=0,At=0,Et=0;const Mt=new Float32Array(256);function Rt(e){Tt=e,Ct=Tt._malloc(64),At=Tt._malloc(64),Et=Tt._malloc(1024)}function It(){Tt&&(Ct&&(Tt._free(Ct),Ct=0),At&&(Tt._free(At),At=0),Et&&(Tt._free(Et),Et=0)),Tt=null}function Ft(){if(!Tt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Tt}const Bt={r:1,g:1,b:1,a:1},$t={begin(e){const t=Ft();try{t.HEAPF32.set(e,Ct/4),t.draw_begin(Ct)}catch(e){Le(e,"Draw.begin")}},end(){try{Ft().draw_end()}catch(e){Le(e,"Draw.end")}},line(e,t,s,n=1){try{Ft().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.line")}},rect(e,t,s,n=!0){try{Ft().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{Ft().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Le(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{Ft().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Le(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{Ft().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Le(e,"Draw.circleOutline")}},texture(e,t,s,n=Bt){try{Ft().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Le(e,"Draw.texture")}},textureRotated(e,t,s,n,r=Bt){try{Ft().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Le(e,"Draw.textureRotated")}},setLayer(e){Ft().draw_setLayer(e)},setDepth(e){Ft().draw_setDepth(e)},getDrawCallCount:()=>Tt?Tt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Tt?Tt.draw_getPrimitiveCount():0,setBlendMode(e){Ft().draw_setBlendMode(e)},setDepthTest(e){Ft().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=Ft();n.HEAPF32.set(s,At/4),n.draw_mesh(e,t,At)}catch(s){Le(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=Ft(),r=Ke.get(t);if(!r)return;if($t.setBlendMode(r.blendMode),$t.setDepthTest(r.depthTest),0===r.uniforms.size)return void $t.drawMesh(e,r.shader,s);let o;if(n.HEAPF32.set(s,At/4),!r.dirty_&&r.cachedBuffer_)o=r.cachedIdx_;else{o=0;let e=0;for(const[t,s]of r.uniforms){const n=Dt(t);if(!(n<0)){if(je(s))Mt[o++]=10,Mt[o++]=n,Mt[o++]=s.slot??e++,Mt[o++]=s.textureId;else if("number"==typeof s)Mt[o++]=1,Mt[o++]=n,Mt[o++]=s;else if(Array.isArray(s)){Mt[o++]=s.length,Mt[o++]=n;for(let e=0;e<s.length;e++)Mt[o++]=s[e]}else"w"in s?(Mt[o++]=4,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y,Mt[o++]=s.z,Mt[o++]=s.w):"z"in s?(Mt[o++]=3,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y,Mt[o++]=s.z):(Mt[o++]=2,Mt[o++]=n,Mt[o++]=s.x,Mt[o++]=s.y);if(o>250){console.warn("Uniform buffer overflow, some uniforms will be ignored");break}}}(!r.cachedBuffer_||r.cachedBuffer_.length<o)&&(r.cachedBuffer_=new Float32Array(o)),r.cachedBuffer_.set(Mt.subarray(0,o)),r.cachedIdx_=o,r.dirty_=!1}if(0===o)return void n.draw_mesh(e,r.shader,At);n.HEAPF32.set(r.cachedBuffer_.subarray(0,o),Et/4),n.draw_meshWithUniforms(e,r.shader,At,Et,o)}catch(s){Le(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},kt={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},Ut=new Set;function Dt(e){const t=kt[e];return void 0!==t?t:(Ut.has(e)||(Ut.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(kt).join(", ")}`)),-1)}const Lt=new Map;function Wt(e,t,s){Lt.set(e,{fn:t,scene:s??""})}function zt(e){Lt.delete(e)}function Ot(){Lt.clear()}var Ht;exports.DataType=void 0,(Ht=exports.DataType||(exports.DataType={}))[Ht.Float=1]="Float",Ht[Ht.Float2=2]="Float2",Ht[Ht.Float3=3]="Float3",Ht[Ht.Float4=4]="Float4",Ht[Ht.Int=5]="Int",Ht[Ht.Int2=6]="Int2",Ht[Ht.Int3=7]="Int3",Ht[Ht.Int4=8]="Int4";let jt=null,Nt=0,Vt=0,Xt=0;function Gt(e){jt=e,Nt=jt._malloc(262144),Vt=jt._malloc(65536),Xt=jt._malloc(256)}function qt(){jt&&(Nt&&jt._free(Nt),Vt&&jt._free(Vt),Xt&&jt._free(Xt),Nt=0,Vt=0,Xt=0),jt=null}function Yt(){if(!jt)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return jt}const Jt={create(e){const t=Yt(),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,Nt/4);const r=e.layout.length,o=new Int32Array(r);for(let t=0;t<r;t++)o[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Xt,r).set(o),t.geometry_init(s,Nt,n,Xt,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,Vt,n).set(e.indices),t.geometry_setIndices16(s,Vt,n)}else{new Uint32Array(t.HEAPU8.buffer,Vt,n).set(e.indices),t.geometry_setIndices32(s,Vt,n)}}return s},updateVertices(e,t,s=0){const n=Yt(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Nt/4),n.geometry_updateVertices(e,Nt,r,s)},release(e){e>0&&Yt().geometry_release(e)},isValid:e=>!(!jt||e<=0)&&jt.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return Jt.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,o=Math.cos(r)*e,i=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(o,i,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return Jt.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const o of e)t=Math.min(t,o.x),s=Math.min(s,o.y),n=Math.max(n,o.x),r=Math.max(r,o.y);const o=[];for(const i of e){const e=(i.x-t)/(n-t),a=(i.y-s)/(r-s);o.push(i.x,i.y,e,a)}const i=[];for(let t=1;t<e.length-1;t++)i.push(0,t,t+1);return Jt.create({vertices:new Float32Array(o),layout:[{name:"a_position",type:exports.DataType.Float2},{name:"a_texCoord",type:exports.DataType.Float2}],indices:new Uint16Array(i)})}};let Kt=null;function Qt(e){Kt=e}function Zt(){Kt&&ts.isInitialized()&&ts.shutdown(),Kt=null}function es(){if(!Kt)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Kt}const ts={init(e,t){try{return es().postprocess_init(e,t)}catch(s){return Le(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{es().postprocess_shutdown()}catch(e){Le(e,"PostProcess.shutdown")}},resize(e,t){try{es().postprocess_resize(e,t)}catch(s){Le(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return es().postprocess_addPass(e,t)}catch(t){return Le(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{es().postprocess_removePass(e)}catch(t){Le(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{es().postprocess_setPassEnabled(e,t)}catch(t){Le(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return es().postprocess_isPassEnabled(e)}catch(t){return Le(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{es().postprocess_setUniformFloat(e,t,s)}catch(s){Le(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{es().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Le(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{es().postprocess_begin()}catch(e){Le(e,"PostProcess.begin")}},end(){try{es().postprocess_end()}catch(e){Le(e,"PostProcess.end")}},getPassCount(){try{return es().postprocess_getPassCount()}catch(e){return Le(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Kt)return!1;try{return Kt.postprocess_isInitialized()}catch(e){return Le(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{es().postprocess_setBypass(e)}catch(e){Le(e,"PostProcess.setBypass")}},isBypassed(){if(!Kt)return!0;try{return Kt.postprocess_isBypassed()}catch(e){return Le(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#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:()=>Ke.createShader(ss,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ke.createShader(ss,"#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")},ss="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var ns;exports.RenderStage=void 0,(ns=exports.RenderStage||(exports.RenderStage={}))[ns.Background=0]="Background",ns[ns.Opaque=1]="Opaque",ns[ns.Transparent=2]="Transparent",ns[ns.Overlay=3]="Overlay";let rs=null,os=0;function is(e){rs=e,os=rs._malloc(64)}function as(){rs&&os&&(rs._free(os),os=0),rs=null}const cs={init(e,t){rs?.renderer_init(e,t)},resize(e,t){rs?.renderer_resize(e,t)},begin(e,t){if(rs&&os)try{rs.HEAPF32.set(e,os/4),rs.renderer_begin(os,t??0)}catch(e){Le(e,"Renderer.begin")}},flush(){try{rs?.renderer_flush()}catch(e){Le(e,"Renderer.flush")}},end(){try{rs?.renderer_end()}catch(e){Le(e,"Renderer.end")}},submitSprites(e){if(rs)try{rs.renderer_submitSprites(e._cpp)}catch(e){Le(e,"Renderer.submitSprites")}},submitBitmapText(e){if(rs)try{rs.renderer_submitBitmapText(e._cpp)}catch(e){Le(e,"Renderer.submitBitmapText")}},submitSpine(e){if(rs)try{rs.renderer_submitSpine?.(e._cpp)}catch(e){Le(e,"Renderer.submitSpine")}},setStage(e){rs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>rs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){rs?.renderer_releaseTarget(e)},getTargetTexture:e=>rs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>rs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){rs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){rs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){rs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){rs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>rs?rs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>rs?{drawCalls:rs.renderer_getDrawCalls(),triangles:rs.renderer_getTriangles(),sprites:rs.renderer_getSprites(),text:rs.renderer_getText(),spine:rs.renderer_getSpine?.()??0,meshes:rs.renderer_getMeshes(),culled:rs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let ls=null;function us(e){ls=e}function ds(){ls=null}const hs={enable(){ls?.gl_enableErrorCheck(!0)},disable(){ls?.gl_enableErrorCheck(!1)},check:e=>ls?.gl_checkErrors(e)??0,diagnose(){ls?.renderer_diagnose()}};class ps{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:o}=e;n===this.lastWidth_&&r===this.lastHeight_||(cs.resize(n,r),ts.isInitialized()&&ts.getPassCount()>0&&ts.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),cs.setViewport(0,0,n,r),cs.clearBuffers(3),cs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),cs.submitSprites(t),cs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):cs.submitSpine(t),cs.flush(),this.executeDrawCallbacks(s,o),cs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:o}=e;cs.setViewport(n.x,n.y,n.w,n.h),cs.setScissor(n.x,n.y,n.w,n.h,!0),cs.clearBuffers(r),cs.setScissor(0,0,0,0,!1),cs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),cs.submitSprites(t),cs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,o):cs.submitSpine(t),cs.flush(),this.executeDrawCallbacks(s,o),cs.end()}executeDrawCallbacks(e,t){const s=Lt;if(s.size>0){$t.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}$t.end();for(const e of n)zt(e)}}}const fs="__scene_transition_overlay__";class _s{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class gs{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,ae,{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),Wt(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=ts.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){ts.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,ae)){const s=this.app_.world.get(e,ae);s.persistent=t,this.app_.world.insert(e,ae,s)}}}class ms{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.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??I.sceneTransitionDuration,r=t.color??{...I.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Wt(fs,()=>{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;$t.setLayer(9999),$t.setDepth(9999),$t.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,zt(fs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,zt(fs),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 _s(t);this.scenes_.set(e,s);const n=new gs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new _s(t);this.scenes_.set(e,s);const n=new gs(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(ft)?this.app_.getResource(ft):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(ft)&&(t.assetServer=this.app_.getResource(ft));const n=await dt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,ae,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=xs(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,ae)){if(this.app_.world.get(e,ae).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())zt(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{ts.removePass(e)}catch{}s.postProcessPasses.length=0,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)}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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Q,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Q)){const s=this.app_.world.get(e,Q),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Q,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{ts.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const ys=fe(null,"SceneManager");function xs(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(ys).getSceneStatus(t)&&s._fn(...n)}}}const ws=Ce([ge(ys),_e(xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),vs={name:"SceneManager",build(e){const t=new ms(e);e.insertResource(ys,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(ys),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(exports.Schedule.Startup,s),e.addSystemToSchedule(exports.Schedule.Last,ws)}};class bs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=a(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(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_=0),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)}requestAnimationFrame(this.mainLoop)},this.world_=new ze,this.resources_=new ye;for(const e of Object.values(exports.Schedule))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new bs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),this}addSystemToSchedule(e,t,s){return this.systems_.get(e).push({system:t,runBefore:s?.runBefore,runAfter:s?.runAfter}),this.sortedSystemsCache_.delete(e),this}addSystem(e){return this.addSystemToSchedule(exports.Schedule.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(exports.Schedule.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return De(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(ys).register(e),this}setInitialScene(e){return this.getResource(ys).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ee(this.world_,this.resources_),this.resources_.insert(xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(exports.Schedule.Startup),this.lastTime_=a(),this.mainLoop())}quit(){this.running_=!1,Ot();const e=[ds,as,Zt,qt,Ye,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}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,o=i=>{if(n.has(i))return;if(r.has(i)){const t=e[i].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(i);const a=e[i];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&o(s)}r.delete(i),n.add(i),s.push(a)};for(let t=0;t<e.length;t++)o(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(xe);t.delta=e,t.elapsed+=e,t.frameCount++}}const Ss=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Ps(e,t,s,n,r){const o=e*t/s,i=e;switch(n){case Y.FixedWidth:return o;case Y.FixedHeight:return i;case Y.Expand:return Math.max(o,i);case Y.Shrink:return Math.min(o,i);case Y.Match:{const e=r;return Math.pow(o,1-e)*Math.pow(i,e)}default:return i}}function Ts(e,t,s,n,r,o){if(0===s||0===n)return[];const i=e.registry_getCameraEntities(t);if(0===i.length)return[];const a=o&&r?i.filter(e=>{const t=r.tryGet(e,ae);return!t||""===t.scene||o.has(t.scene)}):i;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),o=t.getLocalTransform(e),i={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=i.w*s/(i.h*n);let u,d=0,h=0;if(r.projectionType===G.Orthographic){if(h=r.orthoSize,c){h=Ps(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}d=h*a,u=As(-d,d,-h,h,-r.farPlane,r.farPlane)}else u=Ms(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const p=Is(o.position.x,o.position.y,o.position.z);l.push({entity:e,viewProjection:new Float32Array(Bs(u,p)),viewportRect:i,clearFlags:r.clearFlags,priority:r.priority,halfW:d,halfH:h,cameraX:o.position.x,cameraY:o.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Cs=new Float32Array(16);function As(e,t,s,n,r,o){const i=Cs;i.fill(0);const a=t-e,c=n-s,l=o-r;return i[0]=2/a,i[5]=2/c,i[10]=-2/l,i[12]=-(t+e)/a,i[13]=-(n+s)/c,i[14]=-(o+r)/l,i[15]=1,i}const Es=new Float32Array(16);function Ms(e,t,s,n){const r=Es;r.fill(0);const o=1/Math.tan(e/2),i=s-n;return r[0]=o/t,r[5]=o,r[10]=(n+s)/i,r[11]=-1,r[14]=2*n*s/i,r}const Rs=new Float32Array(16);function Is(e,t,s){const n=Rs;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 Fs=new Float32Array(16);function Bs(e,t){const s=Fs;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var $s,ks,Us;exports.TextAlign=void 0,($s=exports.TextAlign||(exports.TextAlign={}))[$s.Left=0]="Left",$s[$s.Center=1]="Center",$s[$s.Right=2]="Right",exports.TextVerticalAlign=void 0,(ks=exports.TextVerticalAlign||(exports.TextVerticalAlign={}))[ks.Top=0]="Top",ks[ks.Middle=1]="Middle",ks[ks.Bottom=2]="Bottom",exports.TextOverflow=void 0,(Us=exports.TextOverflow||(exports.TextOverflow={}))[Us.Visible=0]="Visible",Us[Us.Clip=1]="Clip",Us[Us.Ellipsis=2]="Ellipsis";const Ds=L("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:exports.TextAlign.Left,verticalAlign:exports.TextVerticalAlign.Top,wordWrap:!0,overflow:exports.TextOverflow.Visible,lineHeight:1.2}),Ls=L("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}});class Ws{constructor(e){this.cache=new Map,this.module=e,this.canvas=i(I.textCanvasSize,I.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,o=r?t.size.x:0,i=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?o:0);const l=Math.ceil(e.fontSize*e.lineHeight),u=Math.ceil(.2*e.fontSize),d=Math.ceil(this.measureWidth(c)),h=Math.ceil(c.length*l),p=r?Math.ceil(o):d+2*u,f=r?Math.ceil(i):h+2*u;if(r&&e.overflow===exports.TextOverflow.Ellipsis&&h>i){const e=Math.floor(i/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,o)}}if(n.width<p||n.height<f){const e=Math.max(n.width,this.nextPowerOf2(p)),t=Math.max(n.height,this.nextPowerOf2(f));n.width=e,n.height=t}const _=Math.round(255*e.color.r),g=Math.round(255*e.color.g),m=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(${_}, ${g}, ${m}, ${y})`,r&&e.overflow===exports.TextOverflow.Clip&&(s.save(),s.beginPath(),s.rect(0,0,p,f),s.clip());const x=c.length*l;let w;if(r)switch(e.verticalAlign){case exports.TextVerticalAlign.Top:w=u;break;case exports.TextVerticalAlign.Middle:w=(f-x)/2;break;case exports.TextVerticalAlign.Bottom:w=f-x-u;break;default:w=u}else w=u;let v=w;for(const t of c){let n;switch(e.align){case exports.TextAlign.Left:n=u;break;case exports.TextAlign.Center:n=p/2;break;case exports.TextAlign.Right:n=p-u;break;default:n=u}s.fillText(t,n,v),v+=l}r&&e.overflow===exports.TextOverflow.Clip&&s.restore();const b=s.getImageData(0,0,p,f),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),T=this.module._malloc(S.length);this.module.HEAPU8.set(S,T);const C=P.createTexture(p,f,T,S.length,1,!0);return this.module._free(T),{textureHandle:C,width:p,height:f}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case exports.TextAlign.Left:return"left";case exports.TextAlign.Center:return"center";case exports.TextAlign.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function zs(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function Os(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Hs{build(e){N("Text",Ds);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Ws(t),n=e.world,r=new Map;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Ds));for(const e of r.keys())n.valid(e)&&n.has(e,Ds)||r.delete(e);const e=n.getEntitiesWithComponents([Ds]);for(const t of e){const e=n.get(t,Ds),o=n.has(t,Ls)?n.get(t,Ls):null,i=r.get(t);if(i&&!Os(i,e,o))continue;n.has(t,Q)||n.insert(t,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,o),c=n.get(t,Q);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Q,c),r.set(t,zs(e,o))}}))}}const js=new Hs,Ns=L("UIMask",{enabled:!0});function Vs(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),o=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,o-n)}}function Xs(e,t,s,n,r,o,i,a,c,l,u){const d=e-s*r,h=e+s*(1-r),p=t-n*o,f=t+n*(1-o);function _(e,t){const s=i[0]*e+i[4]*t+i[12],n=i[1]*e+i[5]*t+i[13],r=i[3]*e+i[7]*t+i[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*u]}const[g,m]=_(d,p),[y,x]=_(h,f),w=Math.min(g,y),v=Math.max(g,y),b=Math.min(m,x),S=Math.max(m,x);return{x:Math.round(w),y:Math.round(b),w:Math.round(v-w),h:Math.round(S-b)}}function Gs(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],o=e[2],i=e[3],a=e[4],c=e[5],l=e[6],u=e[7],d=e[8],h=e[9],p=e[10],f=e[11],_=e[12],g=e[13],m=e[14],y=e[15],x=n*c-r*a,w=n*l-o*a,v=n*u-i*a,b=r*l-o*c,S=r*u-i*c,P=o*u-i*l,T=d*g-h*_,C=d*m-p*_,A=d*y-f*_,E=h*m-p*g,M=h*y-f*g,R=p*y-f*m;let I=x*R-w*M+v*E+b*A-S*C+P*T;return 0===I||(I=1/I,s[0]=(c*R-l*M+u*E)*I,s[1]=(o*M-r*R-i*E)*I,s[2]=(g*P-m*S+y*b)*I,s[3]=(p*S-h*P-f*b)*I,s[4]=(l*A-a*R-u*C)*I,s[5]=(n*R-o*A+i*C)*I,s[6]=(m*v-_*P-y*w)*I,s[7]=(d*P-p*v+f*w)*I,s[8]=(a*M-c*A+u*T)*I,s[9]=(r*A-n*M-i*T)*I,s[10]=(_*S-g*v+y*x)*I,s[11]=(h*v-d*S-f*x)*I,s[12]=(c*C-a*E-l*T)*I,s[13]=(n*E-r*C+o*T)*I,s[14]=(g*w-_*b-m*x)*I,s[15]=(d*b-h*w+p*x)*I),s}function qs(e,t,s,n,r,o,i){const a=(e-n)/o*2-1,c=(t-r)/i*2-1,l=s[0]*a+s[4]*c+s[12],u=s[1]*a+s[5]*c+s[13],d=s[3]*a+s[7]*c+s[15];return{x:l/d,y:u/d}}function Ys(e,t,s,n,r,o,i,a){return e>=s-r*i&&e<=s+r*(1-i)&&t>=n-o*a&&t<=n+o*(1-a)}function Js(e,t,s,n,r,o,i){if(!e.has(t,Ls)||!e.has(t,K))return null;const a=e.get(t,Ls),c=e.get(t,K),l=a.size.x*c.scale.x,u=a.size.y*c.scale.y;return Xs(c.position.x,c.position.y,l,u,a.pivot.x,a.pivot.y,s,n,r,o,i)}function Ks(e,t){return(s,n,r,o,i,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Ns]);if(0!==c.length)try{!function(e,t,s,n,r,o,i,a,c){const l=new Set;for(const e of n){t.get(e,Ns).enabled&&l.add(e)}const u=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,se);){const e=t.get(n,se);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&u.push(e)}function d(n,u){const h=e.getChildEntities(s,n);for(const s of h){let n=u;if(l.has(s)){const e=Js(t,s,r,o,i,a,c);e&&(n=Vs(u,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),d(s,n)}}for(const e of u){const s=Js(t,e,r,o,i,a,c);s&&d(e,s)}}(e,t,s,c,n,r,o,i,a)}catch(t){e.renderer_clearAllClipRects()}}}class Qs{build(e){if(N("UIMask",Ns),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Ks(e.wasmModule,e.world))}}const Zs=new Qs,en=L("Interactable",{enabled:!0}),tn=L("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var sn;exports.ButtonState=void 0,(sn=exports.ButtonState||(exports.ButtonState={}))[sn.Normal=0]="Normal",sn[sn.Hovered=1]="Hovered",sn[sn.Pressed=2]="Pressed",sn[sn.Disabled=3]="Disabled";const nn=L("Button",{state:exports.ButtonState.Normal,transition:null});class rn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}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 on=fe(new rn,"UIEvents"),an=W("ScreenSpace");function cn(e,t,s,n,r,o){const i=o.right-o.left,a=o.top-o.bottom,c=o.left+e.x*i,l=o.left+t.x*i,u=o.bottom+e.y*a,d=o.bottom+t.y*a;let h,p,f,_;if(c===l&&u===d){const e=c+s.x,t=u+s.y,n=.5*r.x,o=.5*r.y;h=e-n,p=t-o,f=e+n,_=t+o}else h=c+s.x,p=u+s.y,f=l+n.x,_=d+n.y;return{centerX:.5*(h+f),centerY:.5*(p+_),width:f-h,height:_-p,rect:{left:h,bottom:p,right:f,top:_}}}function ln(e,t,s,n,r,o){if(!e.has(t,Ls))return;const i=e.get(t,Ls),a=cn(i.anchorMin,i.anchorMax,i.offsetMin,i.offsetMax,i.size,s);i.anchorMin.x===i.anchorMax.x&&i.anchorMin.y===i.anchorMax.y||(i.size.x=a.width,i.size.y=a.height);const c=e.get(t,J);if(o?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,J,c),!e.has(t,ne))return;const l=e.get(t,ne);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&ln(e,t,a.rect,a.centerX,a.centerY,!1)}class un{build(e){N("UIRect",Ls);const t=e.world;e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([_e(Oe)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),o=t.getEntitiesWithComponents([an,Ls,J]);for(const e of o)ln(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const dn=new un,hn=new Float32Array(16),pn=new Float32Array(16);let fn=!0,_n=1;class gn{build(e){N("Interactable",en),N("Button",nn);const t=e.world,s=new rn;e.insertResource(on,s);let n=null,r=null;_n="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([_e(Re),_e(Oe)],(e,o)=>{s.drain();const i=t.getEntitiesWithComponents([tn]);for(const e of i){const s=t.get(e,tn);s.justPressed=!1,s.justReleased=!1}if(!o.valid)return;const a=e.mouseX*_n,c=o.screenH-e.mouseY*_n;!function(e){let t=!1;for(let s=0;s<16;s++)if(pn[s]!==e[s]){t=!0;break}t&&(pn.set(e),fn=!0)}(o.viewProjection),fn&&(Gs(o.viewProjection,hn),fn=!1);const l=qs(a,c,hn,o.vpX,o.vpY,o.vpW,o.vpH),u=t.getEntitiesWithComponents([en,Ls,K]);let d=null,h=-1/0;for(const e of u){t.has(e,tn)||t.insert(e,tn);if(!t.get(e,en).enabled)continue;const s=t.get(e,K),n=t.get(e,Ls),r=n.size.x*s.scale.x,o=n.size.y*s.scale.y;if(Ys(l.x,l.y,s.position.x,s.position.y,r,o,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Q)&&(s=t.get(e,Q).layer),s>=h&&(h=s,d=e)}}if(n!==d){if(null!==n&&t.valid(n)&&t.has(n,tn)){t.get(n,tn).hovered=!1,s.emit(n,"hover_exit")}if(null!==d){t.get(d,tn).hovered=!0,s.emit(d,"hover_enter")}n=d}if(e.isMouseButtonPressed(0)&&null!==d){const e=t.get(d,tn);e.pressed=!0,e.justPressed=!0,r=d,s.emit(d,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,tn)){const e=t.get(r,tn);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(exports.Schedule.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([nn]);for(const s of e){if(t.has(s,en)||t.insert(s,en,{enabled:!0}),!t.has(s,tn))continue;const e=t.get(s,tn),n=t.get(s,nn),r=t.get(s,en),o=n.state;if(r.enabled?e.pressed?n.state=exports.ButtonState.Pressed:e.hovered?n.state=exports.ButtonState.Hovered:n.state=exports.ButtonState.Normal:n.state=exports.ButtonState.Disabled,o!==n.state&&n.transition&&t.has(s,Q)){const e=t.get(s,Q),r=n.transition;switch(n.state){case exports.ButtonState.Normal:e.color={...r.normalColor};break;case exports.ButtonState.Hovered:e.color={...r.hoveredColor};break;case exports.ButtonState.Pressed:e.color={...r.pressedColor};break;case exports.ButtonState.Disabled:e.color={...r.disabledColor}}t.insert(s,Q,e)}}},{name:"ButtonSystem"}))}}const mn=new gn,yn=L("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});class xn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){N("TextInput",yn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=i(I.textCanvasSize,64),o=r.getContext("2d",{willReadFrequently:!0});let a=null,c=!1,l=!0,u=0,d=0;const h=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(!h)return;const p=h,f=()=>{c||null===a||x()},_=()=>{c=!0},g=()=>{c=!1,x()},m=t=>{if(null===a)return;if("Escape"===t.key)return void v();const n=s.get(a,yn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(on).emit(a,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,p.selectionStart=r,p.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==a&&s.valid(a)&&s.has(a,yn)){const e=s.get(a,yn);e.focused=!1,e.dirty=!0}a=null};function x(){if(null===a||!s.valid(a))return;const t=s.get(a,yn);if(t.readOnly)return;let n=p.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),p.value=n),n!==t.value){t.value=n;e.getResource(on).emit(a,"change")}t.cursorPos=p.selectionStart??n.length,t.dirty=!0,b()}function w(e){if(a===e)return;v();const t=s.get(e,yn);t.readOnly||(a=e,t.focused=!0,t.dirty=!0,p.value=t.value,p.selectionStart=t.cursorPos,p.selectionEnd=t.cursorPos,p.focus(),b())}function v(){if(null!==a&&s.valid(a)&&s.has(a,yn)){const e=s.get(a,yn);e.focused=!1,e.dirty=!0}a=null,p.blur()}function b(){l=!0,u=0}function S(e,i,a,c){(r.width<a||r.height<c)&&(r.width=vn(Math.max(r.width,a)),r.height=vn(Math.max(r.height,c))),o.clearRect(0,0,r.width,r.height);const u=i.backgroundColor;o.fillStyle=`rgba(${Math.round(255*u.r)}, ${Math.round(255*u.g)}, ${Math.round(255*u.b)}, ${u.a})`,o.fillRect(0,0,a,c),o.save(),o.beginPath(),o.rect(i.padding,0,a-2*i.padding,c),o.clip(),o.font=`${i.fontSize}px ${i.fontFamily}`,o.textBaseline="top",o.textAlign="left";const d=0===i.value.length,h=d?i.placeholder:i.password?"●".repeat(i.value.length):i.value,p=d?i.placeholderColor:i.color;o.fillStyle=`rgba(${Math.round(255*p.r)}, ${Math.round(255*p.g)}, ${Math.round(255*p.b)}, ${p.a})`;const f=Math.ceil(1.2*i.fontSize),_=i.padding;if(i.multiline){const e=wn(o,h,a-2*_);let t=_;for(const s of e)o.fillText(s,_,t),t+=f}else{const e=(c-i.fontSize)/2;o.fillText(h,_,e)}if(i.focused&&l){const e=i.password?"●".repeat(i.cursorPos):i.value.substring(0,i.cursorPos);let t,s,n;if(i.multiline){const e=wn(o,i.value.substring(0,i.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+o.measureText(r).width,s=_+(e.length-1)*f,n=f}else t=_+o.measureText(e).width,s=(c-i.fontSize)/2,n=i.fontSize;o.fillStyle=`rgba(${Math.round(255*i.color.r)}, ${Math.round(255*i.color.g)}, ${Math.round(255*i.color.b)}, ${i.color.a})`,o.fillRect(t,s,2,n)}o.restore();const g=o.getImageData(0,0,a,c),m=new Uint8Array(g.data.buffer),y=t.getResourceManager(),x=t._malloc(m.length);t.HEAPU8.set(m,x);const w=n.get(e);void 0!==w&&y.releaseTexture(w);const v=y.createTexture(a,c,x,m.length,1,!0);n.set(e,v),t._free(x);const b=s.get(e,Q);b.texture=v,b.size.x=a,b.size.y=c,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,Q,b)}p.addEventListener("input",f),p.addEventListener("compositionstart",_),p.addEventListener("compositionend",g),p.addEventListener("keydown",m),p.addEventListener("blur",y),this.cleanupListeners_=()=>{p.removeEventListener("input",f),p.removeEventListener("compositionstart",_),p.removeEventListener("compositionend",g),p.removeEventListener("keydown",m),p.removeEventListener("blur",y),p.remove()},e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([_e(on)],e=>{const t=s.getEntitiesWithComponents([yn,en]);for(const e of t){if(!s.has(e,tn))continue;if(s.get(e,tn).justPressed)return void w(e)}if(null!==a){const e=s.getEntitiesWithComponents([en]);for(const t of e){if(s.has(t,yn))continue;if(!s.has(t,tn))continue;if(s.get(t,tn).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(exports.Schedule.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===d?0:(e-d)/1e3;if(d=e,null!==a&&(u+=r,u>=.5&&(u-=.5,l=!l,null!==a&&s.valid(a)&&s.has(a,yn)))){s.get(a,yn).dirty=!0}const o=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,yn)||(o.releaseTexture(t),n.delete(e));const i=s.getEntitiesWithComponents([yn,Ls]);for(const e of i){const t=s.get(e,yn);if(!t.dirty)continue;const n=s.get(e,Ls),r=Math.ceil(n.size.x),o=Math.ceil(n.size.y);r<=0||o<=0||(s.has(e,Q)||s.insert(e,Q,{texture:F,color:{r:1,g:1,b:1,a:1},size:{x:r,y:o},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),S(e,t,r,o),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function wn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const o of t){const t=n+o;e.measureText(t).width>s&&n?(r.push(n),n=o):n=t}n&&r.push(n)}return r.length>0?r:[""]}function vn(e){let t=1;for(;t<e;)t*=2;return t}const bn=new xn;async function Sn(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 Pn=fe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Tn=fe(null,"PhysicsAPI");function Cn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function An(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class En{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(Pn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Sn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([ee]);for(const s of t){const t=e.world.get(s,ee);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),o=1/r,i=e.world;e.addSystemToSchedule(exports.Schedule.PostUpdate,Ce([_e(xe)],a=>{const c=i.getEntitiesWithComponents([ce,J,K]),l=new Set;for(const r of c){l.add(r);const a=i.get(r,ce),c=i.get(r,K);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const i=Cn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*o,c.position.y*o,i,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),Mn(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===he.Kinematic){const e=Cn(c.rotation);n._physics_setBodyTransform(r,c.position.x*o,c.position.y*o,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),o=r>>2;for(let r=0;r<n;r++){const n=o+4*r,i=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(i))continue;const u=e.world.get(i,J);if(!u)continue;let d=a,h=c,p=l;if(e.world.has(i,se)){const t=e.world.get(i,se);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,K)){const s=e.world.get(t.entity,K),n=Cn(s.rotation),r=a-s.position.x,o=c-s.position.y,i=Math.cos(-n),u=Math.sin(-n);d=(r*i-o*u)/(0!==s.scale.x?s.scale.x:1),h=(r*u+o*i)/(0!==s.scale.y?s.scale.y:1),p=l-n}}u.position.x=d,u.position.y=h;const f=An(p);u.rotation.w=f.w,u.rotation.x=f.x,u.rotation.y=f.y,u.rotation.z=f.z,e.world.insert(i,J,u)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let o=0;o<r;o++){const r=e+6*o;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const o=[],i=t._physics_getCollisionExitCount();if(i>0){const e=t._physics_getCollisionExitBuffer()>>2;for(let s=0;s<i;s++){const n=e+2*s;o.push({entityA:t.HEAPU32[n],entityB:t.HEAPU32[n+1]})}}const a=[],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(Pn,{collisionEnters:n,collisionExits:o,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Tn,Rn._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function Mn(e,t,s){const n=e.world;if(n.has(s,le)){const e=n.get(s,le);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,ue)){const e=n.get(s,ue);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,de)){const e=n.get(s,de);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 Rn{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(Rn.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)}}function In(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const o=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),o}function Fn(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 Bn(e,t,s,n){const r=e.scale.x*t*(s?-1:1),o=e.scale.y*t*(n?-1:1),i=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,u=e.rotation.w,d=a+a,h=c+c,p=l+l,f=a*d,_=a*h,g=a*p,m=c*h,y=c*p,x=l*p,w=u*d,v=u*h,b=u*p;return new Float32Array([(1-(m+x))*r,(_+b)*r,(g-v)*r,0,(_-b)*o,(1-(f+x))*o,(y+w)*o,0,(g+v)*i,(y-w)*i,(1-(f+m))*i,0,e.position.x,e.position.y,e.position.z,1])}async function $n(e,t,s,n,r,o,i,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=In(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let u={},d=null;if(r&&(d=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),u=await async function(e,t,s,n,r){const o={};for(const i of n.entities)for(const n of i.components){if("SpineAnimation"!==n.type||!n.data)continue;const i=n.data.skeletonPath,a=n.data.atlasPath;if(!i||!a)continue;const c=r.resolvePath(i),l=r.resolvePath(a);try{const n=await r.readText(a),u="binary"===_(c)?.contentType;let d,h;if(u){const e=await r.readBinary(i);h=e.length,d=t._malloc(h),t.HEAPU8.set(e,d)}else{const e=await r.readText(i),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,u);if(t._free(d),p<0)continue;o[i]=p;const f=Fn(n),g=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<f.length;t++){const n=g+"/"+f[t];try{const o=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),i=In(e,o,!1),a=e.getResourceManager().getTextureGLId(i);s.setAtlasPageTexture(p,t,a,o.width,o.height)}catch{}}}catch{}}return o}(t,r,d,s,n)),o){new En("",{gravity:i?.gravity??{x:0,y:-9.81},fixedTimestep:i?.fixedTimestep??1/60,subStepCount:i?.subStepCount??4},()=>Promise.resolve(o)).build(e)}const h=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,o;const i=_(r);if("bitmap-font"===i?.editorType&&"json"===i.contentType){const e=JSON.parse(await s.readText(r)),i="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!i){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${i}`:i;t=await s.readText(c),o=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),o=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=o?`${o}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),u=In(e,l,!1),d=e.getResourceManager();n[r]=d.loadBitmapFont(t,u,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),p=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const o=e.vertexSource+e.fragmentSource;let i=n[o];i||(i=Ke.createShader(e.vertexSource,e.fragmentSource),n[o]=i),s[r]=Ke.createFromAsset(e,i)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=lt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,h,p);const f=ut(e.world,s);if(c&&e.hasResource(ys))for(const t of f.values())e.world.insert(t,ae,{scene:c,persistent:!1});if(r&&d){const n=function(e,t,s,n){const r={};for(const o of t.entities)if(!1!==o.visible)for(const t of o.components){if("SpineAnimation"!==t.type||!t.data)continue;const i=s[t.data.skeletonPath];if(void 0===i)continue;const a=e.createInstance(i);if(a<0)continue;const c=n.get(o.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(d,s,u,f);!function(e,t,s,n,r){let o=0;e.setSpineRenderer((i,a)=>{let c=a-o;o=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const o=Number(e),i=r[e],a=l.has(o,oe)?l.get(o,oe):null,u=!1!==a?.playing,d=a?.timeScale??1;u&&n.update(i,c*d);let h=0;if(l.has(o,K)){const e=Bn(l.get(o,K),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);h=t._malloc(64),t.HEAPF32.set(e,h>>2)}const p=n.getMeshBatchCount(i);for(let e=0;e<p;e++){const r=n.getMeshBatchVertexCount(i,e),o=n.getMeshBatchIndexCount(i,e);if(!r||!o)continue;const a=8*r*4,c=2*o,l=s._malloc(a),u=s._malloc(c),d=s._malloc(4),p=s._malloc(4);n.getMeshBatchData(i,e,l,u,d,p);const f=s.HEAPU32[d>>2],_=s.HEAPU32[p>>2],g=new Float32Array(s.HEAPF32.buffer,l,8*r),m=new Uint16Array(s.HEAPU8.buffer,u,o),y=t._malloc(a),x=t._malloc(c);t.HEAPF32.set(g,y>>2),new Uint16Array(t.HEAPU8.buffer,x,o).set(m),t.renderer_submitTriangles(y,r,x,o,f,_,h),t._free(y),t._free(x),s._free(l),s._free(u),s._free(d),s._free(p)}h&&t._free(h)}})}(e,t,r,d,n)}if(a){const t=e.getResource(ft);t&&t.setAddressableManifest(a)}}class kn{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===_(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const o=[];for(const e of n){const t=_(e);if("bitmap-font"!==t?.editorType||"json"!==t.contentType)continue;const s=this.textCache_.get(e);if(s)try{const t=JSON.parse(s),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(n){const t=e.substring(0,e.lastIndexOf("/")),s=t?`${t}/${n}`:n;this.textCache_.has(s)||o.push(fetch(this.resolveUrl(s)).then(e=>e.text()).then(e=>{this.textCache_.set(s,e)}).catch(e=>{console.warn(`[WebAssetProvider] Failed to prefetch font "${s}":`,e)}))}}catch{}}o.length>0&&await Promise.all(o)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),o=new OffscreenCanvas(r.width,r.height).getContext("2d");o.drawImage(r,0,0);const i=o.getImageData(0,0,r.width,r.height);return r.close(),{width:i.width,height:i.height,pixels:new Uint8Array(i.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Un="__preview__";const Dn={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=cs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:cs.getTargetTexture(s),width:e.width,height:e.height}},release(e){cs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(cs.releaseRenderTarget(e._handle),Dn.create({width:t,height:s,depth:!0})),begin(e,t){cs.begin(t,e._handle)},end(){cs.end()},getDepthTexture:e=>cs.getTargetDepthTexture(e._handle)};let Ln=!1;var Wn;exports.LogLevel=void 0,(Wn=exports.LogLevel||(exports.LogLevel={}))[Wn.Debug=0]="Debug",Wn[Wn.Info=1]="Info",Wn[Wn.Warn=2]="Warn",Wn[Wn.Error=3]="Error";class zn{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 On{constructor(){this.handlers_=[],this.minLevel_=exports.LogLevel.Info,this.addHandler(new zn)}setMinLevel(e){this.minLevel_=e}addHandler(e){this.handlers_.push(e)}removeHandler(e){const t=this.handlers_.indexOf(e);-1!==t&&this.handlers_.splice(t,1)}clearHandlers(){this.handlers_=[]}debug(e,t,s){this.log(exports.LogLevel.Debug,e,t,s)}info(e,t,s){this.log(exports.LogLevel.Info,e,t,s)}warn(e,t,s){this.log(exports.LogLevel.Warn,e,t,s)}error(e,t,s){this.log(exports.LogLevel.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const Hn=new On;const jn=[js,Zs,dn,mn,bn];A||(A=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await c(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return l(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=E,exports.App=bs,exports.AssetPlugin=_t,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=pt,exports.Assets=ft,exports.AsyncCache=it,exports.BitmapText=re,exports.BodyType=he,exports.BoxCollider=le,exports.Button=nn,exports.Camera=Z,exports.Canvas=ee,exports.CapsuleCollider=de,exports.Children=ne,exports.CircleCollider=ue,exports.ClearFlags=q,exports.Commands=function(){return{_type:"commands"}},exports.CommandsInstance=Se,exports.DEFAULT_DESIGN_HEIGHT=R,exports.DEFAULT_DESIGN_WIDTH=M,exports.DEFAULT_PIXELS_PER_UNIT=100,exports.DEFAULT_TEXT_CANVAS_SIZE=512,exports.Draw=$t,exports.EntityCommands=be,exports.GLDebug=hs,exports.Geometry=Jt,exports.INVALID_ENTITY=0,exports.INVALID_FONT=B,exports.INVALID_TEXTURE=F,exports.Input=Re,exports.InputPlugin=Ie,exports.InputState=Me,exports.Interactable=en,exports.LocalTransform=J,exports.Logger=On,exports.Material=Ke,exports.MaterialLoader=at,exports.Mut=function(e){return{_type:"mut",_component:e}},exports.Name=ie,exports.Parent=se,exports.Physics=Rn,exports.PhysicsEvents=Pn,exports.PhysicsPlugin=En,exports.PostProcess=ts,exports.PrefabServer=vt,exports.Prefabs=bt,exports.PrefabsPlugin=St,exports.PreviewPlugin=class{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(ys);t.register({name:Un,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Un),this.loadPromise_=t.load(Un).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await s(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),n=new kn(this.baseUrl_);await n.prefetch(t);let r=null;const o=this.app_.spineInitPromise;if(o){r=(await o).controller.raw}await $n(this.app_,this.app_.wasmModule,t,n,r,null,void 0,null,Un)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([Z]);for(const n of s){if(e.get(n,Z).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([ee]);for(const r of n){const n=e.get(r,ee);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(ys).getScene(Un),o=r?r.spawn():e.spawn(),i={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(o,J,i);const a={isActive:!0,projectionType:G.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:q.ColorAndDepth};e.insert(o,Z,a)}}cleanup(){this.eventSource_&&(this.onMessage_&&this.eventSource_.removeEventListener("message",this.onMessage_),this.onError_&&this.eventSource_.removeEventListener("error",this.onError_),this.eventSource_.close(),this.eventSource_=null),this.onMessage_=null,this.onError_=null,this.app_=null}setupHotReload(){const e=new URL(this.sceneUrl_,window.location.href),t=`${e.protocol}//${e.host}/sse-reload`;this.eventSource_=new EventSource(t),this.onMessage_=async e=>{"reload"===e.data&&(console.log("[PreviewPlugin] Reload event received, updating scene..."),await this.reloadScene())},this.onError_=e=>{console.error("[PreviewPlugin] EventSource error:",e)},this.eventSource_.addEventListener("message",this.onMessage_),this.eventSource_.addEventListener("error",this.onError_)}async reloadScene(){if(this.app_)try{const e=this.app_.getResource(ys);await e.switchTo(Un),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.ProjectionType=G,exports.Query=function(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{we(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)},exports.QueryInstance=ve,exports.RenderPipeline=ps,exports.RenderTexture=Dn,exports.Renderer=cs,exports.Res=_e,exports.ResMut=ge,exports.RigidBody=ce,exports.RuntimeConfig=I,exports.ScaleMode=Y,exports.SceneManager=ys,exports.SceneManagerState=ms,exports.SceneOwner=ae,exports.ScreenSpace=an,exports.ShaderSources=ot,exports.SpineAnimation=oe,exports.Sprite=Q,exports.SystemRunner=Ee,exports.Text=Ds,exports.TextInput=yn,exports.TextInputPlugin=xn,exports.TextPlugin=Hs,exports.TextRenderer=Ws,exports.Time=xe,exports.UICameraInfo=Oe,exports.UIEventQueue=rn,exports.UIEvents=on,exports.UIInteraction=tn,exports.UIInteractionPlugin=gn,exports.UILayoutPlugin=un,exports.UIMask=Ns,exports.UIMaskPlugin=Qs,exports.UIRect=Ls,exports.Velocity=te,exports.WebAssetProvider=kn,exports.World=ze,exports.WorldTransform=K,exports.addStartupSystem=function(e){Ae().push({schedule:exports.Schedule.Startup,system:e})},exports.addSystem=function(e){Ae().push({schedule:exports.Schedule.Update,system:e})},exports.addSystemToSchedule=function(e,t){Ae().push({schedule:e,system:t})},exports.applyRuntimeConfig=function(e){e.Text&&(e.Text._default.fontFamily=I.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=I.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=I.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=I.canvasMatchWidthOrHeight)},exports.assetPlugin=gt,exports.clearDrawCallbacks=Ot,exports.clearUserComponents=function(){D().clear()},exports.color=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),exports.computeUIRectLayout=cn,exports.createMaskProcessor=Ks,exports.createRuntimeSceneConfig=function(e,t,s){return{name:e,data:t,async setup(){await $n(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}},exports.createWebApp=function(e,t){return function(e,t){const s=bs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),Rt(e),qe(e),Gt(e),Qt(e),is(e),us(e);const r=new ps;s.setPipeline(r);let o=a();const i=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function c(t,r,o){o||(o=Ts(e,n,t,r));const i=s.getResource(Oe);if(o.length>0){const e=o[0],s=e.viewportRect;i.viewProjection.set(e.viewProjection),i.vpX=Math.round(s.x*t),i.vpY=Math.round((1-s.y-s.h)*r),i.vpW=Math.round(s.w*t),i.vpH=Math.round(s.h*r),i.screenW=t,i.screenH=r,i.worldLeft=e.cameraX-e.halfW,i.worldRight=e.cameraX+e.halfW,i.worldBottom=e.cameraY-e.halfH,i.worldTop=e.cameraY+e.halfH,i.valid=!0}else i.valid=!1}s.insertResource(Oe,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const l={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=i();c(e,t)}},u={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:l}=i();if(0===t||0===l)return;const u=e.registry_getCanvasEntity(n);if(u>=0){const e=n.getCanvas(u).backgroundColor;cs.setClearColor(e.x,e.y,e.z,e.w)}const d=(a()-o)/1e3;let h;if(cs.resize(t,l),ts.isInitialized()&&ts.getPassCount()>0&&!ts.isBypassed()&&ts.resize(t,l),s.hasResource(ys)){const e=s.getResource(ys).getActiveScenes();e.length>0&&(h=new Set(e))}r.setActiveScenes(h??null);const p=Ts(e,n,t,l,s.world,h);if(c(t,l,p),0===p.length)r.render({registry:{_cpp:n},viewProjection:Ss,width:t,height:l,elapsed:d});else{for(const e of p){const s=e.viewportRect,o=Math.round(s.x*t),i=Math.round((1-s.y-s.h)*l),a=Math.round(s.w*t),c=Math.round(s.h*l);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:o,y:i,w:a,h:c},clearFlags:e.clearFlags,elapsed:d})}cs.setViewport(0,0,t,l)}}};if(s.addSystemToSchedule(exports.Schedule.First,l),s.addSystemToSchedule(exports.Schedule.Last,u),s.addPlugin(gt),s.addPlugin(Pt),s.addPlugin(Fe),s.addPlugin(vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:jn,...t})},exports.debug=function(e,t,s){Hn.debug(e,t,s)},exports.defineComponent=L,exports.defineResource=fe,exports.defineSystem=Ce,exports.defineTag=W,exports.error=function(e,t,s){Hn.error(e,t,s)},exports.findEntityByName=function(e,t){const s=e.getEntitiesWithComponents([ie]);for(const n of s){const s=e.get(n,ie);if(s&&s.value===t)return n}return null},exports.flushPendingSystems=function(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}},exports.getAddressableType=function(e){return _(e)?.addressableType??null},exports.getAddressableTypeByEditorType=function(e){for(const t of u)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"},exports.getAllAssetExtensions=function(){return p},exports.getAssetMimeType=function(e){return d[e.toLowerCase()]},exports.getAssetTypeEntry=_,exports.getComponent=V,exports.getComponentAssetFields=function(e){const t=ct.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s},exports.getComponentDefaults=function(e){const t=V(e);return t?$(t._default):null},exports.getCustomExtensions=m,exports.getEditorType=function(e){return _(e)?.editorType??"unknown"},exports.getLogger=function(){return Hn},exports.getPlatform=t,exports.getPlatformType=function(){return e?.name??null},exports.getUserComponent=z,exports.getWeChatPackOptions=function(){return m().map(e=>({type:"suffix",value:e}))},exports.info=function(e,t,s){Hn.info(e,t,s)},exports.initDrawAPI=Rt,exports.initGLDebugAPI=us,exports.initGeometryAPI=Gt,exports.initMaterialAPI=qe,exports.initPostProcessAPI=Qt,exports.initRendererAPI=is,exports.inputPlugin=Fe,exports.instantiatePrefab=mt,exports.intersectRects=Vs,exports.invertMatrix4=Gs,exports.isBuiltinComponent=H,exports.isCustomExtension=y,exports.isEditor=function(){return Ln},exports.isKnownAssetExtension=g,exports.isPlatformInitialized=function(){return null!==e},exports.isRuntime=function(){return!Ln},exports.isTextureRef=je,exports.isWeChat=function(){return"wechat"===e?.name},exports.isWeb=function(){return"web"===e?.name},exports.loadComponent=ht,exports.loadPhysicsModule=Sn,exports.loadRuntimeScene=$n,exports.loadSceneData=ut,exports.loadSceneWithAssets=dt,exports.looksLikeAssetPath=function(e){return"string"==typeof e&&(!!e.includes("/")&&g(f(e)))},exports.platformFetch=s,exports.platformFileExists=o,exports.platformInstantiateWasm=async function(e,s){return t().instantiateWasm(e,s)},exports.platformReadFile=n,exports.platformReadTextFile=r,exports.pointInWorldRect=Ys,exports.prefabsPlugin=Pt,exports.quat=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n}),exports.registerComponent=N,exports.registerComponentAssetFields=function(e,t){ct.set(e,t)},exports.registerDrawCallback=Wt,exports.registerEmbeddedAssets=function(e,t){const s=e.getResource(ft);s&&s.registerEmbeddedAssets(t)},exports.registerMaterialCallback=rt,exports.sceneManagerPlugin=vs,exports.screenToWorld=qs,exports.setEditorMode=function(e){Ln=e},exports.setLogLevel=function(e){Hn.setMinLevel(e)},exports.setWasmErrorHandler=De,exports.shutdownDrawAPI=It,exports.shutdownGLDebugAPI=ds,exports.shutdownGeometryAPI=qt,exports.shutdownMaterialAPI=Ye,exports.shutdownPostProcessAPI=Zt,exports.shutdownRendererAPI=as,exports.textInputPlugin=bn,exports.textPlugin=js,exports.transitionTo=async function(e,t,s){const n=e.getResource(ys);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})},exports.uiInteractionPlugin=mn,exports.uiLayoutPlugin=dn,exports.uiMaskPlugin=Zs,exports.uiPlugins=jn,exports.unregisterDrawCallback=zt,exports.updateCameraAspectRatio=function(e,t){const s=e.getEntitiesWithComponents([Z]);for(const n of s){const s=e.get(n,Z);s&&(s.aspectRatio=t,e.insert(n,Z,s))}},exports.vec2=(e=0,t=0)=>({x:e,y:t}),exports.vec3=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),exports.vec4=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),exports.warn=function(e,t,s){Hn.warn(e,t,s)},exports.worldRectToScreen=Xs,exports.wrapSceneSystem=xs,exports.wxFileExists=P,exports.wxFileExistsSync=function(e){const t=w();try{return t.accessSync(e),!0}catch{return!1}},exports.wxGetImagePixels=C,exports.wxLoadImage=T,exports.wxLoadImagePixels=async function(e){return C(await T(e))},exports.wxReadFile=b,exports.wxReadTextFile=S,exports.wxWriteFile=function(e,t){return new Promise((s,n)=>{w().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 a5f47757f..e532d4706 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(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 _=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},g=new Map,y=new Set;for(const e of _)for(const t of e.extensions)g.set(t,e),y.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return g.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of _)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function $(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(R(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 k(e){return new Promise((t,s)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error($(e,t.errMsg)))}})})}function B(e,t="utf-8"){return new Promise((s,n)=>{F().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error($(e,t.errMsg)))}})})}function U(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function z(e,t){return new Promise((s,n)=>{F().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(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 O(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}async function L(e){return O(await W(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return k(e)}async readTextFile(e){return B(e)}async fileExists(e){return U(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(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){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},N=1920,X=1080,V=100,q=512,G={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function Y(e){e.Text&&(e.Text._default.fontFamily=G.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=G.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=G.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=G.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),te=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),se=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),ne=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const s in e)t[s]=re(e[s]);return t}let ie=0;function oe(e,t){const s=++ie;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ce(e,t){const s=ae(),n=s.get(e);if(n)return n;const r=oe(e,t);return s.set(e,r),de(e,t,!1),r}function le(e){const t=ae(),s=t.get(e);if(s)return s;const n=oe(e,{});return t.set(e,n),de(e,{},!0),n}function he(e){return ae().get(e)}function ue(){ae().clear()}function de(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function fe(e){return!0===e._builtin}const pe=new Map;function _e(e,t){pe.set(e,t)}function me(e){return pe.get(e)??he(e)}function ge(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return pe.set(e,s),s}const ye={Perspective:0,Orthographic:1},we={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ve=ge("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=ge("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=ge("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Pe=ge("Camera",{projectionType:ye.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:we.ColorAndDepth}),Ce=ge("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Te=ge("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ee=ge("Parent",{entity:0}),Me=ge("Children",{entities:[]}),Ae=ge("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q}),Re=ge("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}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Fe=ce("SceneOwner",{scene:"",persistent:!1});function $e(e){const t=me(e);return t?re(t._default):null}_e("Name",Ie);const ke=ge("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Be=ge("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=ge("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),De=ge("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ze={Static:0,Kinematic:1,Dynamic:2};let We=0;function Oe(e,t){const s=++We;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Le(e){return{_type:"res",_resource:e}}function He(e){return{_type:"res_mut",_resource:e}}class je{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 Ne{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 je(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Xe=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{qe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class Ye{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,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(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Je(){return{_type:"commands"}}class Ke{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=fe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ke(this,null);return this.spawned_.push(e),e}entity(e){return new Ke(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ze;!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"}(Ze||(Ze={}));let et=0;function tt(e,t,s){const n=++et;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function nt(e){st().push({schedule:Ze.Update,system:e})}function rt(e){st().push({schedule:Ze.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class ot{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ye(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class at{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 ct=Oe(new at,"Input");class lt{constructor(e){this.target_=e??null}build(e){const s=new at;e.insertResource(ct,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(Ze.Last,tt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ht=new lt;function ut(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=dt(t[e]),i=dt(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function dt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ft(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 pt=null;function _t(e){pt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),pt&&pt(e,t)}function gt(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:gt(e)}}return t}class yt{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==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 mt(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){mt(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.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){mt(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,s){return fe(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return fe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return fe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(fe(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return mt(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.");fe(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_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=ut(t._name,t._default,n);if(e.length>0)throw new Error(ft(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,gt(r))}catch(s){mt(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return mt(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 mt(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){mt(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(ft(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.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,this.queryCache_.clear()}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!fe(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const wt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var xt;function vt(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"}(xt||(xt={}));let bt=null,St=null,Pt=1;const Ct=new Map;function Tt(e){bt=e,St=e.getResourceManager(),Ut()}function Et(){0!==It&&bt&&(bt._free(It),It=0),Ct.clear(),Pt=1,Rt=!1,$t.clear(),kt=null,St=null,bt=null}function Mt(){if(!St)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return St}const At={createShader:(e,t)=>Mt().createShader(e,t),releaseShader(e){e>0&&Mt().releaseShader(e)},create(e){const t=Pt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??xt.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 Ct.set(t,s),t},get:e=>Ct.get(e),setUniform(e,t,s){const n=Ct.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ct.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ct.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??xt.Normal},setDepthTest(e,t){const s=Ct.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear()},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??xt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Pt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(s,n),s},toAssetData(e,t){const s=Ct.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=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Rt=!1,It=0;const Ft=4096,$t=new Map;let kt=null;function Bt(e){const t=(0===It&&bt&&(It=bt._malloc(Ft)),It);if(0===t||!bt)return{ptr:0,count:0};let s=0,n=0;const r=bt.HEAPU8,i=bt.HEAPU32,o=bt.HEAPF32;for(const[a,c]of e){if(s+128>Ft)break;let e=$t.get(a);e||(kt||(kt=new TextEncoder),e=kt.encode(a),$t.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=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 e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}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]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function Ut(){if(!bt||Rt)return;bt.materialDataProvider=(e,t,s,n,r)=>{const i=Ct.get(e);if(!i)return bt.HEAPU32[t>>2]=0,bt.HEAPU32[s>>2]=0,bt.HEAPU32[n>>2]=0,void(bt.HEAPU32[r>>2]=0);bt.HEAPU32[t>>2]=i.shader,bt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Bt(i.uniforms);bt.HEAPU32[n>>2]=o,bt.HEAPU32[r>>2]=a},Rt=!0}const Dt={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 zt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Wt{constructor(e,t=""){this.cache_=new zt,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&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:At.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function Lt(e,t){Ot.set(e,t)}function Ht(e){const t=Ot.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function jt(e){return Ot.get(e)?.fields??[]}function Nt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function Xt(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function Vt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function qt(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);s&&(s.aspectRatio=t,e.insert(n,Pe,s))}}function Gt(e,t){const s=e.getEntitiesWithComponents([Ie]);for(const n of s){const s=e.get(n,Ie);if(s&&s.value===t)return n}return null}class Yt{constructor(e){this.textureCache_=new zt,this.shaderCache_=new zt,this.jsonCache_=new zt,this.textCache_=new zt,this.binaryCache_=new zt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new zt,this.prefabCache_=new zt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=u(G.textCanvasSize,G.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 Wt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,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(),At.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===x(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Xt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const 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=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return At.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return At.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Jt=Oe(null,"Assets");class Kt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new Yt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Kt;class Zt{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 es(e,t){const s=e.getResource(Jt);s&&s.registerEmbeddedAssets(t)}async function ts(e,t,s){const{entities:n,rootId:r}=await ns(t,s?.overrides??[],s,void 0,new Set),i={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}))},o=await Xt(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const ss=10;async function ns(e,t,s,n,r,i=0){if(i>ss)throw new Error(`Prefab nesting depth exceeded ${ss}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ns(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};rs(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function rs(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class is{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ts(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const os=Oe(null,"Prefabs");class as{constructor(){this.name="PrefabsPlugin",this.dependencies=[Jt]}build(e){const t=e.getResource(Jt);e.insertResource(os,new is(e.world,t))}}const cs=new as;let ls=null,hs=0,us=0,ds=0;const fs=new Float32Array(256);function ps(e){ls=e,hs=ls._malloc(64),us=ls._malloc(64),ds=ls._malloc(1024)}function _s(){ls&&(hs&&(ls._free(hs),hs=0),us&&(ls._free(us),us=0),ds&&(ls._free(ds),ds=0)),ls=null}function ms(){if(!ls)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ls}const gs={r:1,g:1,b:1,a:1},ys={begin(e){const t=ms();try{t.HEAPF32.set(e,hs/4),t.draw_begin(hs)}catch(e){mt(e,"Draw.begin")}},end(){try{ms().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,s,n=1){try{ms().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.line")}},rect(e,t,s,n=!0){try{ms().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ms().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ms().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ms().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,s,n=gs){try{ms().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,s,n,r=gs){try{ms().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){ms().draw_setLayer(e)},setDepth(e){ms().draw_setDepth(e)},getDrawCallCount:()=>ls?ls.draw_getDrawCallCount():0,getPrimitiveCount:()=>ls?ls.draw_getPrimitiveCount():0,setBlendMode(e){ms().draw_setBlendMode(e)},setDepthTest(e){ms().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ms();n.HEAPF32.set(s,us/4),n.draw_mesh(e,t,us)}catch(s){mt(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ms(),r=At.get(t);if(!r)return;if(ys.setBlendMode(r.blendMode),ys.setDepthTest(r.depthTest),0===r.uniforms.size)return void ys.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,us/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=vs(t);if(!(n<0)){if(vt(s))fs[i++]=10,fs[i++]=n,fs[i++]=s.slot??e++,fs[i++]=s.textureId;else if("number"==typeof s)fs[i++]=1,fs[i++]=n,fs[i++]=s;else if(Array.isArray(s)){fs[i++]=s.length,fs[i++]=n;for(let e=0;e<s.length;e++)fs[i++]=s[e]}else"w"in s?(fs[i++]=4,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y,fs[i++]=s.z,fs[i++]=s.w):"z"in s?(fs[i++]=3,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y,fs[i++]=s.z):(fs[i++]=2,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.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(fs.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,us);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),ds/4),n.draw_meshWithUniforms(e,r.shader,us,ds,i)}catch(s){mt(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ws={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},xs=new Set;function vs(e){const t=ws[e];return void 0!==t?t:(xs.has(e)||(xs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ws).join(", ")}`)),-1)}const bs=new Map;function Ss(e,t,s){bs.set(e,{fn:t,scene:s??""})}function Ps(e){bs.delete(e)}function Cs(){bs.clear()}var Ts;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Ts||(Ts={}));let Es=null,Ms=0,As=0,Rs=0;function Is(e){Es=e,Ms=Es._malloc(262144),As=Es._malloc(65536),Rs=Es._malloc(256)}function Fs(){Es&&(Ms&&Es._free(Ms),As&&Es._free(As),Rs&&Es._free(Rs),Ms=0,As=0,Rs=0),Es=null}function $s(){if(!Es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Es}const ks={create(e){const t=$s(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ms/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Rs,r).set(i),t.geometry_init(s,Ms,n,Rs,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices16(s,As,n)}else{new Uint32Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices32(s,As,n)}}return s},updateVertices(e,t,s=0){const n=$s(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ms/4),n.geometry_updateVertices(e,Ms,r,s)},release(e){e>0&&$s().geometry_release(e)},isValid:e=>!(!Es||e<=0)&&Es.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ks.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ks.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ks.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array(o)})}};let Bs=null;function Us(e){Bs=e}function Ds(){Bs&&Ws.isInitialized()&&Ws.shutdown(),Bs=null}function zs(){if(!Bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Bs}const Ws={init(e,t){try{return zs().postprocess_init(e,t)}catch(s){return mt(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{zs().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{zs().postprocess_resize(e,t)}catch(s){mt(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return zs().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{zs().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{zs().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return zs().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{zs().postprocess_setUniformFloat(e,t,s)}catch(s){mt(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{zs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){mt(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{zs().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{zs().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return zs().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Bs)return!1;try{return Bs.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{zs().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Bs)return!0;try{return Bs.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>At.createShader(Os,"#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:()=>At.createShader(Os,"#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:()=>At.createShader(Os,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>At.createShader(Os,"#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")},Os="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ls;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ls||(Ls={}));let Hs=null,js=0;function Ns(e){Hs=e,js=Hs._malloc(64)}function Xs(){Hs&&js&&(Hs._free(js),js=0),Hs=null}const Vs={init(e,t){Hs?.renderer_init(e,t)},resize(e,t){Hs?.renderer_resize(e,t)},begin(e,t){if(Hs&&js)try{Hs.HEAPF32.set(e,js/4),Hs.renderer_begin(js,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Hs?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Hs?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Hs)try{Hs.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Hs)try{Hs.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Hs)try{Hs.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Hs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Hs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Hs?.renderer_releaseTarget(e)},getTargetTexture:e=>Hs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Hs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Hs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Hs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Hs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Hs?Hs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Hs?{drawCalls:Hs.renderer_getDrawCalls(),triangles:Hs.renderer_getTriangles(),sprites:Hs.renderer_getSprites(),text:Hs.renderer_getText(),spine:Hs.renderer_getSpine?.()??0,meshes:Hs.renderer_getMeshes(),culled:Hs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let qs=null;function Gs(e){qs=e}function Ys(){qs=null}const Js={enable(){qs?.gl_enableErrorCheck(!0)},disable(){qs?.gl_enableErrorCheck(!1)},check:e=>qs?.gl_checkErrors(e)??0,diagnose(){qs?.renderer_diagnose()}};class Ks{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Vs.resize(n,r),Ws.isInitialized()&&Ws.getPassCount()>0&&Ws.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Vs.setViewport(0,0,n,r),Vs.clearBuffers(3),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,i),Vs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Vs.setViewport(n.x,n.y,n.w,n.h),Vs.setScissor(n.x,n.y,n.w,n.h,!0),Vs.clearBuffers(r),Vs.setScissor(0,0,0,0,!1),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,i),Vs.end()}executeDrawCallbacks(e,t){const s=bs;if(s.size>0){ys.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ys.end();for(const e of n)Ps(e)}}}const Qs="__scene_transition_overlay__";class Zs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class en{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Fe,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ss(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ws.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ws.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Fe)){const s=this.app_.world.get(e,Fe);s.persistent=t,this.app_.world.insert(e,Fe,s)}}}class tn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??G.sceneTransitionDuration,r=t.color??{...G.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ss(Qs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;ys.setLayer(9999),ys.setDepth(9999),ys.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Ps(Qs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ps(Qs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Jt)&&(t.assetServer=this.app_.getResource(Jt));const n=await Xt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=nn(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Jt)&&(t.assetServer=this.app_.getResource(Jt));const n=await Xt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=nn(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Fe)){if(this.app_.world.get(e,Fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Ps(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ws.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Se,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Se,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Ws.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const sn=Oe(null,"SceneManager");function nn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(sn).getSceneStatus(t)&&s._fn(...n)}}}const rn=tt([He(sn),Le(Xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),on={name:"SceneManager",build(e){const t=new tn(e);e.insertResource(sn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(sn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ze.Startup,s),e.addSystemToSchedule(Ze.Last,rn)}};class an{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!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.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.runSchedule(Ze.First),this.fixedAccumulator_+=s;let n=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&n<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ze.FixedPreUpdate),this.runSchedule(Ze.FixedUpdate),this.runSchedule(Ze.FixedPostUpdate),n++;n>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Ze.PreUpdate),this.runSchedule(Ze.Update),this.runSchedule(Ze.PostUpdate),this.runSchedule(Ze.Last),requestAnimationFrame(this.mainLoop)},this.world_=new yt,this.resources_=new Ne;for(const e of Object.values(Ze))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new an}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),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(Ze.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ze.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),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 _t(e),this}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(sn).register(e),this}setInitialScene(e){return this.getResource(sn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ot(this.world_,this.resources_),this.resources_.insert(Xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ze.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Cs();const e=[Ys,Xs,Ds,Fs,Et,_s];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Xe);t.delta=e,t.elapsed+=e,t.frameCount++}}function cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function hn(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case xe.FixedWidth:return i;case xe.FixedHeight:return o;case xe.Expand:return Math.max(i,o);case xe.Shrink:return Math.min(i,o);case xe.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function un(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,Fe);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===ye.Orthographic){if(d=r.orthoSize,c){d=hn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=fn(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=_n(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=gn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(wn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const dn=new Float32Array(16);function fn(e,t,s,n,r,i){const o=dn;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const pn=new Float32Array(16);function _n(e,t,s,n){const r=pn;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const mn=new Float32Array(16);function gn(e,t,s){const n=mn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const yn=new Float32Array(16);function wn(e,t){const s=yn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var xn,vn,bn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(xn||(xn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(vn||(vn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(bn||(bn={}));const Sn=ce("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:xn.Left,verticalAlign:vn.Top,wordWrap:!0,overflow:bn.Visible,lineHeight:1.2}),Pn=ce("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}});class Cn{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(G.textCanvasSize,G.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===bn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),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})`,r&&e.overflow===bn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case vn.Top:x=h;break;case vn.Middle:x=(p-w)/2;break;case vn.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case xn.Left:n=h;break;case xn.Center:n=f/2;break;case xn.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===bn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case xn.Left:return"left";case xn.Center:return"center";case xn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Tn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function En(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Mn{build(e){_e("Text",Sn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Cn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Sn));for(const e of r.keys())n.valid(e)&&n.has(e,Sn)||r.delete(e);const e=n.getEntitiesWithComponents([Sn]);for(const t of e){const e=n.get(t,Sn),i=n.has(t,Pn)?n.get(t,Pn):null,o=r.get(t);if(o&&!En(o,e,i))continue;n.has(t,Se)||n.insert(t,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Se);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Se,c),r.set(t,Tn(e,i))}}))}}const An=new Mn,Rn=ce("UIMask",{enabled:!0});function In(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function Fn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function $n(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,A=d*y-p*m,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+h*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-h*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*A-c*E+h*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function kn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function Bn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function Un(e,t,s,n,r,i,o){if(!e.has(t,Pn)||!e.has(t,be))return null;const a=e.get(t,Pn),c=e.get(t,be),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return Fn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Dn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Rn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,Rn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,Ee);){const e=t.get(n,Ee);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=Un(t,s,r,i,o,a,c);e&&(n=In(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=Un(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class zn{build(e){if(_e("UIMask",Rn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Dn(e.wasmModule,e.world))}}const Wn=new zn,On=ce("Interactable",{enabled:!0}),Ln=ce("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Hn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Hn||(Hn={}));const jn=ce("Button",{state:Hn.Normal,transition:null});class Nn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}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 Xn=Oe(new Nn,"UIEvents"),Vn=le("ScreenSpace");function qn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Gn(e,t,s,n,r,i){if(!e.has(t,Pn))return;const o=e.get(t,Pn),a=qn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,ve);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,ve,c),!e.has(t,Me))return;const l=e.get(t,Me);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Gn(e,t,a.rect,a.centerX,a.centerY,!1)}class Yn{build(e){_e("UIRect",Pn);const t=e.world;e.addSystemToSchedule(Ze.PreUpdate,tt([Le(wt)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Vn,Pn,ve]);for(const e of i)Gn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Jn=new Yn,Kn=new Float32Array(16),Qn=new Float32Array(16);let Zn=!0,er=1;class tr{build(e){_e("Interactable",On),_e("Button",jn);const t=e.world,s=new Nn;e.insertResource(Xn,s);let n=null,r=null;er="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ze.PreUpdate,tt([Le(ct),Le(wt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Ln]);for(const e of o){const s=t.get(e,Ln);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*er,c=i.screenH-e.mouseY*er;!function(e){let t=!1;for(let s=0;s<16;s++)if(Qn[s]!==e[s]){t=!0;break}t&&(Qn.set(e),Zn=!0)}(i.viewProjection),Zn&&($n(i.viewProjection,Kn),Zn=!1);const l=kn(a,c,Kn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([On,Pn,be]);let u=null,d=-1/0;for(const e of h){t.has(e,Ln)||t.insert(e,Ln);if(!t.get(e,On).enabled)continue;const s=t.get(e,be),n=t.get(e,Pn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(Bn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Se)&&(s=t.get(e,Se).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,Ln)){t.get(n,Ln).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,Ln).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,Ln);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ln)){const e=t.get(r,Ln);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ze.Update,tt([],()=>{const e=t.getEntitiesWithComponents([jn]);for(const s of e){if(t.has(s,On)||t.insert(s,On,{enabled:!0}),!t.has(s,Ln))continue;const e=t.get(s,Ln),n=t.get(s,jn),r=t.get(s,On),i=n.state;if(r.enabled?e.pressed?n.state=Hn.Pressed:e.hovered?n.state=Hn.Hovered:n.state=Hn.Normal:n.state=Hn.Disabled,i!==n.state&&n.transition&&t.has(s,Se)){const e=t.get(s,Se),r=n.transition;switch(n.state){case Hn.Normal:e.color={...r.normalColor};break;case Hn.Hovered:e.color={...r.hoveredColor};break;case Hn.Pressed:e.color={...r.pressedColor};break;case Hn.Disabled:e.color={...r.disabledColor}}t.insert(s,Se,e)}}},{name:"ButtonSystem"}))}}const sr=new tr,nr=ce("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});class rr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){_e("TextInput",nr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(G.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||w()},_=()=>{a=!0},m=()=>{a=!1,w()},g=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,nr);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Xn).emit(o,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==o&&s.valid(o)&&s.has(o,nr)){const e=s.get(o,nr);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,nr);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Xn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=s.get(e,nr);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==o&&s.valid(o)&&s.has(o,nr)){const e=s.get(o,nr);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){c=!0,l=0}function S(e,o,a,l){(r.width<a||r.height<l)&&(r.width=or(Math.max(r.width,a)),r.height=or(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=ir(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=ir(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Se);b.texture=v,b.size.x=a,b.size.y=l,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,Se,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ze.PreUpdate,tt([Le(Xn)],e=>{const t=s.getEntitiesWithComponents([nr,On]);for(const e of t){if(!s.has(e,Ln))continue;if(s.get(e,Ln).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([On]);for(const t of e){if(s.has(t,nr))continue;if(!s.has(t,Ln))continue;if(s.get(t,Ln).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,nr)))){s.get(o,nr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,nr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([nr,Pn]);for(const e of a){const t=s.get(e,nr);if(!t.dirty)continue;const n=s.get(e,Pn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Se)||s.insert(e,Se,{texture:K,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}),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function ir(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function or(e){let t=1;for(;t<e;)t*=2;return t}const ar=new rr;async function cr(e,t,s){const n=e.getResource(sn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function lr(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 hr=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ur=Oe(null,"PhysicsAPI");function dr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function fr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class pr{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(hr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=lr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Ce]);for(const s of t){const t=e.world.get(s,Ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ze.PostUpdate,tt([Le(Xe)],a=>{const c=o.getEntitiesWithComponents([ke,ve,be]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,ke),c=o.get(r,be);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=dr(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),_r(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=dr(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,ve);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,Ee)){const t=e.world.get(o,Ee);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,be)){const s=e.world.get(t.entity,be),n=dr(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=fr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,ve,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],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;i.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=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(hr,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ur,mr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function _r(e,t,s){const n=e.world;if(n.has(s,Be)){const e=n.get(s,Be);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,Ue)){const e=n.get(s,Ue);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,De)){const e=n.get(s,De);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 mr{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(mr.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)}}function gr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function yr(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 wr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function xr(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=gr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===x(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=yr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=gr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new pr("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=gr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=At.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=At.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=jt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=Nt(e.world,s);if(c&&e.hasResource(sn))for(const t of p.values())e.world.insert(t,Fe,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Re)?l.get(i,Re):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,be)){const e=wr(l.get(i,be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Jt);t&&t.setAddressableManifest(a)}}function vr(e,t,s){return{name:e,data:t,async setup(){await xr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class br{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===x(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=x(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)||i.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{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Sr="__preview__";class Pr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(sn);t.register({name:Sr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Sr),this.loadPromise_=t.load(Sr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new br(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await xr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,Sr)}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([Ce]);for(const r of n){const n=e.get(r,Ce);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(sn).getScene(Sr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,ve,o);const a={isActive:!0,projectionType:ye.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:we.ColorAndDepth};e.insert(i,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(sn);await e.switchTo(Sr),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 Cr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Vs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Vs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Vs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Vs.releaseRenderTarget(e._handle),Cr.create({width:t,height:s,depth:!0})),begin(e,t){Vs.begin(t,e._handle)},end(){Vs.end()},getDepthTexture:e=>Vs.getTargetDepthTexture(e._handle)};let Tr=!1;function Er(e){Tr=e}function Mr(){return Tr}function Ar(){return!Tr}var Rr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Rr||(Rr={}));class Ir{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Rr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Rr.Debug:console.debug(t,s);break;case Rr.Info:console.log(t,s);break;case Rr.Warn:console.warn(t,s);break;case Rr.Error:console.error(t,s)}}}class Fr{constructor(){this.handlers_=[],this.minLevel_=Rr.Info,this.addHandler(new Ir)}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(Rr.Debug,e,t,s)}info(e,t,s){this.log(Rr.Info,e,t,s)}warn(e,t,s){this.log(Rr.Warn,e,t,s)}error(e,t,s){this.log(Rr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const $r=new Fr;function kr(){return $r}function Br(e){$r.setMinLevel(e)}function Ur(e,t,s){$r.debug(e,t,s)}function Dr(e,t,s){$r.info(e,t,s)}function zr(e,t,s){$r.warn(e,t,s)}function Wr(e,t,s){$r.error(e,t,s)}const Or=[An,Wn,Jn,sr,ar];function Lr(e,t){return function(e,t){const s=an.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ps(e),Tt(e),Is(e),Us(e),Ns(e),Gs(e);const r=new Ks;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=un(e,n,t,r));const o=s.getResource(wt);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(wt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Vs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Vs.resize(t,c),Ws.isInitialized()&&Ws.getPassCount()>0&&!Ws.isBypassed()&&Ws.resize(t,c),s.hasResource(sn)){const e=s.getResource(sn).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=un(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:ln,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Vs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ze.First,c),s.addSystemToSchedule(Ze.Last,l),s.addPlugin(Qt),s.addPlugin(cs),s.addPlugin(ht),s.addPlugin(on),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Or,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{an as App,Kt as AssetPlugin,Zt as AssetRefCounter,Yt as AssetServer,Jt as Assets,zt as AsyncCache,Ae as BitmapText,xt as BlendMode,ze as BodyType,Be as BoxCollider,jn as Button,Hn as ButtonState,Pe as Camera,Ce as Canvas,De as CapsuleCollider,Me as Children,Ue as CircleCollider,we as ClearFlags,Je as Commands,Qe as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,Ts as DataType,ys as Draw,Ke as EntityCommands,Js as GLDebug,ks as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,ct as Input,lt as InputPlugin,at as InputState,On as Interactable,ve as LocalTransform,Rr as LogLevel,Fr as Logger,At as Material,Wt as MaterialLoader,Ve as Mut,Ie as Name,Ee as Parent,mr as Physics,hr as PhysicsEvents,pr as PhysicsPlugin,Ws as PostProcess,is as PrefabServer,os as Prefabs,as as PrefabsPlugin,Pr as PreviewPlugin,ye as ProjectionType,Ge as Query,Ye as QueryInstance,Ks as RenderPipeline,Ls as RenderStage,Cr as RenderTexture,Vs as Renderer,Le as Res,He as ResMut,ke as RigidBody,G as RuntimeConfig,xe as ScaleMode,sn as SceneManager,tn as SceneManagerState,Fe as SceneOwner,Ze as Schedule,Vn as ScreenSpace,Dt as ShaderSources,Re as SpineAnimation,Se as Sprite,ot as SystemRunner,Sn as Text,xn as TextAlign,nr as TextInput,rr as TextInputPlugin,bn as TextOverflow,Mn as TextPlugin,Cn as TextRenderer,vn as TextVerticalAlign,Xe as Time,wt as UICameraInfo,Nn as UIEventQueue,Xn as UIEvents,Ln as UIInteraction,tr as UIInteractionPlugin,Yn as UILayoutPlugin,Rn as UIMask,zn as UIMaskPlugin,Pn as UIRect,Te as Velocity,br as WebAssetProvider,yt as World,be as WorldTransform,rt as addStartupSystem,nt as addSystem,it as addSystemToSchedule,Y as applyRuntimeConfig,Qt as assetPlugin,Cs as clearDrawCallbacks,ue as clearUserComponents,se as color,qn as computeUIRectLayout,Dn as createMaskProcessor,vr as createRuntimeSceneConfig,Lr as createWebApp,Ur as debug,ce as defineComponent,Oe as defineResource,tt as defineSystem,le as defineTag,Wr as error,Gt as findEntityByName,cn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,Ht as getComponentAssetFields,$e as getComponentDefaults,E as getCustomExtensions,v as getEditorType,kr as getLogger,t as getPlatform,n as getPlatformType,he as getUserComponent,M as getWeChatPackOptions,Dr as info,ps as initDrawAPI,Gs as initGLDebugAPI,Is as initGeometryAPI,Tt as initMaterialAPI,Us as initPostProcessAPI,Ns as initRendererAPI,ht as inputPlugin,ts as instantiatePrefab,In as intersectRects,$n as invertMatrix4,fe as isBuiltinComponent,R as isCustomExtension,Mr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Ar as isRuntime,vt as isTextureRef,r as isWeChat,i as isWeb,Vt as loadComponent,lr as loadPhysicsModule,xr as loadRuntimeScene,Nt as loadSceneData,Xt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,Bn as pointInWorldRect,cs as prefabsPlugin,ne as quat,_e as registerComponent,Lt as registerComponentAssetFields,Ss as registerDrawCallback,es as registerEmbeddedAssets,Ut as registerMaterialCallback,on as sceneManagerPlugin,kn as screenToWorld,Er as setEditorMode,Br as setLogLevel,_t as setWasmErrorHandler,_s as shutdownDrawAPI,Ys as shutdownGLDebugAPI,Fs as shutdownGeometryAPI,Et as shutdownMaterialAPI,Ds as shutdownPostProcessAPI,Xs as shutdownRendererAPI,ar as textInputPlugin,An as textPlugin,cr as transitionTo,sr as uiInteractionPlugin,Jn as uiLayoutPlugin,Wn as uiMaskPlugin,Or as uiPlugins,Ps as unregisterDrawCallback,qt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,zr as warn,Fn as worldRectToScreen,nn as wrapSceneSystem,U as wxFileExists,D as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,L as wxLoadImagePixels,k as wxReadFile,B as wxReadTextFile,z 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 s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}function f(e,t){return new Promise((s,n)=>{const r=t?.responseType??"text";wx.request({url:e,method:t?.method??"GET",data:t?.body,header:t?.headers,responseType:"arraybuffer"===r?"arraybuffer":"text",timeout:t?.timeout,success:e=>{const t=e.statusCode>=200&&e.statusCode<300,n={};if(e.header)for(const t of Object.keys(e.header))n[t.toLowerCase()]=e.header[t];s({ok:t,status:e.statusCode,statusText:t?"OK":"Error",headers:n,json:()=>"string"==typeof e.data?Promise.resolve(JSON.parse(e.data)):Promise.resolve(e.data),text:()=>"string"==typeof e.data?Promise.resolve(e.data):Promise.resolve(JSON.stringify(e.data)),arrayBuffer:()=>{if(e.data instanceof ArrayBuffer)return Promise.resolve(e.data);const t=new TextEncoder,s="string"==typeof e.data?e.data:JSON.stringify(e.data);return Promise.resolve(t.encode(s).buffer)}})},fail:e=>{n(new Error(`wx.request failed: ${e.errMsg}`))}})})}async function p(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 _=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],m={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},g=new Map,y=new Set;for(const e of _)for(const t of e.extensions)g.set(t,e),y.add(t);function w(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function x(e){return g.get(w(e))}function v(e){return x(e)?.editorType??"unknown"}function b(e){return x(e)?.addressableType??null}function S(e){for(const t of _)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function P(e){return y.has(e.toLowerCase())}function C(){return y}function T(e){return"string"==typeof e&&(!!e.includes("/")&&P(w(e)))}function E(){const e=[];for(const t of _)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function M(){return E().map(e=>({type:"suffix",value:e}))}function A(e){return m[e.toLowerCase()]}function R(e){const t=x(e);return t?.wechatPackInclude??!1}let I=null;function F(){return I||(I=wx.getFileSystemManager()),I}function $(e,t){const s=t.toLowerCase();if(s.includes("permission denied")){if(R(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 k(e){return new Promise((t,s)=>{F().readFile({filePath:e,success:e=>{t(e.data)},fail:t=>{s(new Error($(e,t.errMsg)))}})})}function B(e,t="utf-8"){return new Promise((s,n)=>{F().readFile({filePath:e,encoding:t,success:e=>{s(e.data)},fail:t=>{n(new Error($(e,t.errMsg)))}})})}function U(e){return new Promise(t=>{F().access({path:e,success:()=>t(!0),fail:()=>t(!1)})})}function D(e){const t=F();try{return t.accessSync(e),!0}catch{return!1}}function z(e,t){return new Promise((s,n)=>{F().writeFile({filePath:e,data:t,success:()=>s(),fail:t=>{n(new Error(`Failed to write file "${e}": ${t.errMsg}`))}})})}function W(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 O(e){const{width:t,height:s}=e,{ctx:n}=function(e,t){const s=wx.createCanvas();s.width=e,s.height=t;const n=s.getContext("2d");return{canvas:s,ctx:n}}(t,s);n.clearRect(0,0,t,s),n.drawImage(e,0,0);const r=n.getImageData(0,0,t,s);return{width:t,height:s,pixels:new Uint8Array(r.data.buffer)}}async function L(e){return O(await W(e))}let H=!1;const j=new class{constructor(){this.name="wechat"}async fetch(e,t){return f(e,t)}async readFile(e){return k(e)}async readTextFile(e){return B(e)}async fileExists(e){return U(e)}async instantiateWasm(e,t){if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer");return p(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){const{pixelRatio:s}=wx.getSystemInfoSync();wx.onTouchStart(t=>{for(const n of t.touches)e.onPointerDown(n.identifier,n.clientX*s,n.clientY*s)}),wx.onTouchMove(t=>{const n=t.touches[0];n&&e.onPointerMove(n.clientX*s,n.clientY*s)}),wx.onTouchEnd(t=>{for(const s of t.changedTouches)e.onPointerUp(s.identifier)})}},N=1920,X=1080,V=100,q=512,G={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function Y(e){e.Text&&(e.Text._default.fontFamily=G.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=G.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=G.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=G.canvasMatchWidthOrHeight)}const J=0,K=4294967295,Q=4294967295,Z=(e=0,t=0)=>({x:e,y:t}),ee=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),te=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),se=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),ne=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function re(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(re);const t={};for(const s in e)t[s]=re(e[s]);return t}let ie=0;function oe(e,t){const s=++ie;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...re(t),...e}:re(t)}}function ae(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function ce(e,t){const s=ae(),n=s.get(e);if(n)return n;const r=oe(e,t);return s.set(e,r),de(e,t,!1),r}function le(e){const t=ae(),s=t.get(e);if(s)return s;const n=oe(e,{});return t.set(e,n),de(e,{},!0),n}function he(e){return ae().get(e)}function ue(){ae().clear()}function de(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function fe(e){return!0===e._builtin}const pe=new Map;function _e(e,t){pe.set(e,t)}function me(e){return pe.get(e)??he(e)}function ge(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return pe.set(e,s),s}const ye={Perspective:0,Orthographic:1},we={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},xe={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},ve=ge("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),be=ge("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Se=ge("Sprite",{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),Pe=ge("Camera",{projectionType:ye.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:we.ColorAndDepth}),Ce=ge("Canvas",{designResolution:{x:N,y:X},pixelsPerUnit:100,scaleMode:xe.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),Te=ge("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),Ee=ge("Parent",{entity:0}),Me=ge("Children",{entities:[]}),Ae=ge("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:Q}),Re=ge("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}),Ie={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},Fe=ce("SceneOwner",{scene:"",persistent:!1});function $e(e){const t=me(e);return t?re(t._default):null}_e("Name",Ie);const ke=ge("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),Be=ge("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),Ue=ge("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),De=ge("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ze={Static:0,Kinematic:1,Dynamic:2};let We=0;function Oe(e,t){const s=++We;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function Le(e){return{_type:"res",_resource:e}}function He(e){return{_type:"res_mut",_resource:e}}class je{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 Ne{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 je(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const Xe=Oe({delta:0,elapsed:0,frameCount:0},"Time");function Ve(e){return{_type:"mut",_component:e}}function qe(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function Ge(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{qe(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class Ye{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>qe(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,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(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function Je(){return{_type:"commands"}}class Ke{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=fe(e)?{...e._default,...t}:e.create(t),this.isNew_?this.components_.push({component:e,data:s}):this.commands_.queueInsert(this.entityRef_.entity,e,s),this}remove(e){return this.isNew_||this.commands_.queueRemove(this.entityRef_.entity,e),this}id(){return this.isNew_&&0===this.entityRef_.entity&&this.finalize(),this.entityRef_.entity}finalize(){this.isNew_&&(this.commands_.spawnImmediate(this.components_,this.entityRef_),this.isNew_=!1)}}class Qe{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new Ke(this,null);return this.spawned_.push(e),e}entity(e){return new Ke(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Ze;!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"}(Ze||(Ze={}));let et=0;function tt(e,t,s){const n=++et;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function st(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function nt(e){st().push({schedule:Ze.Update,system:e})}function rt(e){st().push({schedule:Ze.Startup,system:e})}function it(e,t){st().push({schedule:e,system:t})}class ot{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof Qe&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new Ye(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new Qe(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class at{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 ct=Oe(new at,"Input");class lt{constructor(e){this.target_=e??null}build(e){const s=new at;e.insertResource(ct,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(Ze.Last,tt([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ht=new lt;function ut(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=dt(t[e]),i=dt(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function dt(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function ft(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 pt=null;function _t(e){pt=e}function mt(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),pt&&pt(e,t)}function gt(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:gt(e)}}return t}class yt{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==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 mt(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){mt(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.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){mt(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){mt(t,`removeParent(entity=${e})`)}}insert(e,t,s){return fe(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return fe(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return fe(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(fe(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return mt(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.");fe(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_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=ut(t._name,t._default,n);if(e.length>0)throw new Error(ft(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,gt(r))}catch(s){mt(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return mt(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 mt(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){mt(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=ut(t._name,t._default,e);if(r.length>0)throw new Error(ft(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.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,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_)for(const[s,n]of pe)if(fe(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!fe(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const wt=Oe({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var xt;function vt(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"}(xt||(xt={}));let bt=null,St=null,Pt=1;const Ct=new Map;function Tt(e){bt=e,St=e.getResourceManager(),Ut()}function Et(){0!==It&&bt&&(bt._free(It),It=0),Ct.clear(),Pt=1,Rt=!1,$t.clear(),kt=null,St=null,bt=null}function Mt(){if(!St)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return St}const At={createShader:(e,t)=>Mt().createShader(e,t),releaseShader(e){e>0&&Mt().releaseShader(e)},create(e){const t=Pt++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??xt.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 Ct.set(t,s),t},get:e=>Ct.get(e),setUniform(e,t,s){const n=Ct.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ct.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ct.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ct.get(e);return t?.blendMode??xt.Normal},setDepthTest(e,t){const s=Ct.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ct.get(e);return t?.shader??0},release(e){Ct.delete(e)},isValid:e=>Ct.has(e),releaseAll(){Ct.clear()},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??xt.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ct.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=Pt++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ct.set(s,n),s},toAssetData(e,t){const s=Ct.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=Ct.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let Rt=!1,It=0;const Ft=4096,$t=new Map;let kt=null;function Bt(e){const t=(0===It&&bt&&(It=bt._malloc(Ft)),It);if(0===t||!bt)return{ptr:0,count:0};let s=0,n=0;const r=bt.HEAPU8,i=bt.HEAPU32,o=bt.HEAPF32;for(const[a,c]of e){if(s+128>Ft)break;let e=$t.get(a);e||(kt||(kt=new TextEncoder),e=kt.encode(a),$t.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=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 e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}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]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function Ut(){if(!bt||Rt)return;bt.materialDataProvider=(e,t,s,n,r)=>{const i=Ct.get(e);if(!i)return bt.HEAPU32[t>>2]=0,bt.HEAPU32[s>>2]=0,bt.HEAPU32[n>>2]=0,void(bt.HEAPU32[r>>2]=0);bt.HEAPU32[t>>2]=i.shader,bt.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=Bt(i.uniforms);bt.HEAPU32[n>>2]=o,bt.HEAPU32[r>>2]=a},Rt=!0}const Dt={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 zt{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class Wt{constructor(e,t=""){this.cache_=new zt,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&&(At.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())At.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:At.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const Ot=new Map([["Sprite",{fields:[{field:"texture",type:"texture"},{field:"material",type:"material"}]}],["SpineAnimation",{spine:{skeletonField:"skeletonPath",atlasField:"atlasPath"},fields:[{field:"material",type:"material"}]}],["BitmapText",{fields:[{field:"font",type:"font"}]}]]);function Lt(e,t){Ot.set(e,t)}function Ht(e){const t=Ot.get(e);if(!t)return[];const s=[];if(t.fields)for(const{field:e}of t.fields)s.push(e);return t.spine&&(s.push(t.spine.skeletonField),s.push(t.spine.atlasField)),s}function jt(e){return Ot.get(e)?.fields??[]}function Nt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,Ie,{value:n.name}),!1!==n.visible)for(const s of n.components)Vt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function Xt(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t)continue;const s=e.data;if(t.spine){const e=s[t.spine.skeletonField],n=s[t.spine.atlasField];if(e&&n){const t=`${e}:${n}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=Ot.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,Ie,{value:s.name}),!1!==s.visible)for(const n of s.components)Vt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function Vt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=me(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function qt(e,t){const s=e.getEntitiesWithComponents([Pe]);for(const n of s){const s=e.get(n,Pe);s&&(s.aspectRatio=t,e.insert(n,Pe,s))}}function Gt(e,t){const s=e.getEntitiesWithComponents([Ie]);for(const n of s){const s=e.get(n,Ie);if(s&&s.value===t)return n}return null}class Yt{constructor(e){this.textureCache_=new zt,this.shaderCache_=new zt,this.jsonCache_=new zt,this.textCache_=new zt,this.binaryCache_=new zt,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new zt,this.prefabCache_=new zt,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=u(G.textCanvasSize,G.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 Wt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,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(),At.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===x(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=x(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return Xt(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const 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=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return At.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return At.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Jt=Oe(null,"Assets");class Kt{build(e){const t=e.wasmModule;t?e.insertResource(Jt,new Yt(t)):console.warn("AssetPlugin: No WASM module available")}}const Qt=new Kt;class Zt{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 es(e,t){const s=e.getResource(Jt);s&&s.registerEmbeddedAssets(t)}async function ts(e,t,s){const{entities:n,rootId:r}=await ns(t,s?.overrides??[],s,void 0,new Set),i={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}))},o=await Xt(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const ss=10;async function ns(e,t,s,n,r,i=0){if(i>ss)throw new Error(`Prefab nesting depth exceeded ${ss}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await ns(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};rs(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function rs(e,t){for(const s of t)if(s.prefabEntityId===e.prefabEntityId)switch(s.type){case"property":if(s.componentType&&void 0!==s.propertyName){const t=e.components.find(e=>e.type===s.componentType);t&&(t.data[s.propertyName]=s.value)}break;case"name":"string"==typeof s.value&&(e.name=s.value);break;case"visibility":"boolean"==typeof s.value&&(e.visible=s.value);break;case"component_added":if(s.componentData){e.components.some(e=>e.type===s.componentData.type)||e.components.push({type:s.componentData.type,data:JSON.parse(JSON.stringify(s.componentData.data))})}break;case"component_removed":s.componentType&&(e.components=e.components.filter(e=>e.type!==s.componentType))}}class is{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return ts(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const os=Oe(null,"Prefabs");class as{constructor(){this.name="PrefabsPlugin",this.dependencies=[Jt]}build(e){const t=e.getResource(Jt);e.insertResource(os,new is(e.world,t))}}const cs=new as;let ls=null,hs=0,us=0,ds=0;const fs=new Float32Array(256);function ps(e){ls=e,hs=ls._malloc(64),us=ls._malloc(64),ds=ls._malloc(1024)}function _s(){ls&&(hs&&(ls._free(hs),hs=0),us&&(ls._free(us),us=0),ds&&(ls._free(ds),ds=0)),ls=null}function ms(){if(!ls)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return ls}const gs={r:1,g:1,b:1,a:1},ys={begin(e){const t=ms();try{t.HEAPF32.set(e,hs/4),t.draw_begin(hs)}catch(e){mt(e,"Draw.begin")}},end(){try{ms().draw_end()}catch(e){mt(e,"Draw.end")}},line(e,t,s,n=1){try{ms().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.line")}},rect(e,t,s,n=!0){try{ms().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ms().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){mt(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ms().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){mt(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ms().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){mt(e,"Draw.circleOutline")}},texture(e,t,s,n=gs){try{ms().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){mt(e,"Draw.texture")}},textureRotated(e,t,s,n,r=gs){try{ms().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){mt(e,"Draw.textureRotated")}},setLayer(e){ms().draw_setLayer(e)},setDepth(e){ms().draw_setDepth(e)},getDrawCallCount:()=>ls?ls.draw_getDrawCallCount():0,getPrimitiveCount:()=>ls?ls.draw_getPrimitiveCount():0,setBlendMode(e){ms().draw_setBlendMode(e)},setDepthTest(e){ms().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ms();n.HEAPF32.set(s,us/4),n.draw_mesh(e,t,us)}catch(s){mt(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ms(),r=At.get(t);if(!r)return;if(ys.setBlendMode(r.blendMode),ys.setDepthTest(r.depthTest),0===r.uniforms.size)return void ys.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,us/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=vs(t);if(!(n<0)){if(vt(s))fs[i++]=10,fs[i++]=n,fs[i++]=s.slot??e++,fs[i++]=s.textureId;else if("number"==typeof s)fs[i++]=1,fs[i++]=n,fs[i++]=s;else if(Array.isArray(s)){fs[i++]=s.length,fs[i++]=n;for(let e=0;e<s.length;e++)fs[i++]=s[e]}else"w"in s?(fs[i++]=4,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y,fs[i++]=s.z,fs[i++]=s.w):"z"in s?(fs[i++]=3,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.y,fs[i++]=s.z):(fs[i++]=2,fs[i++]=n,fs[i++]=s.x,fs[i++]=s.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(fs.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,us);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),ds/4),n.draw_meshWithUniforms(e,r.shader,us,ds,i)}catch(s){mt(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},ws={u_time:0,u_color:1,u_intensity:2,u_scale:3,u_offset:4,u_param0:5,u_param1:6,u_param2:7,u_param3:8,u_param4:9,u_vec0:10,u_vec1:11,u_vec2:12,u_vec3:13,u_texture0:14,u_texture1:15,u_texture2:16,u_texture3:17},xs=new Set;function vs(e){const t=ws[e];return void 0!==t?t:(xs.has(e)||(xs.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(ws).join(", ")}`)),-1)}const bs=new Map;function Ss(e,t,s){bs.set(e,{fn:t,scene:s??""})}function Ps(e){bs.delete(e)}function Cs(){bs.clear()}var Ts;!function(e){e[e.Float=1]="Float",e[e.Float2=2]="Float2",e[e.Float3=3]="Float3",e[e.Float4=4]="Float4",e[e.Int=5]="Int",e[e.Int2=6]="Int2",e[e.Int3=7]="Int3",e[e.Int4=8]="Int4"}(Ts||(Ts={}));let Es=null,Ms=0,As=0,Rs=0;function Is(e){Es=e,Ms=Es._malloc(262144),As=Es._malloc(65536),Rs=Es._malloc(256)}function Fs(){Es&&(Ms&&Es._free(Ms),As&&Es._free(As),Rs&&Es._free(Rs),Ms=0,As=0,Rs=0),Es=null}function $s(){if(!Es)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return Es}const ks={create(e){const t=$s(),s=t.geometry_create();if(0===s)throw new Error("Failed to create geometry");const n=e.vertices.length;if(4*n>262144)throw new Error(`Vertex data too large: ${n} floats (max 65536)`);t.HEAPF32.set(e.vertices,Ms/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,Rs,r).set(i),t.geometry_init(s,Ms,n,Rs,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices16(s,As,n)}else{new Uint32Array(t.HEAPU8.buffer,As,n).set(e.indices),t.geometry_setIndices32(s,As,n)}}return s},updateVertices(e,t,s=0){const n=$s(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,Ms/4),n.geometry_updateVertices(e,Ms,r,s)},release(e){e>0&&$s().geometry_release(e)},isValid:e=>!(!Es||e<=0)&&Es.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return ks.create({vertices:new Float32Array([-s,-n,0,0,s,-n,1,0,s,n,1,1,-s,n,0,1]),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return ks.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return ks.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:Ts.Float2},{name:"a_texCoord",type:Ts.Float2}],indices:new Uint16Array(o)})}};let Bs=null;function Us(e){Bs=e}function Ds(){Bs&&Ws.isInitialized()&&Ws.shutdown(),Bs=null}function zs(){if(!Bs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return Bs}const Ws={init(e,t){try{return zs().postprocess_init(e,t)}catch(s){return mt(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{zs().postprocess_shutdown()}catch(e){mt(e,"PostProcess.shutdown")}},resize(e,t){try{zs().postprocess_resize(e,t)}catch(s){mt(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return zs().postprocess_addPass(e,t)}catch(t){return mt(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{zs().postprocess_removePass(e)}catch(t){mt(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{zs().postprocess_setPassEnabled(e,t)}catch(t){mt(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return zs().postprocess_isPassEnabled(e)}catch(t){return mt(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{zs().postprocess_setUniformFloat(e,t,s)}catch(s){mt(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{zs().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){mt(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{zs().postprocess_begin()}catch(e){mt(e,"PostProcess.begin")}},end(){try{zs().postprocess_end()}catch(e){mt(e,"PostProcess.end")}},getPassCount(){try{return zs().postprocess_getPassCount()}catch(e){return mt(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!Bs)return!1;try{return Bs.postprocess_isInitialized()}catch(e){return mt(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{zs().postprocess_setBypass(e)}catch(e){mt(e,"PostProcess.setBypass")}},isBypassed(){if(!Bs)return!0;try{return Bs.postprocess_isBypassed()}catch(e){return mt(e,"PostProcess.isBypassed"),!0}},createBlur:()=>At.createShader(Os,"#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:()=>At.createShader(Os,"#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:()=>At.createShader(Os,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>At.createShader(Os,"#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")},Os="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Ls;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Ls||(Ls={}));let Hs=null,js=0;function Ns(e){Hs=e,js=Hs._malloc(64)}function Xs(){Hs&&js&&(Hs._free(js),js=0),Hs=null}const Vs={init(e,t){Hs?.renderer_init(e,t)},resize(e,t){Hs?.renderer_resize(e,t)},begin(e,t){if(Hs&&js)try{Hs.HEAPF32.set(e,js/4),Hs.renderer_begin(js,t??0)}catch(e){mt(e,"Renderer.begin")}},flush(){try{Hs?.renderer_flush()}catch(e){mt(e,"Renderer.flush")}},end(){try{Hs?.renderer_end()}catch(e){mt(e,"Renderer.end")}},submitSprites(e){if(Hs)try{Hs.renderer_submitSprites(e._cpp)}catch(e){mt(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Hs)try{Hs.renderer_submitBitmapText(e._cpp)}catch(e){mt(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Hs)try{Hs.renderer_submitSpine?.(e._cpp)}catch(e){mt(e,"Renderer.submitSpine")}},setStage(e){Hs?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Hs?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Hs?.renderer_releaseTarget(e)},getTargetTexture:e=>Hs?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Hs?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Hs?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Hs?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Hs?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Hs?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Hs?Hs.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Hs?{drawCalls:Hs.renderer_getDrawCalls(),triangles:Hs.renderer_getTriangles(),sprites:Hs.renderer_getSprites(),text:Hs.renderer_getText(),spine:Hs.renderer_getSpine?.()??0,meshes:Hs.renderer_getMeshes(),culled:Hs.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let qs=null;function Gs(e){qs=e}function Ys(){qs=null}const Js={enable(){qs?.gl_enableErrorCheck(!0)},disable(){qs?.gl_enableErrorCheck(!1)},check:e=>qs?.gl_checkErrors(e)??0,diagnose(){qs?.renderer_diagnose()}};class Ks{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Vs.resize(n,r),Ws.isInitialized()&&Ws.getPassCount()>0&&Ws.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Vs.setViewport(0,0,n,r),Vs.clearBuffers(3),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,i),Vs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Vs.setViewport(n.x,n.y,n.w,n.h),Vs.setScissor(n.x,n.y,n.w,n.h,!0),Vs.clearBuffers(r),Vs.setScissor(0,0,0,0,!1),Vs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Vs.submitSprites(t),Vs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Vs.submitSpine(t),Vs.flush(),this.executeDrawCallbacks(s,i),Vs.end()}executeDrawCallbacks(e,t){const s=bs;if(s.size>0){ys.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}ys.end();for(const e of n)Ps(e)}}}const Qs="__scene_transition_overlay__";class Zs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class en{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,Fe,{scene:this.instance_.config.name,persistent:!1}),e}despawn(e){this.instance_.entities.delete(e),this.app_.world.despawn(e)}registerDrawCallback(e,t){this.instance_.drawCallbacks.set(e,t),Ss(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Ws.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Ws.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,Fe)){const s=this.app_.world.get(e,Fe);s.persistent=t,this.app_.world.insert(e,Fe,s)}}}class tn{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??G.sceneTransitionDuration,r=t.color??{...G.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},Ss(Qs,()=>{if(!this.transition_)return;const e=this.transition_.duration/2,t=Math.min(this.transition_.elapsed/e,1),s="fade-out"===this.transition_.phase?t:1-t;ys.setLayer(9999),ys.setDepth(9999),ys.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,Ps(Qs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,Ps(Qs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Jt)&&(t.assetServer=this.app_.getResource(Jt));const n=await Xt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=nn(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Zs(t);this.scenes_.set(e,s);const n=new en(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Jt)?this.app_.getResource(Jt):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Jt)&&(t.assetServer=this.app_.getResource(Jt));const n=await Xt(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,Fe,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=nn(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,Fe)){if(this.app_.world.get(e,Fe).persistent)continue}this.app_.world.valid(e)&&this.app_.world.despawn(e)}s.entities.clear();for(const e of s.drawCallbacks.keys())Ps(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Ws.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Se,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Se)){const s=this.app_.world.get(e,Se),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Se,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Ws.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const sn=Oe(null,"SceneManager");function nn(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(sn).getSceneStatus(t)&&s._fn(...n)}}}const rn=tt([He(sn),Le(Xe)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),on={name:"SceneManager",build(e){const t=new tn(e);e.insertResource(sn,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(sn),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Ze.Startup,s),e.addSystemToSchedule(Ze.Last,rn)}};class an{constructor(){this.systems_=new Map,this.runner_=null,this.running_=!1,this.lastTime_=0,this.fixedTimestep_=1/60,this.fixedAccumulator_=0,this.maxDeltaTime_=.25,this.maxFixedSteps_=8,this.module_=null,this.pipeline_=null,this.installed_plugins_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Ze.Last);else{this.runSchedule(Ze.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Ze.FixedPreUpdate),this.runSchedule(Ze.FixedUpdate),this.runSchedule(Ze.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Ze.PreUpdate),this.runSchedule(Ze.Update),this.runSchedule(Ze.PostUpdate),this.runSchedule(Ze.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new yt,this.resources_=new Ne;for(const e of Object.values(Ze))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new an}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),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(Ze.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Ze.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),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 _t(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(sn).register(e),this}setInitialScene(e){return this.getResource(sn).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new ot(this.world_,this.resources_),this.resources_.insert(Xe,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Ze.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,Cs();const e=[Ys,Xs,Ds,Fs,Et,_s];for(const t of e)try{t()}catch(e){console.error("[ESEngine] Shutdown error:",e)}for(const e of this.world_.getAllEntities())try{this.world_.despawn(e)}catch(e){}this.world_.disconnectCpp(),this.pipeline_=null,this.runner_=null,this.module_=null}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(Xe);t.delta=e,t.elapsed+=e,t.frameCount++}}function cn(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const ln=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function hn(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case xe.FixedWidth:return i;case xe.FixedHeight:return o;case xe.Expand:return Math.max(i,o);case xe.Shrink:return Math.min(i,o);case xe.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function un(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,Fe);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===ye.Orthographic){if(d=r.orthoSize,c){d=hn(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=fn(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=_n(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=gn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(wn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const dn=new Float32Array(16);function fn(e,t,s,n,r,i){const o=dn;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const pn=new Float32Array(16);function _n(e,t,s,n){const r=pn;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const mn=new Float32Array(16);function gn(e,t,s){const n=mn;return n[0]=1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=1,n[11]=0,n[12]=-e,n[13]=-t,n[14]=-s,n[15]=1,n}const yn=new Float32Array(16);function wn(e,t){const s=yn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var xn,vn,bn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(xn||(xn={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(vn||(vn={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(bn||(bn={}));const Sn=ce("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:xn.Left,verticalAlign:vn.Top,wordWrap:!0,overflow:bn.Visible,lineHeight:1.2}),Pn=ce("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}});class Cn{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(G.textCanvasSize,G.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===bn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),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})`,r&&e.overflow===bn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case vn.Top:x=h;break;case vn.Middle:x=(p-w)/2;break;case vn.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case xn.Left:n=h;break;case xn.Center:n=f/2;break;case xn.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===bn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case xn.Left:return"left";case xn.Center:return"center";case xn.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function Tn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function En(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class Mn{build(e){_e("Text",Sn);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new Cn(t),n=e.world,r=new Map;e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,Sn));for(const e of r.keys())n.valid(e)&&n.has(e,Sn)||r.delete(e);const e=n.getEntitiesWithComponents([Sn]);for(const t of e){const e=n.get(t,Sn),i=n.has(t,Pn)?n.get(t,Pn):null,o=r.get(t);if(o&&!En(o,e,i))continue;n.has(t,Se)||n.insert(t,Se,{texture:K,color:{r:1,g:1,b:1,a:1},size:{x:0,y:0},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0});const a=s.renderForEntity(t,e,i),c=n.get(t,Se);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Se,c),r.set(t,Tn(e,i))}}))}}const An=new Mn,Rn=ce("UIMask",{enabled:!0});function In(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function Fn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function $n(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,A=d*y-p*m,R=f*y-p*g;let I=w*R-x*A+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*R-l*A+h*M)*I,s[1]=(i*A-r*R-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*R-h*T)*I,s[5]=(n*R-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*A-c*E+h*C)*I,s[9]=(r*E-n*A-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function kn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function Bn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function Un(e,t,s,n,r,i,o){if(!e.has(t,Pn)||!e.has(t,be))return null;const a=e.get(t,Pn),c=e.get(t,be),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return Fn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Dn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([Rn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,Rn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,Ee);){const e=t.get(n,Ee);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=Un(t,s,r,i,o,a,c);e&&(n=In(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=Un(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class zn{build(e){if(_e("UIMask",Rn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Dn(e.wasmModule,e.world))}}const Wn=new zn,On=ce("Interactable",{enabled:!0}),Ln=ce("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Hn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Hn||(Hn={}));const jn=ce("Button",{state:Hn.Normal,transition:null});class Nn{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}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 Xn=Oe(new Nn,"UIEvents"),Vn=le("ScreenSpace");function qn(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function Gn(e,t,s,n,r,i){if(!e.has(t,Pn))return;const o=e.get(t,Pn),a=qn(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,ve);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,ve,c),!e.has(t,Me))return;const l=e.get(t,Me);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&Gn(e,t,a.rect,a.centerX,a.centerY,!1)}class Yn{build(e){_e("UIRect",Pn);const t=e.world;e.addSystemToSchedule(Ze.PreUpdate,tt([Le(wt)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Vn,Pn,ve]);for(const e of i)Gn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Jn=new Yn,Kn=new Float32Array(16),Qn=new Float32Array(16);let Zn=!0,er=1;class tr{build(e){_e("Interactable",On),_e("Button",jn);const t=e.world,s=new Nn;e.insertResource(Xn,s);let n=null,r=null;er="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Ze.PreUpdate,tt([Le(ct),Le(wt)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([Ln]);for(const e of o){const s=t.get(e,Ln);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*er,c=i.screenH-e.mouseY*er;!function(e){let t=!1;for(let s=0;s<16;s++)if(Qn[s]!==e[s]){t=!0;break}t&&(Qn.set(e),Zn=!0)}(i.viewProjection),Zn&&($n(i.viewProjection,Kn),Zn=!1);const l=kn(a,c,Kn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([On,Pn,be]);let u=null,d=-1/0;for(const e of h){t.has(e,Ln)||t.insert(e,Ln);if(!t.get(e,On).enabled)continue;const s=t.get(e,be),n=t.get(e,Pn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(Bn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Se)&&(s=t.get(e,Se).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,Ln)){t.get(n,Ln).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,Ln).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,Ln);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,Ln)){const e=t.get(r,Ln);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Ze.Update,tt([],()=>{const e=t.getEntitiesWithComponents([jn]);for(const s of e){if(t.has(s,On)||t.insert(s,On,{enabled:!0}),!t.has(s,Ln))continue;const e=t.get(s,Ln),n=t.get(s,jn),r=t.get(s,On),i=n.state;if(r.enabled?e.pressed?n.state=Hn.Pressed:e.hovered?n.state=Hn.Hovered:n.state=Hn.Normal:n.state=Hn.Disabled,i!==n.state&&n.transition&&t.has(s,Se)){const e=t.get(s,Se),r=n.transition;switch(n.state){case Hn.Normal:e.color={...r.normalColor};break;case Hn.Hovered:e.color={...r.hoveredColor};break;case Hn.Pressed:e.color={...r.pressedColor};break;case Hn.Disabled:e.color={...r.disabledColor}}t.insert(s,Se,e)}}},{name:"ButtonSystem"}))}}const sr=new tr,nr=ce("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});class rr{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){_e("TextInput",nr);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(G.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||w()},_=()=>{a=!0},m=()=>{a=!1,w()},g=t=>{if(null===o)return;if("Escape"===t.key)return void v();const n=s.get(o,nr);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(Xn).emit(o,"submit"),void v()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,b())},y=()=>{if(null!==o&&s.valid(o)&&s.has(o,nr)){const e=s.get(o,nr);e.focused=!1,e.dirty=!0}o=null};function w(){if(null===o||!s.valid(o))return;const t=s.get(o,nr);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(Xn).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,b()}function x(e){if(o===e)return;v();const t=s.get(e,nr);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),b())}function v(){if(null!==o&&s.valid(o)&&s.has(o,nr)){const e=s.get(o,nr);e.focused=!1,e.dirty=!0}o=null,f.blur()}function b(){c=!0,l=0}function S(e,o,a,l){(r.width<a||r.height<l)&&(r.width=or(Math.max(r.width,a)),r.height=or(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=ir(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=ir(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Se);b.texture=v,b.size.x=a,b.size.y=l,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,Se,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",y),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",y),f.remove()},e.addSystemToSchedule(Ze.PreUpdate,tt([Le(Xn)],e=>{const t=s.getEntitiesWithComponents([nr,On]);for(const e of t){if(!s.has(e,Ln))continue;if(s.get(e,Ln).justPressed)return void x(e)}if(null!==o){const e=s.getEntitiesWithComponents([On]);for(const t of e){if(s.has(t,nr))continue;if(!s.has(t,Ln))continue;if(s.get(t,Ln).justPressed)return void v()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Ze.PreUpdate,tt([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,nr)))){s.get(o,nr).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,nr)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([nr,Pn]);for(const e of a){const t=s.get(e,nr);if(!t.dirty)continue;const n=s.get(e,Pn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Se)||s.insert(e,Se,{texture:K,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}),S(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function ir(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function or(e){let t=1;for(;t<e;)t*=2;return t}const ar=new rr;async function cr(e,t,s){const n=e.getResource(sn);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function lr(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 hr=Oe({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),ur=Oe(null,"PhysicsAPI");function dr(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function fr(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class pr{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(hr,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=lr(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([Ce]);for(const s of t){const t=e.world.get(s,Ce);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Ze.PostUpdate,tt([Le(Xe)],a=>{const c=o.getEntitiesWithComponents([ke,ve,be]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,ke),c=o.get(r,be);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=dr(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),_r(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ze.Kinematic){const e=dr(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,ve);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,Ee)){const t=e.world.get(o,Ee);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,be)){const s=e.world.get(t.entity,be),n=dr(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=fr(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,ve,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],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;i.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=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(hr,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(ur,mr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function _r(e,t,s){const n=e.world;if(n.has(s,Be)){const e=n.get(s,Be);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,Ue)){const e=n.get(s,Ue);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,De)){const e=n.get(s,De);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 mr{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(mr.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)}}function gr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function yr(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 wr(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function xr(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=gr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===x(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=yr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=gr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new pr("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=x(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=gr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=At.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=At.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=jt(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=Nt(e.world,s);if(c&&e.hasResource(sn))for(const t of p.values())e.world.insert(t,Fe,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,Re)?l.get(i,Re):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,be)){const e=wr(l.get(i,be),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Jt);t&&t.setAddressableManifest(a)}}function vr(e,t,s){return{name:e,data:t,async setup(){await xr(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class br{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===x(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=x(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)||i.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{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const Sr="__preview__";class Pr{constructor(e,t){this.app_=null,this.loadPromise_=null,this.eventSource_=null,this.onMessage_=null,this.onError_=null,this.sceneUrl_=e,this.baseUrl_=t??""}build(e){this.app_=e;const t=e.getResource(sn);t.register({name:Sr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(Sr),this.loadPromise_=t.load(Sr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new br(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await xr(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,Sr)}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([Ce]);for(const r of n){const n=e.get(r,Ce);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(sn).getScene(Sr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,ve,o);const a={isActive:!0,projectionType:ye.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:we.ColorAndDepth};e.insert(i,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(sn);await e.switchTo(Sr),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 Cr={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Vs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Vs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Vs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Vs.releaseRenderTarget(e._handle),Cr.create({width:t,height:s,depth:!0})),begin(e,t){Vs.begin(t,e._handle)},end(){Vs.end()},getDepthTexture:e=>Vs.getTargetDepthTexture(e._handle)};let Tr=!1;function Er(e){Tr=e}function Mr(){return Tr}function Ar(){return!Tr}var Rr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(Rr||(Rr={}));class Ir{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${Rr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case Rr.Debug:console.debug(t,s);break;case Rr.Info:console.log(t,s);break;case Rr.Warn:console.warn(t,s);break;case Rr.Error:console.error(t,s)}}}class Fr{constructor(){this.handlers_=[],this.minLevel_=Rr.Info,this.addHandler(new Ir)}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(Rr.Debug,e,t,s)}info(e,t,s){this.log(Rr.Info,e,t,s)}warn(e,t,s){this.log(Rr.Warn,e,t,s)}error(e,t,s){this.log(Rr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const $r=new Fr;function kr(){return $r}function Br(e){$r.setMinLevel(e)}function Ur(e,t,s){$r.debug(e,t,s)}function Dr(e,t,s){$r.info(e,t,s)}function zr(e,t,s){$r.warn(e,t,s)}function Wr(e,t,s){$r.error(e,t,s)}const Or=[An,Wn,Jn,sr,ar];function Lr(e,t){return function(e,t){const s=an.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),ps(e),Tt(e),Is(e),Us(e),Ns(e),Gs(e);const r=new Ks;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=un(e,n,t,r));const o=s.getResource(wt);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(wt,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Vs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Vs.resize(t,c),Ws.isInitialized()&&Ws.getPassCount()>0&&!Ws.isBypassed()&&Ws.resize(t,c),s.hasResource(sn)){const e=s.getResource(sn).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=un(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:ln,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Vs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Ze.First,c),s.addSystemToSchedule(Ze.Last,l),s.addPlugin(Qt),s.addPlugin(cs),s.addPlugin(ht),s.addPlugin(on),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Or,...t})}H||(H=!0,function(){const e=globalThis;if(void 0===e.performance){const t=Date.now();e.performance={now:()=>Date.now()-t}}}(),void 0===globalThis.fetch&&(globalThis.fetch=async(e,t)=>{const s="string"==typeof e?e:e.toString(),n={method:t?.method??"GET",headers:t?.headers,body:t?.body},r=await f(s,n);return{ok:r.ok,status:r.status,statusText:r.statusText,headers:new Headers(r.headers),json:()=>r.json(),text:()=>r.text(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>Promise.reject(new Error("Blob not supported in WeChat")),formData:()=>Promise.reject(new Error("FormData not supported in WeChat")),clone:()=>{throw new Error("clone not supported")},body:null,bodyUsed:!1,redirected:!1,type:"basic",url:s}}),"undefined"!=typeof WXWebAssembly&&"undefined"==typeof WebAssembly&&(globalThis.WebAssembly={instantiate:async(e,t)=>{if("string"!=typeof e)throw new Error("WeChat WXWebAssembly requires a file path string, not ArrayBuffer. Use platform adapter instead of direct WebAssembly.instantiate.");return p(e,t??{})},compile:()=>{throw new Error("WebAssembly.compile is not supported in WeChat MiniGame")},compileStreaming:()=>{throw new Error("WebAssembly.compileStreaming is not supported in WeChat MiniGame")},instantiateStreaming:()=>{throw new Error("WebAssembly.instantiateStreaming is not supported in WeChat MiniGame")},validate:()=>{throw new Error("WebAssembly.validate is not supported in WeChat MiniGame")},Module:class{},Instance:class{},Memory:class{},Table:class{},Global:class{},CompileError:Error,LinkError:Error,RuntimeError:Error}),function(){const e=globalThis;void 0===e.TextEncoder&&(e.TextEncoder=class{encode(e){const t=new ArrayBuffer(3*e.length),s=new Uint8Array(t);let n=0;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?s[n++]=r:r<2048?(s[n++]=192|r>>6,s[n++]=128|63&r):r>=55296&&r<=56319?(r=e.charCodeAt(++t)-56320+(r-55296<<10)+65536,s[n++]=240|r>>18,s[n++]=128|r>>12&63,s[n++]=128|r>>6&63,s[n++]=128|63&r):(s[n++]=224|r>>12,s[n++]=128|r>>6&63,s[n++]=128|63&r)}return s.subarray(0,n)}}),void 0===e.TextDecoder&&(e.TextDecoder=class{decode(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);let s="";for(let e=0;e<t.length;){const n=t[e];if(n<128)s+=String.fromCharCode(n),e++;else if(192==(224&n))s+=String.fromCharCode((31&n)<<6|63&t[e+1]),e+=2;else if(224==(240&n))s+=String.fromCharCode((15&n)<<12|(63&t[e+1])<<6|63&t[e+2]),e+=3;else{const r=((7&n)<<18|(63&t[e+1])<<12|(63&t[e+2])<<6|63&t[e+3])-65536;s+=String.fromCharCode(55296+(r>>10),56320+(1023&r)),e+=4}}return s}})}(),console.log("[ESEngine] WeChat platform initialized")),e=j;export{an as App,Kt as AssetPlugin,Zt as AssetRefCounter,Yt as AssetServer,Jt as Assets,zt as AsyncCache,Ae as BitmapText,xt as BlendMode,ze as BodyType,Be as BoxCollider,jn as Button,Hn as ButtonState,Pe as Camera,Ce as Canvas,De as CapsuleCollider,Me as Children,Ue as CircleCollider,we as ClearFlags,Je as Commands,Qe as CommandsInstance,X as DEFAULT_DESIGN_HEIGHT,N as DEFAULT_DESIGN_WIDTH,V as DEFAULT_PIXELS_PER_UNIT,q as DEFAULT_TEXT_CANVAS_SIZE,Ts as DataType,ys as Draw,Ke as EntityCommands,Js as GLDebug,ks as Geometry,J as INVALID_ENTITY,Q as INVALID_FONT,K as INVALID_TEXTURE,ct as Input,lt as InputPlugin,at as InputState,On as Interactable,ve as LocalTransform,Rr as LogLevel,Fr as Logger,At as Material,Wt as MaterialLoader,Ve as Mut,Ie as Name,Ee as Parent,mr as Physics,hr as PhysicsEvents,pr as PhysicsPlugin,Ws as PostProcess,is as PrefabServer,os as Prefabs,as as PrefabsPlugin,Pr as PreviewPlugin,ye as ProjectionType,Ge as Query,Ye as QueryInstance,Ks as RenderPipeline,Ls as RenderStage,Cr as RenderTexture,Vs as Renderer,Le as Res,He as ResMut,ke as RigidBody,G as RuntimeConfig,xe as ScaleMode,sn as SceneManager,tn as SceneManagerState,Fe as SceneOwner,Ze as Schedule,Vn as ScreenSpace,Dt as ShaderSources,Re as SpineAnimation,Se as Sprite,ot as SystemRunner,Sn as Text,xn as TextAlign,nr as TextInput,rr as TextInputPlugin,bn as TextOverflow,Mn as TextPlugin,Cn as TextRenderer,vn as TextVerticalAlign,Xe as Time,wt as UICameraInfo,Nn as UIEventQueue,Xn as UIEvents,Ln as UIInteraction,tr as UIInteractionPlugin,Yn as UILayoutPlugin,Rn as UIMask,zn as UIMaskPlugin,Pn as UIRect,Te as Velocity,br as WebAssetProvider,yt as World,be as WorldTransform,rt as addStartupSystem,nt as addSystem,it as addSystemToSchedule,Y as applyRuntimeConfig,Qt as assetPlugin,Cs as clearDrawCallbacks,ue as clearUserComponents,se as color,qn as computeUIRectLayout,Dn as createMaskProcessor,vr as createRuntimeSceneConfig,Lr as createWebApp,Ur as debug,ce as defineComponent,Oe as defineResource,tt as defineSystem,le as defineTag,Wr as error,Gt as findEntityByName,cn as flushPendingSystems,b as getAddressableType,S as getAddressableTypeByEditorType,C as getAllAssetExtensions,A as getAssetMimeType,x as getAssetTypeEntry,me as getComponent,Ht as getComponentAssetFields,$e as getComponentDefaults,E as getCustomExtensions,v as getEditorType,kr as getLogger,t as getPlatform,n as getPlatformType,he as getUserComponent,M as getWeChatPackOptions,Dr as info,ps as initDrawAPI,Gs as initGLDebugAPI,Is as initGeometryAPI,Tt as initMaterialAPI,Us as initPostProcessAPI,Ns as initRendererAPI,ht as inputPlugin,ts as instantiatePrefab,In as intersectRects,$n as invertMatrix4,fe as isBuiltinComponent,R as isCustomExtension,Mr as isEditor,P as isKnownAssetExtension,s as isPlatformInitialized,Ar as isRuntime,vt as isTextureRef,r as isWeChat,i as isWeb,Vt as loadComponent,lr as loadPhysicsModule,xr as loadRuntimeScene,Nt as loadSceneData,Xt as loadSceneWithAssets,T as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,Bn as pointInWorldRect,cs as prefabsPlugin,ne as quat,_e as registerComponent,Lt as registerComponentAssetFields,Ss as registerDrawCallback,es as registerEmbeddedAssets,Ut as registerMaterialCallback,on as sceneManagerPlugin,kn as screenToWorld,Er as setEditorMode,Br as setLogLevel,_t as setWasmErrorHandler,_s as shutdownDrawAPI,Ys as shutdownGLDebugAPI,Fs as shutdownGeometryAPI,Et as shutdownMaterialAPI,Ds as shutdownPostProcessAPI,Xs as shutdownRendererAPI,ar as textInputPlugin,An as textPlugin,cr as transitionTo,sr as uiInteractionPlugin,Jn as uiLayoutPlugin,Wn as uiMaskPlugin,Or as uiPlugins,Ps as unregisterDrawCallback,qt as updateCameraAspectRatio,Z as vec2,ee as vec3,te as vec4,zr as warn,Fn as worldRectToScreen,nn as wrapSceneSystem,U as wxFileExists,D as wxFileExistsSync,O as wxGetImagePixels,W as wxLoadImage,L as wxLoadImagePixels,k as wxReadFile,B as wxReadTextFile,z 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 0a018505e..74fbdd6f9 100644
--- a/desktop/public/sdk/esm/esengine.d.ts
+++ b/desktop/public/sdk/esm/esengine.d.ts
@@ -696,7 +696,6 @@ declare class World {
private getStorage;
resetQueryPool(): void;
getComponentTypes(entity: Entity): string[];
- private findScriptName;
getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
diff --git a/desktop/public/sdk/esm/esengine.js b/desktop/public/sdk/esm/esengine.js
index 149cfd310..2b3a54d0e 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 r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=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 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),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",c),s.addEventListener("touchmove",l),s.addEventListener("touchend",h),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",c),s.removeEventListener("touchmove",l),s.removeEventListener("touchend",h),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let R=0;function A(e,t){const s=++R;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=A(e,t);return s.set(e,r),U(e,t,!1),r}function $(e){const t=I(),s=t.get(e);if(s)return s;const n=A(e,{});return t.set(e,n),U(e,{},!0),n}function k(e){return I().get(e)}function B(){I().clear()}function U(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const L=new Map;function z(e,t){L.set(e,t)}function O(e){return L.get(e)??k(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return L.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.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:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("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}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}z("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce={Static:0,Kinematic:1,Dynamic:2};let le=0;function he(e,t){const s=++le;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ue(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=he({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,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(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{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=D(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 be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Se;!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"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Re(e,t){Te().push({schedule:e,system:t})}class Ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{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 Fe=he(new Ie,"Input");class $e{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,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(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ke=new $e;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ue(t[e]),i=Ue(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(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 Le=null;function ze(e){Le=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),Le&&Le(e,t)}function He(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:He(e)}}return t}class We{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==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 Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(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.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Oe(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.");D(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_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Oe(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 Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.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,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_){const s=["LocalTransform","GlobalTransform","Sprite","Camera","Text","Velocity","Parent","Children","BitmapText","SpineAnimation","Canvas","UIRect","Interaction","Mask","LayoutGroup","LayoutElement","TextInput","RigidBody","BoxCollider","CircleCollider","CapsuleCollider"];for(const n of s){if(t.includes(n))continue;const s=O(n);if(s&&D(s))try{this.getBuiltinMethods(s._cppName).has(e)&&t.push(n)}catch{}}}const s=this.entityComponents_.get(e);if(s)for(const n of s)for(const[,s]of this.tsStorage_)if(s.has(e)&&s===this.tsStorage_.get(n))for(const[e,s]of this.findScriptName(n))t.includes(e)||t.push(e);return t}findScriptName(e){const t=[];if("undefined"!=typeof window&&window.__esengine_componentRegistry){const s=window.__esengine_componentRegistry;for(const[n,r]of s)if(r._id===e){t.push([n,r]);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const je=he({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ne;function Ve(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"}(Ne||(Ne={}));let Xe=null,Ye=null,qe=1;const Ge=new Map;function Je(e){Xe=e,Ye=e.getResourceManager(),ot()}function Ke(){0!==tt&&Xe&&(Xe._free(tt),tt=0),Ge.clear(),qe=1,et=!1,nt.clear(),rt=null,Ye=null,Xe=null}function Qe(){if(!Ye)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ye}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ne.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 Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??Ne.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},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??Ne.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=qe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.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=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const st=4096,nt=new Map;let rt=null;function it(e){const t=(0===tt&&Xe&&(tt=Xe._malloc(st)),tt);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,i=Xe.HEAPU32,o=Xe.HEAPF32;for(const[a,c]of e){if(s+128>st)break;let e=nt.get(a);e||(rt||(rt=new TextEncoder),e=rt.encode(a),nt.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=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 e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}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]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function ot(){if(!Xe||et)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const i=Ge.get(e);if(!i)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=i.shader,Xe.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=it(i.uniforms);Xe.HEAPU32[n>>2]=o,Xe.HEAPU32[r>>2]=a},et=!0}const at={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class lt{constructor(e,t=""){this.cache_=new ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Ze.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ht=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"}]}]]);function ut(e,t){ht.set(e,t)}function dt(e){const t=ht.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 ft(e){return ht.get(e)?.fields??[]}function pt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)mt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function _t(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.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}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)mt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function mt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function gt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function yt(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const wt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],xt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},vt=new Map,bt=new Set;for(const e of wt)for(const t of e.extensions)vt.set(t,e),bt.add(t);function St(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Pt(e){return vt.get(St(e))}function Ct(e){return Pt(e)?.editorType??"unknown"}function Tt(e){return Pt(e)?.addressableType??null}function Et(e){for(const t of wt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Mt(e){return bt.has(e.toLowerCase())}function Rt(){return bt}function At(e){return"string"==typeof e&&(!!e.includes("/")&&Mt(St(e)))}function It(){const e=[];for(const t of wt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Ft(){return It().map(e=>({type:"suffix",value:e}))}function $t(e){return xt[e.toLowerCase()]}function kt(e){const t=Pt(e);return t?.wechatPackInclude??!1}class Bt{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=u(y.textCanvasSize,y.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 lt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,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(),Ze.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===Pt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Pt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return _t(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const 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=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=he(null,"Assets");class Dt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Bt(t)):console.warn("AssetPlugin: No WASM module available")}}const Lt=new Dt;class zt{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 Ot(e,t){const s=e.getResource(Ut);s&&s.registerEmbeddedAssets(t)}async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(t,s?.overrides??[],s,void 0,new Set),i={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}))},o=await _t(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Wt=10;async function jt(e,t,s,n,r,i=0){if(i>Wt)throw new Error(`Prefab nesting depth exceeded ${Wt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await jt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function Nt(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 Vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=he(null,"Prefabs");class Yt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Xt,new Vt(e.world,t))}}const qt=new Yt;let Gt=null,Jt=0,Kt=0,Qt=0;const Zt=new Float32Array(256);function es(e){Gt=e,Jt=Gt._malloc(64),Kt=Gt._malloc(64),Qt=Gt._malloc(1024)}function ts(){Gt&&(Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0),Qt&&(Gt._free(Qt),Qt=0)),Gt=null}function ss(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const ns={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Oe(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{ss().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{ss().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ss().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ss().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ss().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=ns){try{ss().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ns){try{ss().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ss();n.HEAPF32.set(s,Kt/4),n.draw_mesh(e,t,Kt)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ss(),r=Ze.get(t);if(!r)return;if(rs.setBlendMode(r.blendMode),rs.setDepthTest(r.depthTest),0===r.uniforms.size)return void rs.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Kt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=as(t);if(!(n<0)){if(Ve(s))Zt[i++]=10,Zt[i++]=n,Zt[i++]=s.slot??e++,Zt[i++]=s.textureId;else if("number"==typeof s)Zt[i++]=1,Zt[i++]=n,Zt[i++]=s;else if(Array.isArray(s)){Zt[i++]=s.length,Zt[i++]=n;for(let e=0;e<s.length;e++)Zt[i++]=s[e]}else"w"in s?(Zt[i++]=4,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z,Zt[i++]=s.w):"z"in s?(Zt[i++]=3,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z):(Zt[i++]=2,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.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(Zt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,Kt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Qt/4),n.draw_meshWithUniforms(e,r.shader,Kt,Qt,i)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={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},os=new Set;function as(e){const t=is[e];return void 0!==t?t:(os.has(e)||(os.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ls(e,t,s){cs.set(e,{fn:t,scene:s??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var ds;!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"}(ds||(ds={}));let fs=null,ps=0,_s=0,ms=0;function gs(e){fs=e,ps=fs._malloc(262144),_s=fs._malloc(65536),ms=fs._malloc(256)}function ys(){fs&&(ps&&fs._free(ps),_s&&fs._free(_s),ms&&fs._free(ms),ps=0,_s=0,ms=0),fs=null}function ws(){if(!fs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return fs}const xs={create(e){const t=ws(),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,ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ms,r).set(i),t.geometry_init(s,ps,n,ms,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ps/4),n.geometry_updateVertices(e,ps,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!fs||e<=0)&&fs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return xs.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:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return xs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(o)})}};let vs=null;function bs(e){vs=e}function Ss(){vs&&Cs.isInitialized()&&Cs.shutdown(),vs=null}function Ps(){if(!vs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vs}const Cs={init(e,t){try{return Ps().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ps().postprocess_setUniformFloat(e,t,s)}catch(s){Oe(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ps().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Oe(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!vs)return!1;try{return vs.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!vs)return!0;try{return vs.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ze.createShader(Ts,"#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="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Es;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Es||(Es={}));let Ms=null,Rs=0;function As(e){Ms=e,Rs=Ms._malloc(64)}function Is(){Ms&&Rs&&(Ms._free(Rs),Rs=0),Ms=null}const Fs={init(e,t){Ms?.renderer_init(e,t)},resize(e,t){Ms?.renderer_resize(e,t)},begin(e,t){if(Ms&&Rs)try{Ms.HEAPF32.set(e,Rs/4),Ms.renderer_begin(Rs,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{Ms?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{Ms?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(Ms)try{Ms.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ms)try{Ms.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ms)try{Ms.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){Ms?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ms?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ms?.renderer_releaseTarget(e)},getTargetTexture:e=>Ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ms?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ms?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ms?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ms?Ms.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ms?{drawCalls:Ms.renderer_getDrawCalls(),triangles:Ms.renderer_getTriangles(),sprites:Ms.renderer_getSprites(),text:Ms.renderer_getText(),spine:Ms.renderer_getSpine?.()??0,meshes:Ms.renderer_getMeshes(),culled:Ms.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $s=null;function ks(e){$s=e}function Bs(){$s=null}const Us={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ds{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Fs.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Fs.setViewport(0,0,n,r),Fs.clearBuffers(3),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Fs.setViewport(n.x,n.y,n.w,n.h),Fs.setScissor(n.x,n.y,n.w,n.h,!0),Fs.clearBuffers(r),Fs.setScissor(0,0,0,0,!1),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){rs.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}rs.end();for(const e of n)hs(e)}}}const Ls="__scene_transition_overlay__";class zs{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Os{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,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),ls(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Hs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ls(Ls,()=>{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;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,hs(Ls)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(Ls),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new zs(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new zs(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,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())hs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ws=he(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ws).getSceneStatus(t)&&s._fn(...n)}}}const Ns=Ce([de(Ws),ue(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vs={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Ws,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ws),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Ns)}};class Xs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Se.Last);else{this.runSchedule(Se.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new We,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Xs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),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(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),t&&(this.module_=t),this}get wasmModule(){return this.module_}get pipeline(){return this.pipeline_}setPipeline(e){this.pipeline_=e}setSpineRenderer(e){this.pipeline_?.setSpineRenderer(e)}get spineInitPromise(){return this.spineInitPromise_}set spineInitPromise(e){this.spineInitPromise_=e}get physicsInitPromise(){return this.physicsInitPromise_}set physicsInitPromise(e){this.physicsInitPromise_=e}get physicsModule(){return this.physicsModule_}set physicsModule(e){this.physicsModule_=e}get world(){return this.world_}setFixedTimestep(e){return this.fixedTimestep_=e,this}setMaxDeltaTime(e){return this.maxDeltaTime_=e,this}setMaxFixedSteps(e){return this.maxFixedSteps_=e,this}onError(e){return this.error_handler_=e,this}onSystemError(e){return this.system_error_handler_=e,this}onWasmError(e){return ze(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ws).register(e),this}setInitialScene(e){return this.getResource(Ws).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ae(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,us();const e=[Bs,Is,Ss,ys,Ke,ts];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}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ys(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Js(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,c){d=Gs(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=Qs(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=en(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=sn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(rn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Ks=new Float32Array(16);function Qs(e,t,s,n,r,i){const o=Ks;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const Zs=new Float32Array(16);function en(e,t,s,n){const r=Zs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const tn=new Float32Array(16);function sn(e,t,s){const n=tn;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 nn=new Float32Array(16);function rn(e,t){const s=nn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var on,an,cn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(on||(on={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(an||(an={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cn||(cn={}));const ln=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:on.Left,verticalAlign:an.Top,wordWrap:!0,overflow:cn.Visible,lineHeight:1.2}),hn=F("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}});class un{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===cn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),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})`,r&&e.overflow===cn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case an.Top:x=h;break;case an.Middle:x=(p-w)/2;break;case an.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case on.Left:n=h;break;case on.Center:n=f/2;break;case on.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===cn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case on.Left:return"left";case on.Center:return"center";case on.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function dn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function fn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class pn{build(e){z("Text",ln);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new un(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ln));for(const e of r.keys())n.valid(e)&&n.has(e,ln)||r.delete(e);const e=n.getEntitiesWithComponents([ln]);for(const t of e){const e=n.get(t,ln),i=n.has(t,hn)?n.get(t,hn):null,o=r.get(t);if(o&&!fn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,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});const a=s.renderForEntity(t,e,i),c=n.get(t,Y);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Y,c),r.set(t,dn(e,i))}}))}}const _n=new pn,mn=F("UIMask",{enabled:!0});function gn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function yn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function wn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,R=d*y-p*m,A=f*y-p*g;let I=w*A-x*R+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*A-l*R+h*M)*I,s[1]=(i*R-r*A-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*A-h*T)*I,s[5]=(n*A-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*R-c*E+h*C)*I,s[9]=(r*E-n*R-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function xn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function vn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function bn(e,t,s,n,r,i,o){if(!e.has(t,hn)||!e.has(t,X))return null;const a=e.get(t,hn),c=e.get(t,X),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return yn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Sn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([mn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,mn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=bn(t,s,r,i,o,a,c);e&&(n=gn(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=bn(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Pn{build(e){if(z("UIMask",mn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Sn(e.wasmModule,e.world))}}const Cn=new Pn,Tn=F("Interactable",{enabled:!0}),En=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Mn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Mn||(Mn={}));const Rn=F("Button",{state:Mn.Normal,transition:null});class An{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}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 In=he(new An,"UIEvents"),Fn=$("ScreenSpace");function $n(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function kn(e,t,s,n,r,i){if(!e.has(t,hn))return;const o=e.get(t,hn),a=$n(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,V);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,V,c),!e.has(t,Q))return;const l=e.get(t,Q);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&kn(e,t,a.rect,a.centerX,a.centerY,!1)}class Bn{build(e){z("UIRect",hn);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([ue(je)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Fn,hn,V]);for(const e of i)kn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Un=new Bn,Dn=new Float32Array(16),Ln=new Float32Array(16);let zn=!0,On=1;class Hn{build(e){z("Interactable",Tn),z("Button",Rn);const t=e.world,s=new An;e.insertResource(In,s);let n=null,r=null;On="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([ue(Fe),ue(je)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([En]);for(const e of o){const s=t.get(e,En);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*On,c=i.screenH-e.mouseY*On;!function(e){let t=!1;for(let s=0;s<16;s++)if(Ln[s]!==e[s]){t=!0;break}t&&(Ln.set(e),zn=!0)}(i.viewProjection),zn&&(wn(i.viewProjection,Dn),zn=!1);const l=xn(a,c,Dn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Tn,hn,X]);let u=null,d=-1/0;for(const e of h){t.has(e,En)||t.insert(e,En);if(!t.get(e,Tn).enabled)continue;const s=t.get(e,X),n=t.get(e,hn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(vn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,En)){t.get(n,En).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,En).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,En);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,En)){const e=t.get(r,En);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){if(t.has(s,Tn)||t.insert(s,Tn,{enabled:!0}),!t.has(s,En))continue;const e=t.get(s,En),n=t.get(s,Rn),r=t.get(s,Tn),i=n.state;if(r.enabled?e.pressed?n.state=Mn.Pressed:e.hovered?n.state=Mn.Hovered:n.state=Mn.Normal:n.state=Mn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Mn.Normal:e.color={...r.normalColor};break;case Mn.Hovered:e.color={...r.hoveredColor};break;case Mn.Pressed:e.color={...r.pressedColor};break;case Mn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const Wn=new Hn,jn=F("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});class Nn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){z("TextInput",jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,jn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(In).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,jn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(In).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,jn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){c=!0,l=0}function C(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Xn(Math.max(r.width,a)),r.height=Xn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Vn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Vn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=l,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,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([ue(In)],e=>{const t=s.getEntitiesWithComponents([jn,Tn]);for(const e of t){if(!s.has(e,En))continue;if(s.get(e,En).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([Tn]);for(const t of e){if(s.has(t,jn))continue;if(!s.has(t,En))continue;if(s.get(t,En).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,jn)))){s.get(o,jn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,jn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([jn,hn]);for(const e of a){const t=s.get(e,jn);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,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}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Vn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Xn(e){let t=1;for(;t<e;)t*=2;return t}const Yn=new Nn;async function qn(e,t,s){const n=e.getResource(Ws);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Gn(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 Jn=he({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kn=he(null,"PhysicsAPI");function Qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class er{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(Jn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Gn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([ue(_e)],a=>{const c=o.getEntitiesWithComponents([re,V,X]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,re),c=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Qn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),tr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=Qn(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,V);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=Qn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=Zn(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,V,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],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;i.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=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Jn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Kn,sr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function tr(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);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,oe)){const e=n.get(s,oe);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,ae)){const e=n.get(s,ae);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 sr{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(sr.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)}}function nr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function rr(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 ir(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function or(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=nr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===Pt(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=rr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=nr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new er("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=Pt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=nr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Ze.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ft(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=pt(e.world,s);if(c&&e.hasResource(Ws))for(const t of p.values())e.world.insert(t,se,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,ee)?l.get(i,ee):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,X)){const e=ir(l.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function ar(e,t,s){return{name:e,data:t,async setup(){await or(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class cr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===Pt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=Pt(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)||i.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{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const lr="__preview__";class hr{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(Ws);t.register({name:lr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(lr),this.loadPromise_=t.load(lr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new cr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await or(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,lr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).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([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ws).getScene(lr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,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(Ws);await e.switchTo(lr),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 ur={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Fs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Fs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Fs.releaseRenderTarget(e._handle),ur.create({width:t,height:s,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};let dr=!1;function fr(e){dr=e}function pr(){return dr}function _r(){return!dr}var mr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mr||(mr={}));class gr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mr.Debug:console.debug(t,s);break;case mr.Info:console.log(t,s);break;case mr.Warn:console.warn(t,s);break;case mr.Error:console.error(t,s)}}}class yr{constructor(){this.handlers_=[],this.minLevel_=mr.Info,this.addHandler(new gr)}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(mr.Debug,e,t,s)}info(e,t,s){this.log(mr.Info,e,t,s)}warn(e,t,s){this.log(mr.Warn,e,t,s)}error(e,t,s){this.log(mr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const wr=new yr;function xr(){return wr}function vr(e){wr.setMinLevel(e)}function br(e,t,s){wr.debug(e,t,s)}function Sr(e,t,s){wr.info(e,t,s)}function Pr(e,t,s){wr.warn(e,t,s)}function Cr(e,t,s){wr.error(e,t,s)}const Tr=[_n,Cn,Un,Wn,Yn];function Er(e,t){return function(e,t){const s=Xs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),es(e),Je(e),gs(e),bs(e),As(e),ks(e);const r=new Ds;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Js(e,n,t,r));const o=s.getResource(je);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(je,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Fs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Fs.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ws)){const e=s.getResource(Ws).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Js(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:qs,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Fs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Se.First,c),s.addSystemToSchedule(Se.Last,l),s.addPlugin(Lt),s.addPlugin(qt),s.addPlugin(ke),s.addPlugin(Vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Tr,...t})}e=f;export{Xs as App,Dt as AssetPlugin,zt as AssetRefCounter,Bt as AssetServer,Ut as Assets,ct as AsyncCache,Z as BitmapText,Ne as BlendMode,ce as BodyType,ie as BoxCollider,Rn as Button,Mn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ds as DataType,rs as Draw,ve as EntityCommands,Us as GLDebug,xs as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,$e as InputPlugin,Ie as InputState,Tn as Interactable,V as LocalTransform,mr as LogLevel,yr as Logger,Ze as Material,lt as MaterialLoader,me as Mut,te as Name,K as Parent,sr as Physics,Jn as PhysicsEvents,er as PhysicsPlugin,Cs as PostProcess,Vt as PrefabServer,Xt as Prefabs,Yt as PrefabsPlugin,hr as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,Ds as RenderPipeline,Es as RenderStage,ur as RenderTexture,Fs as Renderer,ue as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,Ws as SceneManager,Hs as SceneManagerState,se as SceneOwner,Se as Schedule,Fn as ScreenSpace,at as ShaderSources,ee as SpineAnimation,Y as Sprite,Ae as SystemRunner,ln as Text,on as TextAlign,jn as TextInput,Nn as TextInputPlugin,cn as TextOverflow,pn as TextPlugin,un as TextRenderer,an as TextVerticalAlign,_e as Time,je as UICameraInfo,An as UIEventQueue,In as UIEvents,En as UIInteraction,Hn as UIInteractionPlugin,Bn as UILayoutPlugin,mn as UIMask,Pn as UIMaskPlugin,hn as UIRect,J as Velocity,cr as WebAssetProvider,We as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Re as addSystemToSchedule,w as applyRuntimeConfig,Lt as assetPlugin,us as clearDrawCallbacks,B as clearUserComponents,T as color,$n as computeUIRectLayout,Sn as createMaskProcessor,ar as createRuntimeSceneConfig,Er as createWebApp,br as debug,F as defineComponent,he as defineResource,Ce as defineSystem,$ as defineTag,Cr as error,yt as findEntityByName,Ys as flushPendingSystems,Tt as getAddressableType,Et as getAddressableTypeByEditorType,Rt as getAllAssetExtensions,$t as getAssetMimeType,Pt as getAssetTypeEntry,O as getComponent,dt as getComponentAssetFields,ne as getComponentDefaults,It as getCustomExtensions,Ct as getEditorType,xr as getLogger,t as getPlatform,n as getPlatformType,k as getUserComponent,Ft as getWeChatPackOptions,Sr as info,es as initDrawAPI,ks as initGLDebugAPI,gs as initGeometryAPI,Je as initMaterialAPI,bs as initPostProcessAPI,As as initRendererAPI,ke as inputPlugin,Ht as instantiatePrefab,gn as intersectRects,wn as invertMatrix4,D as isBuiltinComponent,kt as isCustomExtension,pr as isEditor,Mt as isKnownAssetExtension,s as isPlatformInitialized,_r as isRuntime,Ve as isTextureRef,r as isWeChat,i as isWeb,mt as loadComponent,Gn as loadPhysicsModule,or as loadRuntimeScene,pt as loadSceneData,_t as loadSceneWithAssets,At as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,vn as pointInWorldRect,qt as prefabsPlugin,E as quat,z as registerComponent,ut as registerComponentAssetFields,ls as registerDrawCallback,Ot as registerEmbeddedAssets,ot as registerMaterialCallback,Vs as sceneManagerPlugin,xn as screenToWorld,fr as setEditorMode,vr as setLogLevel,ze as setWasmErrorHandler,ts as shutdownDrawAPI,Bs as shutdownGLDebugAPI,ys as shutdownGeometryAPI,Ke as shutdownMaterialAPI,Ss as shutdownPostProcessAPI,Is as shutdownRendererAPI,Yn as textInputPlugin,_n as textPlugin,qn as transitionTo,Wn as uiInteractionPlugin,Un as uiLayoutPlugin,Cn as uiMaskPlugin,Tr as uiPlugins,hs as unregisterDrawCallback,gt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,Pr as warn,yn as worldRectToScreen,js as wrapSceneSystem};
+let e=null;function t(){if(!e)throw new Error('[ESEngine] Platform not initialized. Import from "esengine" (web) or "esengine/wechat" (WeChat) instead of direct imports.');return e}function s(){return null!==e}function n(){return e?.name??null}function r(){return"wechat"===e?.name}function i(){return"web"===e?.name}async function o(e,s){return t().fetch(e,s)}async function a(e){return t().readFile(e)}async function c(e){return t().readTextFile(e)}async function l(e){return t().fileExists(e)}async function h(e,s){return t().instantiateWasm(e,s)}function u(e,s){return t().createCanvas(e,s)}function d(){return t().now()}const f=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 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),r=t=>e.onKeyUp(t.code),i=t=>{const s=t;e.onPointerMove(s.offsetX,s.offsetY)},o=t=>{const s=t;e.onPointerDown(s.button,s.offsetX,s.offsetY)},a=t=>{e.onPointerUp(t.button)},c=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerDown(0,n.clientX-t.left,n.clientY-t.top)}},l=t=>{const n=t.touches[0];if(n){const t=s.getBoundingClientRect();e.onPointerMove(n.clientX-t.left,n.clientY-t.top)}},h=()=>{e.onPointerUp(0)},u=t=>{const s=t;e.onWheel(s.deltaX,s.deltaY)};document.addEventListener("keydown",n),document.addEventListener("keyup",r),s.addEventListener("mousemove",i),s.addEventListener("mousedown",o),s.addEventListener("mouseup",a),s.addEventListener("touchstart",c),s.addEventListener("touchmove",l),s.addEventListener("touchend",h),s.addEventListener("wheel",u),this.inputCleanup_=()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r),s.removeEventListener("mousemove",i),s.removeEventListener("mousedown",o),s.removeEventListener("mouseup",a),s.removeEventListener("touchstart",c),s.removeEventListener("touchmove",l),s.removeEventListener("touchend",h),s.removeEventListener("wheel",u)}}unbindInputEvents(){this.inputCleanup_&&(this.inputCleanup_(),this.inputCleanup_=null)}},p=1920,_=1080,m=100,g=512,y={sceneTransitionDuration:.3,sceneTransitionColor:{r:0,g:0,b:0,a:1},defaultFontFamily:"Arial",canvasScaleMode:1,canvasMatchWidthOrHeight:.5,maxDeltaTime:.25,maxFixedSteps:8,textCanvasSize:512};function w(e){e.Text&&(e.Text._default.fontFamily=y.defaultFontFamily),e.TextInput&&(e.TextInput._default.fontFamily=y.defaultFontFamily),e.Canvas&&(e.Canvas._default.scaleMode=y.canvasScaleMode,e.Canvas._default.matchWidthOrHeight=y.canvasMatchWidthOrHeight)}const x=0,v=4294967295,b=4294967295,S=(e=0,t=0)=>({x:e,y:t}),P=(e=0,t=0,s=0)=>({x:e,y:t,z:s}),C=(e=0,t=0,s=0,n=1)=>({x:e,y:t,z:s,w:n}),T=(e=1,t=1,s=1,n=1)=>({r:e,g:t,b:s,a:n}),E=(e=1,t=0,s=0,n=0)=>({w:e,x:t,y:s,z:n});function M(e){if(null===e||"object"!=typeof e)return e;if(Array.isArray(e))return e.map(M);const t={};for(const s in e)t[s]=M(e[s]);return t}let R=0;function A(e,t){const s=++R;return{_id:Symbol(`Component_${s}_${e}`),_name:e,_default:t,_builtin:!1,create:e=>e?{...M(t),...e}:M(t)}}function I(){return"undefined"==typeof window?new Map:window.__esengine_componentRegistry??(window.__esengine_componentRegistry=new Map)}function F(e,t){const s=I(),n=s.get(e);if(n)return n;const r=A(e,t);return s.set(e,r),U(e,t,!1),r}function $(e){const t=I(),s=t.get(e);if(s)return s;const n=A(e,{});return t.set(e,n),U(e,{},!0),n}function k(e){return I().get(e)}function B(){I().clear()}function U(e,t,s){"undefined"!=typeof window&&window.__esengine_registerComponent&&window.__esengine_registerComponent(e,t,s)}function D(e){return!0===e._builtin}const z=new Map;function L(e,t){z.set(e,t)}function O(e){return z.get(e)??k(e)}function H(e,t){const s={_id:Symbol(`Builtin_${e}`),_name:e,_cppName:e,_builtin:!0,_default:t};return z.set(e,s),s}const W={Perspective:0,Orthographic:1},j={None:0,ColorOnly:1,DepthOnly:2,ColorAndDepth:3},N={FixedWidth:0,FixedHeight:1,Expand:2,Shrink:3,Match:4},V=H("LocalTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),X=H("WorldTransform",{position:{x:0,y:0,z:0},rotation:{w:1,x:0,y:0,z:0},scale:{x:1,y:1,z:1}}),Y=H("Sprite",{texture:v,color:{r:1,g:1,b:1,a:1},size:{x:32,y:32},uvOffset:{x:0,y:0},uvScale:{x:1,y:1},layer:0,flipX:!1,flipY:!1,material:0}),q=H("Camera",{projectionType:W.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:j.ColorAndDepth}),G=H("Canvas",{designResolution:{x:p,y:_},pixelsPerUnit:100,scaleMode:N.FixedHeight,matchWidthOrHeight:.5,backgroundColor:{r:0,g:0,b:0,a:1}}),J=H("Velocity",{linear:{x:0,y:0,z:0},angular:{x:0,y:0,z:0}}),K=H("Parent",{entity:0}),Q=H("Children",{entities:[]}),Z=H("BitmapText",{text:"",color:{r:1,g:1,b:1,a:1},fontSize:1,align:0,spacing:0,layer:0,font:b}),ee=H("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}),te={_id:Symbol("Component_Name"),_name:"Name",_default:{value:""},_builtin:!1,create:e=>({value:"",...e})},se=F("SceneOwner",{scene:"",persistent:!1});function ne(e){const t=O(e);return t?M(t._default):null}L("Name",te);const re=H("RigidBody",{bodyType:2,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,enabled:!0}),ie=H("BoxCollider",{halfExtents:{x:.5,y:.5},offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),oe=H("CircleCollider",{radius:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ae=H("CapsuleCollider",{radius:.25,halfHeight:.5,offset:{x:0,y:0},density:1,friction:.3,restitution:0,isSensor:!1}),ce={Static:0,Kinematic:1,Dynamic:2};let le=0;function he(e,t){const s=++le;return{_id:Symbol(`Resource_${s}_${t??""}`),_name:t??`Resource_${s}`,_default:e}}function ue(e){return{_type:"res",_resource:e}}function de(e){return{_type:"res_mut",_resource:e}}class fe{constructor(e,t){this.value_=e,this.setter_=t}get(){return this.value_}set(e){this.value_=e,this.setter_(e)}modify(e){e(this.value_),this.setter_(this.value_)}updateValue(e){this.value_=e}}class pe{constructor(){this.resources_=new Map,this.resMutPool_=new Map}insert(e,t){this.resources_.set(e._id,t)}get(e){return this.resources_.has(e._id)||this.resources_.set(e._id,e._default),this.resources_.get(e._id)}set(e,t){this.resources_.set(e._id,t)}has(e){return this.resources_.has(e._id)}remove(e){this.resources_.delete(e._id),this.resMutPool_.delete(e._id)}getResMut(e){let t=this.resMutPool_.get(e._id);return t?(t.updateValue(this.get(e)),t):(t=new fe(this.get(e),t=>this.set(e,t)),this.resMutPool_.set(e._id,t),t)}}const _e=he({delta:0,elapsed:0,frameCount:0},"Time");function me(e){return{_type:"mut",_component:e}}function ge(e){return"object"==typeof e&&null!==e&&"_type"in e&&"mut"===e._type}function ye(...e){return function(e,t=[],s=[]){const n=[];return e.forEach((e,t)=>{ge(e)&&n.push(t)}),{_type:"query",_components:e,_mutIndices:n,_with:t,_without:s}}(e)}class we{constructor(e,t){this.world_=e,this.descriptor_=t,this.actualComponents_=t._components.map(e=>ge(e)?e._component:e),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}))}*[Symbol.iterator](){const{_mutIndices:e,_without:t}=this.descriptor_,s=this.actualComponents_,n=this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,this.descriptor_._without),r=s.length,i=e.length>0,o=t.length>0,a=this.result_,c=this.mutData_,l=c.length;let h=null;this.world_.beginIteration();try{for(const u of n){if(null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,t.component,t.data)}if(o){let e=!1;for(let s=0;s<t.length;s++)if(this.world_.has(u,t[s])){e=!0;break}if(e)continue}a[0]=u;for(let e=0;e<r;e++)a[e+1]=this.world_.get(u,s[e]);if(i){for(let t=0;t<l;t++)c[t].data=a[e[t]+1];h=u}yield a}}finally{if(this.world_.endIteration(),null!==h&&i)for(let e=0;e<l;e++){const t=c[e];this.world_.insert(h,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(){let e=0;for(const t of this)e++;return e}toArray(){const e=[];for(const t of this)e.push([...t]);return e}}function xe(){return{_type:"commands"}}class ve{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=D(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 be{constructor(e,t){this.pending_=[],this.spawned_=[],this.world_=e,this.resources_=t}spawn(){const e=new ve(this,null);return this.spawned_.push(e),e}entity(e){return new ve(this,e)}despawn(e){return this.pending_.push({type:"despawn",entity:e}),this}insertResource(e,t){return this.pending_.push({type:"insert_resource",resource:e,value:t}),this}queueInsert(e,t,s){this.pending_.push({type:"insert",entity:e,component:t,data:s})}queueRemove(e,t){this.pending_.push({type:"remove",entity:e,component:t})}spawnImmediate(e,t){const s=this.world_.spawn();t.entity=s;for(const t of e)this.world_.insert(s,t.component,t.data)}flush(){for(const e of this.spawned_)e.finalize();this.spawned_.length=0;for(const e of this.pending_)this.executeCommand(e);this.pending_.length=0}executeCommand(e){switch(e.type){case"spawn":{const t=this.world_.spawn();e.entityRef.entity=t;for(const s of e.components)this.world_.insert(t,s.component,s.data);break}case"despawn":if(!this.world_.valid(e.entity)){console.warn(`[Commands] despawn skipped: entity ${e.entity} is already invalid`);break}this.world_.despawn(e.entity);break;case"insert":if(!this.world_.valid(e.entity)){console.warn(`[Commands] insert skipped: entity ${e.entity} is invalid`);break}this.world_.insert(e.entity,e.component,e.data);break;case"remove":if(!this.world_.valid(e.entity)){console.warn(`[Commands] remove skipped: entity ${e.entity} is invalid`);break}this.world_.remove(e.entity,e.component);break;case"insert_resource":this.resources_.insert(e.resource,e.value)}}}var Se;!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"}(Se||(Se={}));let Pe=0;function Ce(e,t,s){const n=++Pe;return{_id:Symbol(`System_${n}_${s?.name??""}`),_params:e,_fn:t,_name:s?.name??`System_${n}`}}function Te(){return"undefined"==typeof window?[]:window.__esengine_pendingSystems??(window.__esengine_pendingSystems=[])}function Ee(e){Te().push({schedule:Se.Update,system:e})}function Me(e){Te().push({schedule:Se.Startup,system:e})}function Re(e,t){Te().push({schedule:e,system:t})}class Ae{constructor(e,t){this.argsCache_=new Map,this.world_=e,this.resources_=t}run(e){let t=this.argsCache_.get(e._id);t||(t=new Array(e._params.length),this.argsCache_.set(e._id,t));for(let s=0;s<e._params.length;s++)t[s]=this.resolveParam(e._params[s]);try{e._fn(...t);for(let e=0;e<t.length;e++)t[e]instanceof be&&t[e].flush()}finally{this.world_.resetIterationDepth()}}resolveParam(e){switch(e._type){case"query":return new we(this.world_,e);case"res":return this.resources_.get(e._resource);case"res_mut":return this.resources_.getResMut(e._resource);case"commands":return new be(this.world_,this.resources_);default:throw new Error("Unknown system parameter type")}}}class Ie{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 Fe=he(new Ie,"Input");class $e{constructor(e){this.target_=e??null}build(e){const s=new Ie;e.insertResource(Fe,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(Se.Last,Ce([],()=>{s.keysPressed.clear(),s.keysReleased.clear(),s.mouseButtonsPressed.clear(),s.mouseButtonsReleased.clear(),s.scrollDeltaX=0,s.scrollDeltaY=0},{name:"InputClearSystem"}))}}const ke=new $e;function Be(e,t,s){const n=[];for(const[e,r]of Object.entries(s)){if(!(e in t)){n.push({field:e,expected:"field to exist in component definition",actual:"unknown field",value:r});continue}const s=Ue(t[e]),i=Ue(r);"null"!==s&&"undefined"!==s&&(s!==i&&null!=r&&n.push({field:e,expected:s,actual:i,value:r}))}return n}function Ue(e){return null===e?"null":void 0===e?"undefined":Array.isArray(e)?"array":typeof e}function De(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 ze=null;function Le(e){ze=e}function Oe(e,t){console.error(`[ESEngine] WASM error in ${t}:`,e),ze&&ze(e,t)}function He(e){const t={};for(const s of Object.keys(e)){const n=e[s];if(null==n||"object"!=typeof n||Array.isArray(n))t[s]=n;else{const e=n;t[s]="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}:He(e)}}return t}class We{constructor(){this.cppRegistry_=null,this.entities_=new Set,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}connectCpp(e){this.cppRegistry_=e,this.builtinMethodCache_.clear()}disconnectCpp(){this.cppRegistry_=null,this.builtinMethodCache_.clear()}get hasCpp(){return null!==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 Oe(e,"spawn"),e}else e=this.entities_.size+1;return this.entities_.add(e),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.");if(this.cppRegistry_)try{this.cppRegistry_.destroy(e)}catch(t){Oe(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.entityComponents_.delete(e)}}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&&(this.iterationDepth_=0)}resetIterationDepth(){this.iterationDepth_=0}isIterating(){return this.iterationDepth_>0}getAllEntities(){return Array.from(this.entities_)}setParent(e,t){if(this.cppRegistry_)try{this.cppRegistry_.setParent(e,t)}catch(s){Oe(s,`setParent(child=${e}, parent=${t})`)}}removeParent(e){if(this.cppRegistry_)try{this.cppRegistry_.removeParent(e)}catch(t){Oe(t,`removeParent(entity=${e})`)}}insert(e,t,s){return D(t)?this.insertBuiltin(e,t,s):this.insertScript(e,t,s)}get(e,t){return D(t)?this.getBuiltin(e,t):this.getScript(e,t)}has(e,t){return D(t)?this.hasBuiltin(e,t):this.hasScript(e,t)}tryGet(e,t){if(D(t)){if(!this.cppRegistry_)return null;try{const s=this.getBuiltinMethods(t._cppName);return s.has(e)?s.get(e):null}catch(s){return Oe(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.");D(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_;return t={add:s[`add${e}`].bind(s),get:s[`get${e}`].bind(s),has:s[`has${e}`].bind(s),remove:s[`remove${e}`].bind(s)},this.builtinMethodCache_.set(e,t),t}insertBuiltin(e,t,s){const n={};if(null!=s&&"object"==typeof s){for(const[e,t]of Object.entries(s))void 0!==t&&(n[e]=t);const e=Be(t._name,t._default,n);if(e.length>0)throw new Error(De(t._name,e))}const r={...t._default,...n};if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).add(e,He(r))}catch(s){Oe(s,`insertBuiltin(${t._name}, entity=${e})`)}return r}getBuiltin(e,t){if(!this.cppRegistry_)throw new Error("C++ Registry not connected");try{return this.getBuiltinMethods(t._cppName).get(e)}catch(s){return Oe(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 Oe(s,`hasBuiltin(${t._name}, entity=${e})`),!1}}removeBuiltin(e,t){if(this.cppRegistry_)try{this.getBuiltinMethods(t._cppName).remove(e)}catch(s){Oe(s,`removeBuiltin(${t._name}, entity=${e})`)}}insertScript(e,t,s){let n;if(null!=s&&"object"==typeof s){const e={};for(const[t,n]of Object.entries(s))void 0!==n&&(e[t]=n);const r=Be(t._name,t._default,e);if(r.length>0)throw new Error(De(t._name,r));n=e}const r=t.create(n);this.getStorage(t).set(e,r),this.worldVersion_++;let i=this.entityComponents_.get(e);return i||(i=[],this.entityComponents_.set(e,i)),-1===i.indexOf(t._id)&&i.push(t._id),r}getScript(e,t){const s=this.tsStorage_.get(t._id);if(!s)throw new Error(`Component not found: ${t._name}`);return s.get(e)}hasScript(e,t){const s=this.tsStorage_.get(t._id);return s?.has(e)??!1}removeScript(e,t){const s=this.tsStorage_.get(t._id);s?.delete(e),this.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,this.queryCache_.clear()}getComponentTypes(e){const t=[];for(const[s,n]of this.builtinMethodCache_)try{n.has(e)&&t.push(s)}catch{}if(this.cppRegistry_)for(const[s,n]of z)if(D(n)&&!t.includes(s))try{this.getBuiltinMethods(n._cppName).has(e)&&t.push(s)}catch{}const s=this.entityComponents_.get(e);if(s){const e="undefined"!=typeof window?window.__esengine_componentRegistry:void 0;if(e)for(const n of s)for(const[s,r]of e)if(r._id===n){t.push(s);break}}return t}getEntitiesWithComponents(e,t=[],s=[]){if(0===e.length&&0===t.length&&0===s.length)return this.getAllEntities();let n=e.map(e=>e._name).sort().join(",");t.length>0&&(n+="|+"+t.map(e=>e._name).sort().join(",")),s.length>0&&(n+="|-"+s.map(e=>e._name).sort().join(","));const r=this.queryCache_.get(n);if(r&&r.version===this.worldVersion_)return r.result;let i=null,o=1/0;for(const t of e)if(!D(t)){const e=this.tsStorage_.get(t._id),s=e?e.size:0;s<o&&(o=s,i=e??null)}this.queryPoolIdx_>=this.queryPool_.length&&this.queryPool_.push([]);const a=this.queryPool_[this.queryPoolIdx_++];a.length=0;const c=i?i.keys():this.entities_;for(const t of c){let s=!0;for(const n of e)if(!this.has(t,n)){s=!1;break}s&&a.push(t)}return this.queryCache_.set(n,{version:this.worldVersion_,result:a}),a}}const je=he({viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1},"UICameraInfo");var Ne;function Ve(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"}(Ne||(Ne={}));let Xe=null,Ye=null,qe=1;const Ge=new Map;function Je(e){Xe=e,Ye=e.getResourceManager(),ot()}function Ke(){0!==tt&&Xe&&(Xe._free(tt),tt=0),Ge.clear(),qe=1,et=!1,nt.clear(),rt=null,Ye=null,Xe=null}function Qe(){if(!Ye)throw new Error("Material API not initialized. Call initMaterialAPI() first.");return Ye}const Ze={createShader:(e,t)=>Qe().createShader(e,t),releaseShader(e){e>0&&Qe().releaseShader(e)},create(e){const t=qe++,s={shader:e.shader,uniforms:new Map,blendMode:e.blendMode??Ne.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 Ge.set(t,s),t},get:e=>Ge.get(e),setUniform(e,t,s){const n=Ge.get(e);n&&(n.uniforms.set(t,s),n.dirty_=!0)},getUniform(e,t){const s=Ge.get(e);return s?.uniforms.get(t)},setBlendMode(e,t){const s=Ge.get(e);s&&(s.blendMode=t)},getBlendMode(e){const t=Ge.get(e);return t?.blendMode??Ne.Normal},setDepthTest(e,t){const s=Ge.get(e);s&&(s.depthTest=t)},getShader(e){const t=Ge.get(e);return t?.shader??0},release(e){Ge.delete(e)},isValid:e=>Ge.has(e),releaseAll(){Ge.clear()},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??Ne.Normal,depthTest:e.depthTest??!1})},createInstance(e){const t=Ge.get(e);if(!t)throw new Error(`Invalid source material: ${e}`);const s=qe++,n={shader:t.shader,uniforms:new Map(t.uniforms),blendMode:t.blendMode,depthTest:t.depthTest,dirty_:!0,cachedBuffer_:null,cachedIdx_:0};return Ge.set(s,n),s},toAssetData(e,t){const s=Ge.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=Ge.get(e);return t?new Map(t.uniforms):new Map},tex:(e,t)=>({__textureRef:!0,textureId:e,slot:t})};let et=!1,tt=0;const st=4096,nt=new Map;let rt=null;function it(e){const t=(0===tt&&Xe&&(tt=Xe._malloc(st)),tt);if(0===t||!Xe)return{ptr:0,count:0};let s=0,n=0;const r=Xe.HEAPU8,i=Xe.HEAPU32,o=Xe.HEAPF32;for(const[a,c]of e){if(s+128>st)break;let e=nt.get(a);e||(rt||(rt=new TextEncoder),e=rt.encode(a),nt.set(a,e));const l=e.length,h=4*Math.ceil(l/4);i[t+s>>2]=l,s+=4,r.set(e,t+s),s+=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 e=0;e<Math.min(c.length,4);e++)d[e]=c[e]}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]);i[t+s>>2]=u,s+=4;for(let e=0;e<4;e++)o[t+s>>2]=d[e],s+=4;n++}return{ptr:t,count:n}}function ot(){if(!Xe||et)return;Xe.materialDataProvider=(e,t,s,n,r)=>{const i=Ge.get(e);if(!i)return Xe.HEAPU32[t>>2]=0,Xe.HEAPU32[s>>2]=0,Xe.HEAPU32[n>>2]=0,void(Xe.HEAPU32[r>>2]=0);Xe.HEAPU32[t>>2]=i.shader,Xe.HEAPU32[s>>2]=i.blendMode;const{ptr:o,count:a}=it(i.uniforms);Xe.HEAPU32[n>>2]=o,Xe.HEAPU32[r>>2]=a},et=!0}const at={SPRITE_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\nout vec2 v_texCoord;\n\nvoid main() {\n v_color = a_color;\n v_texCoord = a_texCoord;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",SPRITE_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\nin vec2 v_texCoord;\n\nuniform sampler2D u_texture;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = texture(u_texture, v_texCoord) * v_color;\n}\n",COLOR_VERTEX:"#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\n\nuniform mat4 u_projection;\nuniform mat4 u_model;\n\nout vec4 v_color;\n\nvoid main() {\n v_color = a_color;\n gl_Position = u_projection * u_model * vec4(a_position, 1.0);\n}\n",COLOR_FRAGMENT:"#version 300 es\nprecision highp float;\n\nin vec4 v_color;\n\nout vec4 fragColor;\n\nvoid main() {\n fragColor = v_color;\n}\n"};class ct{constructor(){this.cache_=new Map,this.pending_=new Map}async getOrLoad(e,t,s=3e4){const n=this.cache_.get(e);if(void 0!==n)return n;const r=this.pending_.get(e);if(r&&!r.aborted)return r.promise;const i={promise:null,aborted:!1};i.promise=(async()=>{const n=t(),r=await(s>0?Promise.race([n,new Promise((t,n)=>setTimeout(()=>{i.aborted=!0,n(new Error(`AsyncCache timeout: ${e} (${s}ms)`))},s))]):n);return i.aborted||this.cache_.set(e,r),this.pending_.delete(e),r})(),this.pending_.set(e,i);try{return await i.promise}catch(t){throw this.pending_.delete(e),t instanceof Error&&t.message.startsWith("AsyncCache timeout:")&&console.warn(`[AsyncCache] ${t.message}`),t}}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}delete(e){return this.cache_.delete(e)}clear(){this.cache_.clear()}clearAll(){this.cache_.clear();for(const e of this.pending_.values())e.aborted=!0;this.pending_.clear()}values(){return this.cache_.values()}}class lt{constructor(e,t=""){this.cache_=new ct,this.shaderLoader_=e,this.basePath_=t}async load(e){return this.cache_.getOrLoad(e,()=>this.loadInternal(e),0)}get(e){return this.cache_.get(e)}has(e){return this.cache_.has(e)}release(e){const t=this.cache_.get(e);t&&(Ze.release(t.handle),this.cache_.delete(e))}releaseAll(){for(const e of this.cache_.values())Ze.release(e.handle);this.cache_.clear()}async loadInternal(e){const t=this.resolvePath(e);if(!await l(t))throw new Error(`Material file not found: ${t}`);const s=await c(t);if(!s)throw new Error(`Failed to read material file: ${t}`);const n=JSON.parse(s);if("material"!==n.type)throw new Error(`Invalid material file type: ${n.type}`);const r=this.resolveShaderPath(e,n.shader),i=await this.shaderLoader_.load(r);return{handle:Ze.createFromAsset(n,i),shaderHandle:i,path:e}}resolvePath(e){return e.startsWith("/")||e.startsWith("http")?e:this.basePath_?`${this.basePath_}/${e}`:e}resolveShaderPath(e,t){if(t.startsWith("/")||t.startsWith("http")||t.startsWith("assets/"))return t;const s=e.substring(0,e.lastIndexOf("/"));return s?`${s}/${t}`:t}}const ht=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"}]}]]);function ut(e,t){ht.set(e,t)}function dt(e){const t=ht.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 ft(e){return ht.get(e)?.fields??[]}function pt(e,t){const s=new Map;for(const n of t.entities){const t=e.spawn();if(s.set(n.id,t),e.insert(t,te,{value:n.name}),!1!==n.visible)for(const s of n.components)mt(e,t,s,n.name)}for(const n of t.entities)if(null!==n.parent){const t=s.get(n.id),r=s.get(n.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}return s}async function _t(e,t,s){const n=new Map,r=s?.assetServer,i=s?.assetBaseUrl,o=new Map;r&&await async function(e,t,s,n){e=JSON.parse(JSON.stringify(e));const r=new Set,i=new Set,o=new Set,a=[],c=new Set;for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.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}`;c.has(t)||(c.add(t),a.push({skeleton:e,atlas:n}))}}if(t.fields)for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":r.add(t);break;case"material":i.add(t);break;case"font":o.add(t)}}}const l=new Map,h=new Map,u=new Map,d=[];for(const e of r)d.push((async()=>{try{const r=e.startsWith("data:")?e:s?`${s}/${e}`:`/${e}`,i=await t.loadTexture(r);l.set(e,i.handle),n.set(e,r)}catch(t){console.warn(`Failed to load texture: ${e}`,t),l.set(e,0)}})());for(const e of i)d.push((async()=>{try{const n=await t.loadMaterial(e,s);h.set(e,n.handle)}catch(t){console.warn(`Failed to load material: ${e}`,t),h.set(e,0)}})());for(const e of o)d.push((async()=>{try{const n=await t.loadBitmapFont(e,s);u.set(e,n)}catch(t){console.warn(`Failed to load bitmap font: ${e}`,t),u.set(e,0)}})());for(const e of a)d.push((async()=>{const n=await t.loadSpine(e.skeleton,e.atlas,s);n.success||console.warn(`Failed to load Spine: ${n.error}`)})());await Promise.all(d);for(const t of e.entities)if(!1!==t.visible)for(const e of t.components){const t=ht.get(e.type);if(!t?.fields)continue;const s=e.data;for(const e of t.fields){const t=s[e.field];if("string"==typeof t&&t)switch(e.type){case"texture":s[e.field]=l.get(t)??0;break;case"material":s[e.field]=h.get(t)??0;break;case"font":s[e.field]=u.get(t)??0}}}}(t,r,i,o);for(const s of t.entities){const t=e.spawn();if(n.set(s.id,t),e.insert(t,te,{value:s.name}),!1!==s.visible)for(const n of s.components)mt(e,t,n,s.name)}for(const s of t.entities)if(null!==s.parent){const t=n.get(s.id),r=n.get(s.parent);void 0!==t&&void 0!==r&&e.setParent(t,r)}if(r&&t.textureMetadata)for(const[e,s]of Object.entries(t.textureMetadata)){const t=o.get(e);t&&s.sliceBorder&&r.setTextureMetadataByPath(t,s.sliceBorder)}return n}function mt(e,t,s,n){if("UIRect"===s.type){const e=s.data;e.anchor&&!e.anchorMin&&(e.anchorMin={...e.anchor},e.anchorMax={...e.anchor},delete e.anchor)}const r=O(s.type);if(r)e.insert(t,r,s.data);else{const e=n?` on entity "${n}"`:"";console.warn(`Unknown component type: ${s.type}${e}`)}}function gt(e,t){const s=e.getEntitiesWithComponents([q]);for(const n of s){const s=e.get(n,q);s&&(s.aspectRatio=t,e.insert(n,q,s))}}function yt(e,t){const s=e.getEntitiesWithComponents([te]);for(const n of s){const s=e.get(n,te);if(s&&s.value===t)return n}return null}const wt=[{extensions:["png","jpg","jpeg","gif","webp","svg"],contentType:"image",editorType:"texture",addressableType:"texture",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["mp3","wav","ogg"],contentType:"audio",editorType:"audio",addressableType:"audio",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["esmaterial"],contentType:"json",editorType:"material",addressableType:"material",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esshader"],contentType:"text",editorType:"shader",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["atlas"],contentType:"text",editorType:"spine-atlas",addressableType:"binary",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["skel"],contentType:"binary",editorType:"spine-skeleton",addressableType:"spine",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["json"],contentType:"json",editorType:"json",addressableType:"json",wechatPackInclude:!1,hasTransitiveDeps:!1},{extensions:["bmfont"],contentType:"json",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["fnt"],contentType:"text",editorType:"bitmap-font",addressableType:"bitmap-font",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esprefab"],contentType:"json",editorType:"prefab",addressableType:"prefab",wechatPackInclude:!0,hasTransitiveDeps:!0},{extensions:["esscene"],contentType:"json",editorType:"scene",addressableType:null,wechatPackInclude:!1,hasTransitiveDeps:!1}],xt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",json:"application/json",atlas:"text/plain",skel:"application/octet-stream",esmaterial:"application/json",esshader:"text/plain",esprefab:"application/json",bmfont:"application/json",fnt:"text/plain"},vt=new Map,bt=new Set;for(const e of wt)for(const t of e.extensions)vt.set(t,e),bt.add(t);function St(e){const t=e.lastIndexOf(".");return t>=0?e.substring(t+1).toLowerCase():e.toLowerCase()}function Pt(e){return vt.get(St(e))}function Ct(e){return Pt(e)?.editorType??"unknown"}function Tt(e){return Pt(e)?.addressableType??null}function Et(e){for(const t of wt)if(t.editorType===e)return t.addressableType;return"text"===e?"text":"binary"}function Mt(e){return bt.has(e.toLowerCase())}function Rt(){return bt}function At(e){return"string"==typeof e&&(!!e.includes("/")&&Mt(St(e)))}function It(){const e=[];for(const t of wt)if(t.wechatPackInclude)for(const s of t.extensions)e.push(`.${s}`);return e}function Ft(){return It().map(e=>({type:"suffix",value:e}))}function $t(e){return xt[e.toLowerCase()]}function kt(e){const t=Pt(e);return t?.wechatPackInclude??!1}class Bt{constructor(e){this.textureCache_=new ct,this.shaderCache_=new ct,this.jsonCache_=new ct,this.textCache_=new ct,this.binaryCache_=new ct,this.loadedSpines_=new Set,this.virtualFSPaths_=new Set,this.fontCache_=new ct,this.prefabCache_=new ct,this.embedded_=new Map,this.embeddedOnly_=!1,this.addressableManifest_=null,this.addressIndex_=new Map,this.labelIndex_=new Map,this.groupAssets_=new Map,this.spineController_=null,this.spineSkeletons_=new Map,this.textureRefCounts_=new Map,this.module_=e,this.canvas_=u(y.textCanvasSize,y.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 lt(t)}registerEmbeddedAssets(e){for(const[t,s]of Object.entries(e))this.embedded_.set(t,s);this.embeddedOnly_||(this.embeddedOnly_="undefined"!=typeof location&&"file:"===location.protocol)}setEmbeddedOnly(e){this.embeddedOnly_=e}async loadTexture(e){return this.loadTextureWithFlip(e,!0)}async loadTextureRaw(e){return this.loadTextureWithFlip(e,!1)}getTexture(e){return this.textureCache_.get(this.textureCacheKey(e,!0))}hasTexture(e){return this.textureCache_.has(this.textureCacheKey(e,!0))}getTextureRefCount(e){let t=0;for(const s of[!0,!1])t+=this.textureRefCounts_.get(this.textureCacheKey(e,s))??0;return t}releaseTexture(e){const t=this.module_.getResourceManager();for(const s of[!0,!1]){const n=this.textureCacheKey(e,s),r=this.textureCache_.get(n);if(!r)continue;const i=(this.textureRefCounts_.get(n)??1)-1;i<=0?(t.releaseTexture(r.handle),this.textureCache_.delete(n),this.textureRefCounts_.delete(n)):this.textureRefCounts_.set(n,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(),Ze.releaseAll(),this.textureCache_.clearAll(),this.textureRefCounts_.clear(),this.shaderCache_.clearAll(),this.fontCache_.clearAll(),this.prefabCache_.clearAll(),this.jsonCache_.clearAll(),this.textCache_.clearAll(),this.binaryCache_.clearAll(),this.loadedSpines_.clear(),this.spineController_)for(const e of this.spineSkeletons_.values())this.spineController_.unloadSkeleton(e);this.spineSkeletons_.clear(),this.cleanupVirtualFS()}cleanupVirtualFS(){const e=this.module_.FS;if(e){for(const t of this.virtualFSPaths_)try{e.unlink(t)}catch{}this.virtualFSPaths_.clear()}}setTextureMetadata(e,t){this.module_.getResourceManager().setTextureMetadata(e,t.left,t.right,t.top,t.bottom)}setTextureMetadataByPath(e,t){const s=this.textureCache_.get(this.textureCacheKey(e,!0));return!!s&&(this.setTextureMetadata(s.handle,t),!0)}setSpineController(e){this.spineController_=e}getSpineSkeletonHandle(e,t){return this.spineSkeletons_.get(`${e}:${t}`)}async loadSpine(e,t,s){const n=`${e}:${t}`;if(this.loadedSpines_.has(n))return{success:!0};try{const r=this.resolveUrl(t,s),i=await this.fetchText(r);if(!this.writeToVirtualFS(t,i))return{success:!1,error:`Failed to write atlas to virtual FS: ${t}`};const o=t.substring(0,t.lastIndexOf("/")),a=this.parseAtlasTextures(i),c=[];for(const e of a){const t=o?`${o}/${e}`:e,n=this.resolveUrl(t,s);try{const s=await this.loadTextureRaw(n);this.module_.getResourceManager().registerTextureWithPath(s.handle,t),c.push({name:e,info:s})}catch(e){console.warn(`[AssetServer] Failed to load Spine texture: ${t}`,e)}}const l=this.resolveUrl(e,s),h="binary"===Pt(e)?.contentType,u=h?new Uint8Array(await this.fetchBinary(l)):await this.fetchText(l);if(!this.writeToVirtualFS(e,u))return{success:!1,error:`Failed to write skeleton to virtual FS: ${e}`};if(this.loadedSpines_.add(n),this.spineController_){const e=this.spineController_.loadSkeleton(u,i,h);if(e>=0){const t=this.module_.getResourceManager(),s=this.spineController_.getAtlasPageCount(e);for(let n=0;n<s;n++){const s=this.spineController_.getAtlasPageTextureName(e,n),r=c.find(e=>e.name===s);if(r){const s=t.getTextureGLId(r.info.handle);this.spineController_.setAtlasPageTexture(e,n,s,r.info.width,r.info.height)}}this.spineSkeletons_.set(n,e)}}return{success:!0}}catch(e){return{success:!1,error:String(e)}}}isSpineLoaded(e,t){return this.loadedSpines_.has(`${e}:${t}`)}async loadBitmapFont(e,t){const s=this.resolveUrl(e,t);return this.fontCache_.getOrLoad(s,async()=>{const t=Pt(e);return"bitmap-font"===t?.editorType&&"json"===t.contentType?this.loadBmfontAsset(s):this.loadFntFile(s)})}getFont(e){return this.fontCache_.get(e)}releaseFont(e){const t=this.fontCache_.get(e);if(t){this.module_.getResourceManager().releaseBitmapFont(t),this.fontCache_.delete(e)}}async loadBmfontAsset(e){const t=await this.fetchJson(e),s=e.substring(0,e.lastIndexOf("/")),n="label-atlas"===t.type?t.generatedFnt:t.fntFile;if(!n)throw new Error("Invalid bmfont asset: no fnt file specified");const r=s?`${s}/${n}`:n;return this.loadFntFile(r)}async loadFntFile(e){const t=await this.fetchText(e),s=t.match(/file="([^"]+)"/);if(!s)throw new Error(`No page texture found in .fnt file: ${e}`);const n=s[1],r=e.substring(0,e.lastIndexOf("/")),i=r?`${r}/${n}`:n,o=await this.loadTextureRaw(i);return this.module_.getResourceManager().loadBitmapFont(t,o.handle,o.width,o.height)}async loadPrefab(e,t){const s=this.resolveUrl(e,t);return this.prefabCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadMaterial(e,t){return this.materialLoader_.load(this.resolveUrl(e,t))}getMaterial(e,t){return this.materialLoader_.get(this.resolveUrl(e,t))}hasMaterial(e,t){return this.materialLoader_.has(this.resolveUrl(e,t))}async loadShader(e){return this.shaderCache_.getOrLoad(e,()=>this.loadShaderInternal(e))}async loadJson(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchJson(s):this.jsonCache_.getOrLoad(s,()=>this.fetchJson(s))}async loadText(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchText(s):this.textCache_.getOrLoad(s,()=>this.fetchText(s))}async loadBinary(e,t){const s=this.resolveUrl(e,t?.baseUrl);return t?.noCache?this.fetchBinary(s):this.binaryCache_.getOrLoad(s,()=>this.fetchBinary(s))}async loadScene(e,t){return _t(e,t,{assetServer:this})}async loadAll(e){this.setAddressableManifest(e);const t=[];if(e.groups)for(const s of Object.values(e.groups))s.assets&&t.push(...Object.values(s.assets));return this.loadAddressableAssets(t)}setAddressableManifest(e){this.addressableManifest_=e,this.addressIndex_.clear(),this.labelIndex_.clear(),this.groupAssets_.clear();for(const[t,s]of Object.entries(e.groups||{})){const e=[];for(const t of Object.values(s.assets)){e.push(t),t.address&&this.addressIndex_.set(t.address,t);for(const e of t.labels){let s=this.labelIndex_.get(e);s||(s=[],this.labelIndex_.set(e,s)),s.push(t)}}this.groupAssets_.set(t,e)}}resolveAddress(e){return this.addressIndex_.get(e)}async load(e){const t=this.addressIndex_.get(e);if(!t)throw new Error(`No asset found with address: ${e}`);return this.loadAddressableAsset(t)}async loadByLabel(e){const t=this.labelIndex_.get(e)??[];return this.loadAddressableAssets(t)}async loadGroup(e){const t=this.groupAssets_.get(e)??[];return this.loadAddressableAssets(t)}async loadAddressableAsset(e){switch(e.type){case"texture":return this.loadTexture(e.path);case"material":return this.loadMaterial(e.path);case"spine":{const t=e.metadata?.atlas;if(!t)throw new Error(`Spine asset missing atlas metadata: ${e.path}`);return this.loadSpine(e.path,t)}case"bitmap-font":return this.loadBitmapFont(e.path);case"prefab":return this.loadPrefab(e.path);case"audio":case"binary":default:return this.loadBinary(e.path);case"json":return this.loadJson(e.path);case"text":return this.loadText(e.path)}}async loadAddressableAssets(e){const t={textures:new Map,materials:new Map,spine:new Map,fonts:new Map,prefabs:new Map,json:new Map,text:new Map,binary:new Map},s=[];for(const n of e){const e=n.address??n.path;switch(n.type){case"texture":s.push(this.loadTexture(n.path).then(s=>{t.textures.set(e,s)}));break;case"material":s.push(this.loadMaterial(n.path).then(s=>{t.materials.set(e,s)}));break;case"spine":{const r=n.metadata?.atlas;r&&s.push(this.loadSpine(n.path,r).then(s=>{t.spine.set(e,s)}));break}case"bitmap-font":s.push(this.loadBitmapFont(n.path).then(s=>{t.fonts.set(e,s)}));break;case"prefab":s.push(this.loadPrefab(n.path).then(s=>{t.prefabs.set(e,s)}));break;case"audio":case"binary":default:s.push(this.loadBinary(n.path).then(s=>{t.binary.set(e,s)}));break;case"json":s.push(this.loadJson(n.path).then(s=>{t.json.set(e,s)}));break;case"text":s.push(this.loadText(n.path).then(s=>{t.text.set(e,s)}))}}const n=await Promise.allSettled(s);for(const e of n)"rejected"===e.status&&console.warn("[AssetServer] Failed to load asset:",e.reason);return t}textureCacheKey(e,t){return`${e}:${t?"f":"n"}`}async loadTextureWithFlip(e,t){const s=this.textureCacheKey(e,t),n=await this.textureCache_.getOrLoad(s,()=>this.loadTextureInternal(e,t));return this.textureRefCounts_.set(s,(this.textureRefCounts_.get(s)??0)+1),n}async loadTextureInternal(e,t){const s=await this.loadImage(e);return this.createTextureFromImage(s,t)}async loadImage(e){const s=this.isLocalPath(e)?this.toLocalPath(e):e,n=this.embedded_.get(s);if(this.embeddedOnly_&&!n)throw new Error(`Asset not embedded: ${e}`);const r=n??s;return new Promise((s,n)=>{const 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=r})}createTextureFromImage(e,t){const{width:s,height:n}=e,r=this.getWebGL2Context();return r?this.createTextureWebGL2(r,e,s,n,t):this.createTextureFallback(e,s,n,t)}getWebGL2Context(){try{const e=this.module_.GL;if(e&&e.currentContext&&e.currentContext.GLctx){const t=e.currentContext.GLctx;if(t instanceof WebGL2RenderingContext)return t}}catch{}return null}createTextureWebGL2(e,t,s,n,r){const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,r?1:0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT),e.generateMipmap(e.TEXTURE_2D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0);const o=this.module_.GL,a=o.getNewId(o.textures);o.textures[a]=i;return{handle:this.module_.getResourceManager().registerExternalTexture(a,s,n),width:s,height:n}}createTextureFallback(e,t,s,n){(this.canvas_.width<t||this.canvas_.height<s)&&(this.canvas_.width=Math.max(this.canvas_.width,this.nextPowerOf2(t)),this.canvas_.height=Math.max(this.canvas_.height,this.nextPowerOf2(s))),this.ctx_.clearRect(0,0,this.canvas_.width,this.canvas_.height),this.ctx_.drawImage(e,0,0);const r=this.ctx_.getImageData(0,0,t,s),i=new Uint8Array(r.data.buffer);this.unpremultiplyAlpha(i);const o=this.module_.getResourceManager(),a=this.module_._malloc(i.length);this.module_.HEAPU8.set(i,a);const c=o.createTexture(t,s,a,i.length,1,n);return this.module_._free(a),{handle:c,width:t,height:s}}unpremultiplyAlpha(e){for(let t=0;t<e.length;t+=4){const s=e[t+3];if(s>0&&s<255){const n=255/s;e[t]=Math.min(255,Math.round(e[t]*n)),e[t+1]=Math.min(255,Math.round(e[t+1]*n)),e[t+2]=Math.min(255,Math.round(e[t+2]*n))}}}async loadShaderInternal(e){const t=this.isLocalPath(e)?this.toLocalPath(e):e,s=this.embedded_.get(t);if(s){const t=this.decodeDataUrlText(s),{vertex:n,fragment:r}=this.parseEsShader(t);if(!n||!r)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(n,r)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);if(!await l(t))throw new Error(`Shader file not found: ${e}`);const n=await c(t);if(!n)throw new Error(`Failed to read shader file: ${e}`);const{vertex:r,fragment:i}=this.parseEsShader(n);if(!r||!i)throw new Error(`Invalid shader format: ${e}`);return Ze.createShader(r,i)}parseEsShader(e){const t=e.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/),s=e.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);return{vertex:t?.[1].trim()??null,fragment:s?.[1].trim()??null}}decodeDataUrlText(e){return atob(e.split(",")[1])}decodeDataUrlBinary(e){const t=atob(e.split(",")[1]),s=new Uint8Array(t.length);for(let e=0;e<t.length;e++)s[e]=t.charCodeAt(e);return s.buffer}isLocalPath(e){return!e.startsWith("http://")&&!e.startsWith("https://")}toLocalPath(e){return e.startsWith("/")?e.substring(1):e}async fetchJson(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return JSON.parse(this.decodeDataUrlText(s));if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const n=await c(t);return JSON.parse(n)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch JSON: ${e} (${s.status})`);return s.json()}async fetchText(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlText(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return c(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch text: ${e} (${s.status})`);return s.text()}async fetchBinary(e){const t=this.isLocalPath(e)?this.toLocalPath(e):null;if(t){const s=this.embedded_.get(t);if(s)return this.decodeDataUrlBinary(s);if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);return a(t)}if(this.embeddedOnly_)throw new Error(`Asset not embedded: ${e}`);const s=await o(e);if(!s.ok)throw new Error(`Failed to fetch binary: ${e} (${s.status})`);return s.arrayBuffer()}writeToVirtualFS(e,t){if(this.virtualFSPaths_.has(e))return!0;const s=this.module_.FS;if(!s)return!1;try{return this.ensureVirtualDir(e),s.writeFile(e,t),this.virtualFSPaths_.add(e),!0}catch(t){return console.error(`[AssetServer] Failed to write to virtual FS: ${e}`,t),!1}}ensureVirtualDir(e){const t=this.module_.FS;if(!t)return;const s=e.substring(0,e.lastIndexOf("/"));if(!s)return;const n=s.split("/").filter(e=>e);let r="";for(const e of n){r=r?`${r}/${e}`:e;try{t.analyzePath(r).exists||t.mkdir(r)}catch{try{t.mkdir(r)}catch{}}}}resolveUrl(e,t){if(e.startsWith("/")||e.startsWith("http://")||e.startsWith("https://"))return e;const s=t??this.baseUrl;return s?`${s}/${e}`:`/${e}`}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}parseAtlasTextures(e){const t=[];for(const s of e.split("\n")){const e=s.trim();e&&!e.includes(":")&&(e.endsWith(".png")||e.endsWith(".jpg"))&&t.push(e)}return t}}const Ut=he(null,"Assets");class Dt{build(e){const t=e.wasmModule;t?e.insertResource(Ut,new Bt(t)):console.warn("AssetPlugin: No WASM module available")}}const zt=new Dt;class Lt{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 Ot(e,t){const s=e.getResource(Ut);s&&s.registerEmbeddedAssets(t)}async function Ht(e,t,s){const{entities:n,rootId:r}=await jt(t,s?.overrides??[],s,void 0,new Set),i={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}))},o=await _t(e,i,{assetServer:s?.assetServer,assetBaseUrl:s?.assetBaseUrl}),a=o.get(r);return void 0!==s?.parent&&e.setParent(a,s.parent),{root:a,entities:o}}const Wt=10;async function jt(e,t,s,n,r,i=0){if(i>Wt)throw new Error(`Prefab nesting depth exceeded ${Wt}. Check for deep or circular nesting in: ${e.name}`);const o=new Map;let a;if(void 0===n){a=0;for(const t of e.entities)t.nestedPrefab||(o.set(t.prefabEntityId,t.prefabEntityId),a=Math.max(a,t.prefabEntityId+1))}else{a=n;for(const t of e.entities)t.nestedPrefab||o.set(t.prefabEntityId,a++)}const c=[];for(const n of e.entities){if(n.nestedPrefab){if(!s?.assetServer)throw new Error(`AssetServer required to load nested prefab: ${n.nestedPrefab.prefabPath}`);if(r?.has(n.nestedPrefab.prefabPath)){console.error(`[Prefab] Cycle detected: ${n.nestedPrefab.prefabPath}`);continue}r?.add(n.nestedPrefab.prefabPath);const e=await s.assetServer.loadPrefab(n.nestedPrefab.prefabPath,s.assetBaseUrl),t=await jt(e,n.nestedPrefab.overrides,s,a,r,i+1);o.set(n.prefabEntityId,t.rootId),a=t.nextId;const l=t.entities.find(e=>e.id===t.rootId);l&&(l.parent=null!==n.parent?o.get(n.parent)??null:null),c.push(...t.entities);continue}const l=o.get(n.prefabEntityId),h=n.prefabEntityId===e.rootEntityId,u={id:l,prefabEntityId:n.prefabEntityId,name:n.name,parent:h?null:null!==n.parent?o.get(n.parent)??null:null,children:n.children.map(e=>o.get(e)).filter(e=>void 0!==e),components:JSON.parse(JSON.stringify(n.components)),visible:n.visible};Nt(u,t),c.push(u)}const l=o.get(e.rootEntityId);if(void 0===l)throw new Error("Failed to resolve prefab root entity");return{entities:c,rootId:l,nextId:a}}function Nt(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 Vt{constructor(e,t){this.world_=e,this.assetServer_=t}async instantiate(e,t){const s=this.assetServer_.resolveAddress(e),n=s?s.path:e,r=await this.assetServer_.loadPrefab(n,t?.baseUrl);return Ht(this.world_,r,{assetServer:this.assetServer_,assetBaseUrl:t?.baseUrl,parent:t?.parent,overrides:t?.overrides})}}const Xt=he(null,"Prefabs");class Yt{constructor(){this.name="PrefabsPlugin",this.dependencies=[Ut]}build(e){const t=e.getResource(Ut);e.insertResource(Xt,new Vt(e.world,t))}}const qt=new Yt;let Gt=null,Jt=0,Kt=0,Qt=0;const Zt=new Float32Array(256);function es(e){Gt=e,Jt=Gt._malloc(64),Kt=Gt._malloc(64),Qt=Gt._malloc(1024)}function ts(){Gt&&(Jt&&(Gt._free(Jt),Jt=0),Kt&&(Gt._free(Kt),Kt=0),Qt&&(Gt._free(Qt),Qt=0)),Gt=null}function ss(){if(!Gt)throw new Error("Draw API not initialized. Call initDrawAPI() first.");return Gt}const ns={r:1,g:1,b:1,a:1},rs={begin(e){const t=ss();try{t.HEAPF32.set(e,Jt/4),t.draw_begin(Jt)}catch(e){Oe(e,"Draw.begin")}},end(){try{ss().draw_end()}catch(e){Oe(e,"Draw.end")}},line(e,t,s,n=1){try{ss().draw_line(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.line")}},rect(e,t,s,n=!0){try{ss().draw_rect(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rect")}},rectOutline(e,t,s,n=1){try{ss().draw_rectOutline(e.x,e.y,t.x,t.y,s.r,s.g,s.b,s.a,n)}catch(e){Oe(e,"Draw.rectOutline")}},circle(e,t,s,n=!0,r=32){try{ss().draw_circle(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circle")}},circleOutline(e,t,s,n=1,r=32){try{ss().draw_circleOutline(e.x,e.y,t,s.r,s.g,s.b,s.a,n,r)}catch(e){Oe(e,"Draw.circleOutline")}},texture(e,t,s,n=ns){try{ss().draw_texture(e.x,e.y,t.x,t.y,s,n.r,n.g,n.b,n.a)}catch(e){Oe(e,"Draw.texture")}},textureRotated(e,t,s,n,r=ns){try{ss().draw_textureRotated(e.x,e.y,t.x,t.y,s,n,r.r,r.g,r.b,r.a)}catch(e){Oe(e,"Draw.textureRotated")}},setLayer(e){ss().draw_setLayer(e)},setDepth(e){ss().draw_setDepth(e)},getDrawCallCount:()=>Gt?Gt.draw_getDrawCallCount():0,getPrimitiveCount:()=>Gt?Gt.draw_getPrimitiveCount():0,setBlendMode(e){ss().draw_setBlendMode(e)},setDepthTest(e){ss().draw_setDepthTest(e)},drawMesh(e,t,s){try{const n=ss();n.HEAPF32.set(s,Kt/4),n.draw_mesh(e,t,Kt)}catch(s){Oe(s,`Draw.drawMesh(geometry=${e}, shader=${t})`)}},drawMeshWithMaterial(e,t,s){try{const n=ss(),r=Ze.get(t);if(!r)return;if(rs.setBlendMode(r.blendMode),rs.setDepthTest(r.depthTest),0===r.uniforms.size)return void rs.drawMesh(e,r.shader,s);let i;if(n.HEAPF32.set(s,Kt/4),!r.dirty_&&r.cachedBuffer_)i=r.cachedIdx_;else{i=0;let e=0;for(const[t,s]of r.uniforms){const n=as(t);if(!(n<0)){if(Ve(s))Zt[i++]=10,Zt[i++]=n,Zt[i++]=s.slot??e++,Zt[i++]=s.textureId;else if("number"==typeof s)Zt[i++]=1,Zt[i++]=n,Zt[i++]=s;else if(Array.isArray(s)){Zt[i++]=s.length,Zt[i++]=n;for(let e=0;e<s.length;e++)Zt[i++]=s[e]}else"w"in s?(Zt[i++]=4,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z,Zt[i++]=s.w):"z"in s?(Zt[i++]=3,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.y,Zt[i++]=s.z):(Zt[i++]=2,Zt[i++]=n,Zt[i++]=s.x,Zt[i++]=s.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(Zt.subarray(0,i)),r.cachedIdx_=i,r.dirty_=!1}if(0===i)return void n.draw_mesh(e,r.shader,Kt);n.HEAPF32.set(r.cachedBuffer_.subarray(0,i),Qt/4),n.draw_meshWithUniforms(e,r.shader,Kt,Qt,i)}catch(s){Oe(s,`Draw.drawMeshWithMaterial(geometry=${e}, material=${t})`)}}},is={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},os=new Set;function as(e){const t=is[e];return void 0!==t?t:(os.has(e)||(os.add(e),console.warn(`[ESEngine] Unknown uniform name "${e}" - supported names: ${Object.keys(is).join(", ")}`)),-1)}const cs=new Map;function ls(e,t,s){cs.set(e,{fn:t,scene:s??""})}function hs(e){cs.delete(e)}function us(){cs.clear()}var ds;!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"}(ds||(ds={}));let fs=null,ps=0,_s=0,ms=0;function gs(e){fs=e,ps=fs._malloc(262144),_s=fs._malloc(65536),ms=fs._malloc(256)}function ys(){fs&&(ps&&fs._free(ps),_s&&fs._free(_s),ms&&fs._free(ms),ps=0,_s=0,ms=0),fs=null}function ws(){if(!fs)throw new Error("Geometry API not initialized. Call initGeometryAPI() first.");return fs}const xs={create(e){const t=ws(),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,ps/4);const r=e.layout.length,i=new Int32Array(r);for(let t=0;t<r;t++)i[t]=e.layout[t].type;if(new Int32Array(t.HEAPU8.buffer,ms,r).set(i),t.geometry_init(s,ps,n,ms,r,e.dynamic??!1),e.indices){const n=e.indices.length;if(4*n>65536)throw new Error(`Index data too large: ${n} indices (max 16384)`);if(e.indices instanceof Uint16Array){new Uint16Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices16(s,_s,n)}else{new Uint32Array(t.HEAPU8.buffer,_s,n).set(e.indices),t.geometry_setIndices32(s,_s,n)}}return s},updateVertices(e,t,s=0){const n=ws(),r=t.length;if(4*r>262144)throw new Error(`Vertex data too large: ${r} floats (max 65536)`);n.HEAPF32.set(t,ps/4),n.geometry_updateVertices(e,ps,r,s)},release(e){e>0&&ws().geometry_release(e)},isValid:e=>!(!fs||e<=0)&&fs.geometry_isValid(e),createQuad(e=1,t=1){const s=e/2,n=t/2;return xs.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:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array([0,1,2,2,3,0])})},createCircle(e=1,t=32){const s=[],n=[];s.push(0,0,.5,.5);for(let n=0;n<=t;n++){const r=n/t*Math.PI*2,i=Math.cos(r)*e,o=Math.sin(r)*e,a=(Math.cos(r)+1)/2,c=(Math.sin(r)+1)/2;s.push(i,o,a,c)}for(let e=1;e<=t;e++)n.push(0,e,e+1);return xs.create({vertices:new Float32Array(s),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(n)})},createPolygon(e){if(e.length<3)throw new Error("Polygon must have at least 3 points");let t=1/0,s=1/0,n=-1/0,r=-1/0;for(const i of e)t=Math.min(t,i.x),s=Math.min(s,i.y),n=Math.max(n,i.x),r=Math.max(r,i.y);const i=[];for(const o of e){const e=(o.x-t)/(n-t),a=(o.y-s)/(r-s);i.push(o.x,o.y,e,a)}const o=[];for(let t=1;t<e.length-1;t++)o.push(0,t,t+1);return xs.create({vertices:new Float32Array(i),layout:[{name:"a_position",type:ds.Float2},{name:"a_texCoord",type:ds.Float2}],indices:new Uint16Array(o)})}};let vs=null;function bs(e){vs=e}function Ss(){vs&&Cs.isInitialized()&&Cs.shutdown(),vs=null}function Ps(){if(!vs)throw new Error("PostProcess API not initialized. Call initPostProcessAPI() first.");return vs}const Cs={init(e,t){try{return Ps().postprocess_init(e,t)}catch(s){return Oe(s,`PostProcess.init(${e}x${t})`),!1}},shutdown(){try{Ps().postprocess_shutdown()}catch(e){Oe(e,"PostProcess.shutdown")}},resize(e,t){try{Ps().postprocess_resize(e,t)}catch(s){Oe(s,`PostProcess.resize(${e}x${t})`)}},addPass(e,t){try{return Ps().postprocess_addPass(e,t)}catch(t){return Oe(t,`PostProcess.addPass("${e}")`),-1}},removePass(e){try{Ps().postprocess_removePass(e)}catch(t){Oe(t,`PostProcess.removePass("${e}")`)}},setEnabled(e,t){try{Ps().postprocess_setPassEnabled(e,t)}catch(t){Oe(t,`PostProcess.setEnabled("${e}")`)}},isEnabled(e){try{return Ps().postprocess_isPassEnabled(e)}catch(t){return Oe(t,`PostProcess.isEnabled("${e}")`),!1}},setUniform(e,t,s){try{Ps().postprocess_setUniformFloat(e,t,s)}catch(s){Oe(s,`PostProcess.setUniform("${e}", "${t}")`)}},setUniformVec4(e,t,s){try{Ps().postprocess_setUniformVec4(e,t,s.x,s.y,s.z,s.w)}catch(s){Oe(s,`PostProcess.setUniformVec4("${e}", "${t}")`)}},begin(){try{Ps().postprocess_begin()}catch(e){Oe(e,"PostProcess.begin")}},end(){try{Ps().postprocess_end()}catch(e){Oe(e,"PostProcess.end")}},getPassCount(){try{return Ps().postprocess_getPassCount()}catch(e){return Oe(e,"PostProcess.getPassCount"),0}},isInitialized(){if(!vs)return!1;try{return vs.postprocess_isInitialized()}catch(e){return Oe(e,"PostProcess.isInitialized"),!1}},setBypass(e){try{Ps().postprocess_setBypass(e)}catch(e){Oe(e,"PostProcess.setBypass")}},isBypassed(){if(!vs)return!0;try{return vs.postprocess_isBypassed()}catch(e){return Oe(e,"PostProcess.isBypassed"),!0}},createBlur:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#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:()=>Ze.createShader(Ts,"#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform float u_intensity;\nout vec4 fragColor;\n\nvoid main() {\n vec4 color = texture(u_texture, v_texCoord);\n float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));\n fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);\n}\n"),createChromaticAberration:()=>Ze.createShader(Ts,"#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="#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\n\nout vec2 v_texCoord;\n\nvoid main() {\n v_texCoord = a_texCoord;\n gl_Position = vec4(a_position, 0.0, 1.0);\n}\n";var Es;!function(e){e[e.Background=0]="Background",e[e.Opaque=1]="Opaque",e[e.Transparent=2]="Transparent",e[e.Overlay=3]="Overlay"}(Es||(Es={}));let Ms=null,Rs=0;function As(e){Ms=e,Rs=Ms._malloc(64)}function Is(){Ms&&Rs&&(Ms._free(Rs),Rs=0),Ms=null}const Fs={init(e,t){Ms?.renderer_init(e,t)},resize(e,t){Ms?.renderer_resize(e,t)},begin(e,t){if(Ms&&Rs)try{Ms.HEAPF32.set(e,Rs/4),Ms.renderer_begin(Rs,t??0)}catch(e){Oe(e,"Renderer.begin")}},flush(){try{Ms?.renderer_flush()}catch(e){Oe(e,"Renderer.flush")}},end(){try{Ms?.renderer_end()}catch(e){Oe(e,"Renderer.end")}},submitSprites(e){if(Ms)try{Ms.renderer_submitSprites(e._cpp)}catch(e){Oe(e,"Renderer.submitSprites")}},submitBitmapText(e){if(Ms)try{Ms.renderer_submitBitmapText(e._cpp)}catch(e){Oe(e,"Renderer.submitBitmapText")}},submitSpine(e){if(Ms)try{Ms.renderer_submitSpine?.(e._cpp)}catch(e){Oe(e,"Renderer.submitSpine")}},setStage(e){Ms?.renderer_setStage(e)},createRenderTarget:(e,t,s=1)=>Ms?.renderer_createTarget(e,t,s)??0,releaseRenderTarget(e){Ms?.renderer_releaseTarget(e)},getTargetTexture:e=>Ms?.renderer_getTargetTexture(e)??0,getTargetDepthTexture:e=>Ms?.renderer_getTargetDepthTexture(e)??0,setClearColor(e,t,s,n){Ms?.renderer_setClearColor?.(e,t,s,n)},setViewport(e,t,s,n){Ms?.renderer_setViewport(e,t,s,n)},setScissor(e,t,s,n,r){Ms?.renderer_setScissor(e,t,s,n,r)},clearBuffers(e){Ms?.renderer_clearBuffers(e)},measureBitmapText:(e,t,s,n)=>Ms?Ms.getResourceManager().measureBitmapText(e,t,s,n):{width:0,height:0},getStats:()=>Ms?{drawCalls:Ms.renderer_getDrawCalls(),triangles:Ms.renderer_getTriangles(),sprites:Ms.renderer_getSprites(),text:Ms.renderer_getText(),spine:Ms.renderer_getSpine?.()??0,meshes:Ms.renderer_getMeshes(),culled:Ms.renderer_getCulled()}:{drawCalls:0,triangles:0,sprites:0,text:0,spine:0,meshes:0,culled:0}};let $s=null;function ks(e){$s=e}function Bs(){$s=null}const Us={enable(){$s?.gl_enableErrorCheck(!0)},disable(){$s?.gl_enableErrorCheck(!1)},check:e=>$s?.gl_checkErrors(e)??0,diagnose(){$s?.renderer_diagnose()}};class Ds{constructor(){this.spineRenderer_=null,this.maskProcessor_=null,this.lastWidth_=0,this.lastHeight_=0,this.activeScenes_=null}get spineRenderer(){return this.spineRenderer_}setSpineRenderer(e){this.spineRenderer_=e}get maskProcessor(){return this.maskProcessor_}setMaskProcessor(e){this.maskProcessor_=e}setActiveScenes(e){this.activeScenes_=e}render(e){const{registry:t,viewProjection:s,width:n,height:r,elapsed:i}=e;n===this.lastWidth_&&r===this.lastHeight_||(Fs.resize(n,r),Cs.isInitialized()&&Cs.getPassCount()>0&&Cs.resize(n,r),this.lastWidth_=n,this.lastHeight_=r),Fs.setViewport(0,0,n,r),Fs.clearBuffers(3),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,0,0,n,r),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}renderCamera(e){const{registry:t,viewProjection:s,viewportPixels:n,clearFlags:r,elapsed:i}=e;Fs.setViewport(n.x,n.y,n.w,n.h),Fs.setScissor(n.x,n.y,n.w,n.h,!0),Fs.clearBuffers(r),Fs.setScissor(0,0,0,0,!1),Fs.begin(s),this.maskProcessor_&&this.maskProcessor_(t._cpp,s,n.x,n.y,n.w,n.h),Fs.submitSprites(t),Fs.submitBitmapText(t),this.spineRenderer_?this.spineRenderer_(t,i):Fs.submitSpine(t),Fs.flush(),this.executeDrawCallbacks(s,i),Fs.end()}executeDrawCallbacks(e,t){const s=cs;if(s.size>0){rs.begin(e);const n=[];for(const[e,r]of s.entries())if(!r.scene||!this.activeScenes_||this.activeScenes_.has(r.scene))try{r.fn(t)}catch(t){console.error(`[CustomDraw] callback '${e}' error:`,t),n.push(e)}rs.end();for(const e of n)hs(e)}}}const zs="__scene_transition_overlay__";class Ls{constructor(e){this.entities=new Set,this.drawCallbacks=new Map,this.postProcessPasses=[],this.savedAlphas=new Map,this.status="loading",this.config=e}}class Os{constructor(e,t){this.instance_=e,this.app_=t}get name(){return this.instance_.config.name}get entities(){return this.instance_.entities}spawn(){const e=this.app_.world.spawn();return this.instance_.entities.add(e),this.app_.world.insert(e,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),ls(e,t,this.instance_.config.name)}addPostProcessPass(e,t){const s=Cs.addPass(e,t);return this.instance_.postProcessPasses.push(e),s}removePostProcessPass(e){Cs.removePass(e);const t=this.instance_.postProcessPasses.indexOf(e);-1!==t&&this.instance_.postProcessPasses.splice(t,1)}setPersistent(e,t){if(this.app_.world.has(e,se)){const s=this.app_.world.get(e,se);s.persistent=t,this.app_.world.insert(e,se,s)}}}class Hs{constructor(e){this.configs_=new Map,this.scenes_=new Map,this.contexts_=new Map,this.additiveScenes_=new Set,this.pausedScenes_=new Set,this.sleepingScenes_=new Set,this.loadOrder_=[],this.activeScene_=null,this.initialScene_=null,this.transition_=null,this.loadPromises_=new Map,this.app_=e}register(e){this.configs_.set(e.name,e)}setInitial(e){this.initialScene_=e}getInitial(){return this.initialScene_}isTransitioning(){return null!==this.transition_}async switchTo(e,t){if(this.transition_)return void console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${e}")`);"fade"!==(t?.transition??"none")?(this.activeScene_&&this.activeScene_!==e&&await this.unload(this.activeScene_,t),await this.load(e)):await this.startFadeTransition(e,t??{})}startFadeTransition(e,t){return new Promise(s=>{const n=t.duration??y.sceneTransitionDuration,r=t.color??{...y.sceneTransitionColor};t.onStart?.(),this.transition_={phase:"fade-out",elapsed:0,duration:n,color:r,targetScene:e,options:t,resolve:s},ls(zs,()=>{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;rs.setLayer(9999),rs.setDepth(9999),rs.rect({x:0,y:0},{x:2e4,y:2e4},{r:r.r,g:r.g,b:r.b,a:s})})})}updateTransition(e){if(!this.transition_)return;this.transition_.elapsed+=e;const t=this.transition_.duration/2;if("fade-out"===this.transition_.phase&&this.transition_.elapsed>=t){this.transition_.phase="fade-in",this.transition_.elapsed=0;const{targetScene:e,options:t}=this.transition_,s=this.activeScene_;(async()=>{s&&s!==e&&await this.unload(s,t),await this.load(e)})().catch(e=>{console.error("Scene transition failed:",e),this.transition_=null,hs(zs)})}if("fade-in"===this.transition_.phase&&this.transition_.elapsed>=t){const{resolve:e,options:t}=this.transition_;this.transition_=null,hs(zs),t.onComplete?.(),e()}}async load(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.activeScene_=e,this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Ls(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.activeScene_=e,this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async loadAdditive(e){if(this.scenes_.has(e)){const t=this.scenes_.get(e);return"loading"===t.status?this.loadPromises_.get(e):(t.status="running",this.additiveScenes_.add(e),this.contexts_.get(e))}const t=this.configs_.get(e);if(!t)throw new Error(`Scene "${e}" is not registered`);const s=new Ls(t);this.scenes_.set(e,s);const n=new Os(s,this.app_);this.contexts_.set(e,n);const r=(async()=>{let r=t.data;if(!r&&t.path){const e=this.app_.hasResource(Ut)?this.app_.getResource(Ut):null;if(e)r=await e.loadJson(t.path);else{const e=await fetch(t.path);r=await e.json()}}if(r){const t={};this.app_.hasResource(Ut)&&(t.assetServer=this.app_.getResource(Ut));const n=await _t(this.app_.world,r,t);for(const t of n.values())s.entities.add(t),this.app_.world.insert(t,se,{scene:e,persistent:!1})}if(t.systems)for(const{schedule:s,system:n}of t.systems){const t=js(this.app_,e,n);this.app_.addSystemToSchedule(s,t)}return t.setup&&await t.setup(n),s.status="running",this.additiveScenes_.add(e),this.loadOrder_.push(e),n})();this.loadPromises_.set(e,r);try{return await r}finally{this.loadPromises_.delete(e)}}async unload(e,t){const s=this.scenes_.get(e);if(!s)return;const n=this.contexts_.get(e);s.status="unloading",s.config.cleanup&&s.config.cleanup(n);const r=t?.keepPersistent??!0;for(const e of s.entities){if(r&&this.app_.world.valid(e)&&this.app_.world.has(e,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())hs(e);s.drawCallbacks.clear();for(const e of s.postProcessPasses)try{Cs.removePass(e)}catch{}s.postProcessPasses.length=0,this.scenes_.delete(e),this.contexts_.delete(e),this.additiveScenes_.delete(e),this.pausedScenes_.delete(e),this.sleepingScenes_.delete(e);const i=this.loadOrder_.indexOf(e);-1!==i&&this.loadOrder_.splice(i,1),this.activeScene_===e&&(this.activeScene_=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){t.status="sleeping",this.sleepingScenes_.add(e),this.setPostProcessPassesEnabled(t,!1),t.savedAlphas.clear();for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y);t.savedAlphas.set(e,s.color.a),s.color={...s.color,a:0},this.app_.world.insert(e,Y,s)}}}wake(e){const t=this.scenes_.get(e);if(t&&"sleeping"===t.status){t.status="running",this.sleepingScenes_.delete(e),this.setPostProcessPassesEnabled(t,!0);for(const e of t.entities)if(this.app_.world.valid(e)&&this.app_.world.has(e,Y)){const s=this.app_.world.get(e,Y),n=t.savedAlphas.get(e)??1;s.color={...s.color,a:n},this.app_.world.insert(e,Y,s)}t.savedAlphas.clear()}}setPostProcessPassesEnabled(e,t){for(const s of e.postProcessPasses)try{Cs.setEnabled(s,t)}catch{}}isPaused(e){return this.pausedScenes_.has(e)}isSleeping(e){return this.sleepingScenes_.has(e)}isLoaded(e){return this.scenes_.has(e)}isActive(e){return this.activeScene_===e}getActive(){return this.activeScene_}getActiveScenes(){const e=[];for(const[t,s]of this.scenes_)"running"===s.status&&e.push(t);return e}getLoaded(){return Array.from(this.scenes_.keys())}getLoadOrder(){return[...this.loadOrder_]}bringToTop(e){const t=this.loadOrder_.indexOf(e);-1!==t&&(this.loadOrder_.splice(t,1),this.loadOrder_.push(e))}getScene(e){return this.contexts_.get(e)??null}getSceneStatus(e){return this.scenes_.get(e)?.status??null}}const Ws=he(null,"SceneManager");function js(e,t,s){return{_id:Symbol(`SceneScoped_${s._name}_${t}`),_name:`${s._name}@${t}`,_params:s._params,_fn:(...n)=>{"running"===e.getResource(Ws).getSceneStatus(t)&&s._fn(...n)}}}const Ns=Ce([de(Ws),ue(_e)],(e,t)=>{e.get().updateTransition(t.delta)},{name:"SceneTransitionSystem"}),Vs={name:"SceneManager",build(e){const t=new Hs(e);e.insertResource(Ws,t);const s={_id:Symbol("SceneInitSystem"),_name:"SceneInitSystem",_params:[],_fn:()=>{const t=e.getResource(Ws),s=t.getInitial();s&&t.load(s).catch(e=>{console.error("Failed to load initial scene:",e)})}};e.addSystemToSchedule(Se.Startup,s),e.addSystemToSchedule(Se.Last,Ns)}};class Xs{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_=new Set,this.sortedSystemsCache_=new Map,this.error_handler_=null,this.system_error_handler_=null,this.frame_paused_=!1,this.user_paused_=!1,this.step_pending_=!1,this.play_speed_=1,this.mainLoop=()=>{if(!this.running_)return;const e=d(),t=e-this.lastTime_;this.lastTime_=e;const s=Math.min(t/1e3,this.maxDeltaTime_)*this.play_speed_;if(this.updateTime(s),this.world_.resetQueryPool(),this.frame_paused_=!1,this.user_paused_&&!this.step_pending_)this.runSchedule(Se.Last);else{this.runSchedule(Se.First),this.fixedAccumulator_+=s;let e=0;for(;this.fixedAccumulator_>=this.fixedTimestep_&&e<this.maxFixedSteps_;)this.fixedAccumulator_-=this.fixedTimestep_,this.runSchedule(Se.FixedPreUpdate),this.runSchedule(Se.FixedUpdate),this.runSchedule(Se.FixedPostUpdate),e++;e>=this.maxFixedSteps_&&(this.fixedAccumulator_=0),this.runSchedule(Se.PreUpdate),this.runSchedule(Se.Update),this.runSchedule(Se.PostUpdate),this.runSchedule(Se.Last),this.step_pending_&&(this.step_pending_=!1)}requestAnimationFrame(this.mainLoop)},this.world_=new We,this.resources_=new pe;for(const e of Object.values(Se))"number"==typeof e&&this.systems_.set(e,[])}static new(){return new Xs}addPlugin(e){if(this.installed_plugins_.has(e))return this;if(e.dependencies)for(const t of e.dependencies)if(!this.hasResource(t))throw new Error(`Plugin "${e.name??"unknown"}" requires resource "${t._name}" which has not been registered`);return this.installed_plugins_.add(e),e.build(this),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(Se.Update,e)}addStartupSystem(e){return this.addSystemToSchedule(Se.Startup,e)}connectCpp(e,t){return this.world_.connectCpp(e),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 Le(e),this}setPaused(e){this.user_paused_=e}isPaused(){return this.user_paused_}stepFrame(){this.step_pending_=!0}setPlaySpeed(e){this.play_speed_=Math.max(.1,Math.min(4,e))}getPlaySpeed(){return this.play_speed_}insertResource(e,t){return this.resources_.insert(e,t),this}getResource(e){return this.resources_.get(e)}hasResource(e){return this.resources_.has(e)}registerScene(e){return this.getResource(Ws).register(e),this}setInitialScene(e){return this.getResource(Ws).setInitial(e),this}run(){this.running_||(this.running_=!0,this.runner_=new Ae(this.world_,this.resources_),this.resources_.insert(_e,{delta:0,elapsed:0,frameCount:0}),this.runSchedule(Se.Startup),this.lastTime_=d(),this.mainLoop())}quit(){this.running_=!1,us();const e=[Bs,Is,Ss,ys,Ke,ts];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}sortSystems(e){if(e.length<=1)return e;const t=new Map;for(let s=0;s<e.length;s++)t.set(e[s].system._name,s);for(const s of e)if(s.runBefore)for(const n of s.runBefore){const r=t.get(n);if(void 0!==r){const t=e[r];t.runAfter||(t.runAfter=[]),t.runAfter.includes(s.system._name)||t.runAfter.push(s.system._name)}}const s=[],n=new Set,r=new Set,i=o=>{if(n.has(o))return;if(r.has(o)){const t=e[o].system._name;throw new Error(`Circular dependency detected involving system "${t}"`)}r.add(o);const a=e[o];if(a.runAfter)for(const e of a.runAfter){const s=t.get(e);void 0!==s&&i(s)}r.delete(o),n.add(o),s.push(a)};for(let t=0;t<e.length;t++)i(t);return s}runSchedule(e){const t=this.systems_.get(e);if(!t||!this.runner_||this.frame_paused_)return;let s=this.sortedSystemsCache_.get(e);s||(s=t.some(e=>e.runBefore||e.runAfter)?this.sortSystems(t):t,this.sortedSystemsCache_.set(e,s));for(const e of s)try{this.runner_.run(e.system)}catch(t){const s=e.system._name;if(console.error(`[ESEngine] System "${s}" threw an error:`,t),this.error_handler_&&this.error_handler_(t,s),this.system_error_handler_){const e=t instanceof Error?t:new Error(String(t));if("pause"===this.system_error_handler_(e,s))return void(this.frame_paused_=!0)}}}updateTime(e){const t=this.resources_.get(_e);t.delta=e,t.elapsed+=e,t.frameCount++}}function Ys(e){if("undefined"==typeof window)return;const t=window.__esengine_pendingSystems;if(t&&0!==t.length){for(const s of t)e.addSystemToSchedule(s.schedule,s.system);t.length=0}}const qs=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function Gs(e,t,s,n,r){const i=e*t/s,o=e;switch(n){case N.FixedWidth:return i;case N.FixedHeight:return o;case N.Expand:return Math.max(i,o);case N.Shrink:return Math.min(i,o);case N.Match:{const e=r;return Math.pow(i,1-e)*Math.pow(o,e)}default:return o}}function Js(e,t,s,n,r,i){if(0===s||0===n)return[];const o=e.registry_getCameraEntities(t);if(0===o.length)return[];const a=i&&r?o.filter(e=>{const t=r.tryGet(e,se);return!t||""===t.scene||i.has(t.scene)}):o;if(0===a.length)return[];const c=function(e,t){const s=e.registry_getCanvasEntity(t);return s<0?null:t.getCanvas(s)}(e,t),l=[];for(const e of a){const r=t.getCamera(e),i=t.getLocalTransform(e),o={x:r.viewportX,y:r.viewportY,w:r.viewportW,h:r.viewportH},a=o.w*s/(o.h*n);let h,u=0,d=0;if(r.projectionType===W.Orthographic){if(d=r.orthoSize,c){d=Gs(c.designResolution.y/2,c.designResolution.x/c.designResolution.y,a,c.scaleMode,c.matchWidthOrHeight)}u=d*a,h=Qs(-u,u,-d,d,-r.farPlane,r.farPlane)}else h=en(r.fov*Math.PI/180,a,r.nearPlane,r.farPlane);const f=sn(i.position.x,i.position.y,i.position.z);l.push({entity:e,viewProjection:new Float32Array(rn(h,f)),viewportRect:o,clearFlags:r.clearFlags,priority:r.priority,halfW:u,halfH:d,cameraX:i.position.x,cameraY:i.position.y})}return l.sort((e,t)=>e.priority-t.priority),l}const Ks=new Float32Array(16);function Qs(e,t,s,n,r,i){const o=Ks;o.fill(0);const a=t-e,c=n-s,l=i-r;return o[0]=2/a,o[5]=2/c,o[10]=-2/l,o[12]=-(t+e)/a,o[13]=-(n+s)/c,o[14]=-(i+r)/l,o[15]=1,o}const Zs=new Float32Array(16);function en(e,t,s,n){const r=Zs;r.fill(0);const i=1/Math.tan(e/2),o=s-n;return r[0]=i/t,r[5]=i,r[10]=(n+s)/o,r[11]=-1,r[14]=2*n*s/o,r}const tn=new Float32Array(16);function sn(e,t,s){const n=tn;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 nn=new Float32Array(16);function rn(e,t){const s=nn;for(let n=0;n<4;n++)for(let r=0;r<4;r++)s[4*r+n]=e[0+n]*t[4*r+0]+e[4+n]*t[4*r+1]+e[8+n]*t[4*r+2]+e[12+n]*t[4*r+3];return s}var on,an,cn;!function(e){e[e.Left=0]="Left",e[e.Center=1]="Center",e[e.Right=2]="Right"}(on||(on={})),function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle",e[e.Bottom=2]="Bottom"}(an||(an={})),function(e){e[e.Visible=0]="Visible",e[e.Clip=1]="Clip",e[e.Ellipsis=2]="Ellipsis"}(cn||(cn={}));const ln=F("Text",{content:"",fontFamily:"Arial",fontSize:24,color:{r:1,g:1,b:1,a:1},align:on.Left,verticalAlign:an.Top,wordWrap:!0,overflow:cn.Visible,lineHeight:1.2}),hn=F("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}});class un{constructor(e){this.cache=new Map,this.module=e,this.canvas=u(y.textCanvasSize,y.textCanvasSize),this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0})}renderText(e,t){const s=this.ctx,n=this.canvas;s.font=`${e.fontSize}px ${e.fontFamily}`;const r=t&&t.size.x>0&&t.size.y>0,i=r?t.size.x:0,o=r?t.size.y:0,a=e.wordWrap&&r;let c=this.wrapText(e.content,a?i:0);const l=Math.ceil(e.fontSize*e.lineHeight),h=Math.ceil(.2*e.fontSize),u=Math.ceil(this.measureWidth(c)),d=Math.ceil(c.length*l),f=r?Math.ceil(i):u+2*h,p=r?Math.ceil(o):d+2*h;if(r&&e.overflow===cn.Ellipsis&&d>o){const e=Math.floor(o/l);if(e>0&&c.length>e){c=c.slice(0,e);const t=c[e-1];c[e-1]=this.truncateWithEllipsis(t,i)}}if(n.width<f||n.height<p){const e=Math.max(n.width,this.nextPowerOf2(f)),t=Math.max(n.height,this.nextPowerOf2(p));n.width=e,n.height=t}const _=Math.round(255*e.color.r),m=Math.round(255*e.color.g),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})`,r&&e.overflow===cn.Clip&&(s.save(),s.beginPath(),s.rect(0,0,f,p),s.clip());const w=c.length*l;let x;if(r)switch(e.verticalAlign){case an.Top:x=h;break;case an.Middle:x=(p-w)/2;break;case an.Bottom:x=p-w-h;break;default:x=h}else x=h;let v=x;for(const t of c){let n;switch(e.align){case on.Left:n=h;break;case on.Center:n=f/2;break;case on.Right:n=f-h;break;default:n=h}s.fillText(t,n,v),v+=l}r&&e.overflow===cn.Clip&&s.restore();const b=s.getImageData(0,0,f,p),S=new Uint8Array(b.data.buffer),P=this.module.getResourceManager(),C=this.module._malloc(S.length);this.module.HEAPU8.set(S,C);const T=P.createTexture(f,p,C,S.length,1,!0);return this.module._free(C),{textureHandle:T,width:f,height:p}}truncateWithEllipsis(e,t){if(this.ctx.measureText(e).width<=t)return e;let s=e;for(;s.length>0&&this.ctx.measureText(s+"...").width>t;)s=s.slice(0,-1);return s+"..."}renderForEntity(e,t,s){const n=this.cache.get(e);if(n){this.module.getResourceManager().releaseTexture(n.textureHandle)}const r=this.renderText(t,s);return this.cache.set(e,r),r}getCached(e){return this.cache.get(e)}release(e){const t=this.cache.get(e);if(t){this.module.getResourceManager().releaseTexture(t.textureHandle),this.cache.delete(e)}}cleanupOrphaned(e){const t=this.module.getResourceManager();for(const[s,n]of this.cache)e(s)||(t.releaseTexture(n.textureHandle),this.cache.delete(s))}releaseAll(){const e=this.module.getResourceManager();for(const t of this.cache.values())e.releaseTexture(t.textureHandle);this.cache.clear()}wrapText(e,t){if(!e)return[""];if(t<=0)return e.split("\n");const s=e.split("\n"),n=[];for(const e of s){if(!e){n.push("");continue}let s="";for(const r of e){const e=s+r;this.ctx.measureText(e).width>t&&s?(n.push(s),s=r):s=e}s&&n.push(s)}return n.length>0?n:[""]}measureWidth(e){let t=0;for(const s of e){const e=this.ctx.measureText(s),n=void 0!==e.actualBoundingBoxLeft?e.actualBoundingBoxLeft+e.actualBoundingBoxRight:e.width;t=Math.max(t,n)}return t}mapAlign(e){switch(e){case on.Left:return"left";case on.Center:return"center";case on.Right:return"right"}}nextPowerOf2(e){let t=1;for(;t<e;)t*=2;return t}}function dn(e,t){return{content:e.content,fontFamily:e.fontFamily,fontSize:e.fontSize,colorR:e.color.r,colorG:e.color.g,colorB:e.color.b,colorA:e.color.a,align:e.align,verticalAlign:e.verticalAlign,wordWrap:e.wordWrap,overflow:e.overflow,lineHeight:e.lineHeight,containerWidth:t?t.size.x:0,containerHeight:t?t.size.y:0}}function fn(e,t,s){return e.content!==t.content||e.fontFamily!==t.fontFamily||e.fontSize!==t.fontSize||e.colorR!==t.color.r||e.colorG!==t.color.g||e.colorB!==t.color.b||e.colorA!==t.color.a||e.align!==t.align||e.verticalAlign!==t.verticalAlign||e.wordWrap!==t.wordWrap||e.overflow!==t.overflow||e.lineHeight!==t.lineHeight||e.containerWidth!==(s?s.size.x:0)||e.containerHeight!==(s?s.size.y:0)}class pn{build(e){L("Text",ln);const t=e.wasmModule;if(!t)return void console.warn("TextPlugin: No WASM module available");const s=new un(t),n=e.world,r=new Map;e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{s.cleanupOrphaned(e=>n.valid(e)&&n.has(e,ln));for(const e of r.keys())n.valid(e)&&n.has(e,ln)||r.delete(e);const e=n.getEntitiesWithComponents([ln]);for(const t of e){const e=n.get(t,ln),i=n.has(t,hn)?n.get(t,hn):null,o=r.get(t);if(o&&!fn(o,e,i))continue;n.has(t,Y)||n.insert(t,Y,{texture:v,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});const a=s.renderForEntity(t,e,i),c=n.get(t,Y);c.texture=a.textureHandle,c.size.x=a.width,c.size.y=a.height,c.uvOffset.x=0,c.uvOffset.y=0,c.uvScale.x=1,c.uvScale.y=1,n.insert(t,Y,c),r.set(t,dn(e,i))}}))}}const _n=new pn,mn=F("UIMask",{enabled:!0});function gn(e,t){const s=Math.max(e.x,t.x),n=Math.max(e.y,t.y),r=Math.min(e.x+e.w,t.x+t.w),i=Math.min(e.y+e.h,t.y+t.h);return{x:s,y:n,w:Math.max(0,r-s),h:Math.max(0,i-n)}}function yn(e,t,s,n,r,i,o,a,c,l,h){const u=e-s*r,d=e+s*(1-r),f=t-n*i,p=t+n*(1-i);function _(e,t){const s=o[0]*e+o[4]*t+o[12],n=o[1]*e+o[5]*t+o[13],r=o[3]*e+o[7]*t+o[15];return[a+(.5*(s/r)+.5)*l,c+(.5*(n/r)+.5)*h]}const[m,g]=_(u,f),[y,w]=_(d,p),x=Math.min(m,y),v=Math.max(m,y),b=Math.min(g,w),S=Math.max(g,w);return{x:Math.round(x),y:Math.round(b),w:Math.round(v-x),h:Math.round(S-b)}}function wn(e,t){const s=t??new Float32Array(16),n=e[0],r=e[1],i=e[2],o=e[3],a=e[4],c=e[5],l=e[6],h=e[7],u=e[8],d=e[9],f=e[10],p=e[11],_=e[12],m=e[13],g=e[14],y=e[15],w=n*c-r*a,x=n*l-i*a,v=n*h-o*a,b=r*l-i*c,S=r*h-o*c,P=i*h-o*l,C=u*m-d*_,T=u*g-f*_,E=u*y-p*_,M=d*g-f*m,R=d*y-p*m,A=f*y-p*g;let I=w*A-x*R+v*M+b*E-S*T+P*C;return 0===I||(I=1/I,s[0]=(c*A-l*R+h*M)*I,s[1]=(i*R-r*A-o*M)*I,s[2]=(m*P-g*S+y*b)*I,s[3]=(f*S-d*P-p*b)*I,s[4]=(l*E-a*A-h*T)*I,s[5]=(n*A-i*E+o*T)*I,s[6]=(g*v-_*P-y*x)*I,s[7]=(u*P-f*v+p*x)*I,s[8]=(a*R-c*E+h*C)*I,s[9]=(r*E-n*R-o*C)*I,s[10]=(_*S-m*v+y*w)*I,s[11]=(d*v-u*S-p*w)*I,s[12]=(c*T-a*M-l*C)*I,s[13]=(n*M-r*T+i*C)*I,s[14]=(m*x-_*b-g*w)*I,s[15]=(u*b-d*x+f*w)*I),s}function xn(e,t,s,n,r,i,o){const a=(e-n)/i*2-1,c=(t-r)/o*2-1,l=s[0]*a+s[4]*c+s[12],h=s[1]*a+s[5]*c+s[13],u=s[3]*a+s[7]*c+s[15];return{x:l/u,y:h/u}}function vn(e,t,s,n,r,i,o,a){return e>=s-r*o&&e<=s+r*(1-o)&&t>=n-i*a&&t<=n+i*(1-a)}function bn(e,t,s,n,r,i,o){if(!e.has(t,hn)||!e.has(t,X))return null;const a=e.get(t,hn),c=e.get(t,X),l=a.size.x*c.scale.x,h=a.size.y*c.scale.y;return yn(c.position.x,c.position.y,l,h,a.pivot.x,a.pivot.y,s,n,r,i,o)}function Sn(e,t){return(s,n,r,i,o,a)=>{e.renderer_clearAllClipRects();const c=t.getEntitiesWithComponents([mn]);if(0!==c.length)try{!function(e,t,s,n,r,i,o,a,c){const l=new Set;for(const e of n){t.get(e,mn).enabled&&l.add(e)}const h=[];for(const e of n){if(!l.has(e))continue;let s=!0,n=e;for(;t.has(n,K);){const e=t.get(n,K);if(l.has(e.entity)){s=!1;break}n=e.entity}s&&h.push(e)}function u(n,h){const d=e.getChildEntities(s,n);for(const s of d){let n=h;if(l.has(s)){const e=bn(t,s,r,i,o,a,c);e&&(n=gn(h,e))}e.renderer_setEntityClipRect(s,n.x,n.y,n.w,n.h),u(s,n)}}for(const e of h){const s=bn(t,e,r,i,o,a,c);s&&u(e,s)}}(e,t,s,c,n,r,i,o,a)}catch(t){e.renderer_clearAllClipRects()}}}class Pn{build(e){if(L("UIMask",mn),!e.wasmModule)return;const t=e.pipeline;t&&t.setMaskProcessor(Sn(e.wasmModule,e.world))}}const Cn=new Pn,Tn=F("Interactable",{enabled:!0}),En=F("UIInteraction",{hovered:!1,pressed:!1,justPressed:!1,justReleased:!1});var Mn;!function(e){e[e.Normal=0]="Normal",e[e.Hovered=1]="Hovered",e[e.Pressed=2]="Pressed",e[e.Disabled=3]="Disabled"}(Mn||(Mn={}));const Rn=F("Button",{state:Mn.Normal,transition:null});class An{constructor(){this.events_=[]}emit(e,t){this.events_.push({entity:e,type:t})}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 In=he(new An,"UIEvents"),Fn=$("ScreenSpace");function $n(e,t,s,n,r,i){const o=i.right-i.left,a=i.top-i.bottom,c=i.left+e.x*o,l=i.left+t.x*o,h=i.bottom+e.y*a,u=i.bottom+t.y*a;let d,f,p,_;if(c===l&&h===u){const e=c+s.x,t=h+s.y,n=.5*r.x,i=.5*r.y;d=e-n,f=t-i,p=e+n,_=t+i}else d=c+s.x,f=h+s.y,p=l+n.x,_=u+n.y;return{centerX:.5*(d+p),centerY:.5*(f+_),width:p-d,height:_-f,rect:{left:d,bottom:f,right:p,top:_}}}function kn(e,t,s,n,r,i){if(!e.has(t,hn))return;const o=e.get(t,hn),a=$n(o.anchorMin,o.anchorMax,o.offsetMin,o.offsetMax,o.size,s);o.anchorMin.x===o.anchorMax.x&&o.anchorMin.y===o.anchorMax.y||(o.size.x=a.width,o.size.y=a.height);const c=e.get(t,V);if(i?(c.position.x=a.centerX,c.position.y=a.centerY):(c.position.x=a.centerX-n,c.position.y=a.centerY-r),e.insert(t,V,c),!e.has(t,Q))return;const l=e.get(t,Q);if(l&&l.entities)for(const t of l.entities)e.valid(t)&&kn(e,t,a.rect,a.centerX,a.centerY,!1)}class Bn{build(e){L("UIRect",hn);const t=e.world;e.addSystemToSchedule(Se.PreUpdate,Ce([ue(je)],e=>{if(!e.valid)return;const s={left:e.worldLeft,bottom:e.worldBottom,right:e.worldRight,top:e.worldTop},n=.5*(s.left+s.right),r=.5*(s.bottom+s.top),i=t.getEntitiesWithComponents([Fn,hn,V]);for(const e of i)kn(t,e,s,n,r,!0)},{name:"UILayoutSystem"}))}}const Un=new Bn,Dn=new Float32Array(16),zn=new Float32Array(16);let Ln=!0,On=1;class Hn{build(e){L("Interactable",Tn),L("Button",Rn);const t=e.world,s=new An;e.insertResource(In,s);let n=null,r=null;On="undefined"!=typeof window&&window.devicePixelRatio||1,e.addSystemToSchedule(Se.PreUpdate,Ce([ue(Fe),ue(je)],(e,i)=>{s.drain();const o=t.getEntitiesWithComponents([En]);for(const e of o){const s=t.get(e,En);s.justPressed=!1,s.justReleased=!1}if(!i.valid)return;const a=e.mouseX*On,c=i.screenH-e.mouseY*On;!function(e){let t=!1;for(let s=0;s<16;s++)if(zn[s]!==e[s]){t=!0;break}t&&(zn.set(e),Ln=!0)}(i.viewProjection),Ln&&(wn(i.viewProjection,Dn),Ln=!1);const l=xn(a,c,Dn,i.vpX,i.vpY,i.vpW,i.vpH),h=t.getEntitiesWithComponents([Tn,hn,X]);let u=null,d=-1/0;for(const e of h){t.has(e,En)||t.insert(e,En);if(!t.get(e,Tn).enabled)continue;const s=t.get(e,X),n=t.get(e,hn),r=n.size.x*s.scale.x,i=n.size.y*s.scale.y;if(vn(l.x,l.y,s.position.x,s.position.y,r,i,n.pivot.x,n.pivot.y)){let s=0;t.has(e,Y)&&(s=t.get(e,Y).layer),s>=d&&(d=s,u=e)}}if(n!==u){if(null!==n&&t.valid(n)&&t.has(n,En)){t.get(n,En).hovered=!1,s.emit(n,"hover_exit")}if(null!==u){t.get(u,En).hovered=!0,s.emit(u,"hover_enter")}n=u}if(e.isMouseButtonPressed(0)&&null!==u){const e=t.get(u,En);e.pressed=!0,e.justPressed=!0,r=u,s.emit(u,"press")}if(e.isMouseButtonReleased(0)&&null!==r){if(t.valid(r)&&t.has(r,En)){const e=t.get(r,En);e.pressed=!1,e.justReleased=!0,s.emit(r,"release"),r===n&&s.emit(r,"click")}r=null}},{name:"UIInteractionSystem"})),e.addSystemToSchedule(Se.Update,Ce([],()=>{const e=t.getEntitiesWithComponents([Rn]);for(const s of e){if(t.has(s,Tn)||t.insert(s,Tn,{enabled:!0}),!t.has(s,En))continue;const e=t.get(s,En),n=t.get(s,Rn),r=t.get(s,Tn),i=n.state;if(r.enabled?e.pressed?n.state=Mn.Pressed:e.hovered?n.state=Mn.Hovered:n.state=Mn.Normal:n.state=Mn.Disabled,i!==n.state&&n.transition&&t.has(s,Y)){const e=t.get(s,Y),r=n.transition;switch(n.state){case Mn.Normal:e.color={...r.normalColor};break;case Mn.Hovered:e.color={...r.hoveredColor};break;case Mn.Pressed:e.color={...r.pressedColor};break;case Mn.Disabled:e.color={...r.disabledColor}}t.insert(s,Y,e)}}},{name:"ButtonSystem"}))}}const Wn=new Hn,jn=F("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});class Nn{constructor(){this.cleanupListeners_=null}cleanup(){this.cleanupListeners_&&(this.cleanupListeners_(),this.cleanupListeners_=null)}build(e){L("TextInput",jn);const t=e.wasmModule;if(!t)return void console.warn("TextInputPlugin: No WASM module available");const s=e.world,n=new Map,r=u(y.textCanvasSize,64),i=r.getContext("2d",{willReadFrequently:!0});let o=null,a=!1,c=!0,l=0,h=0;const d=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(!d)return;const f=d,p=()=>{a||null===o||x()},_=()=>{a=!0},m=()=>{a=!1,x()},g=t=>{if(null===o)return;if("Escape"===t.key)return void S();const n=s.get(o,jn);if("Enter"===t.key&&!n.multiline){t.preventDefault();return e.getResource(In).emit(o,"submit"),void S()}let r=n.cursorPos;"ArrowLeft"===t.key?r=Math.max(0,n.cursorPos-1):"ArrowRight"===t.key?r=Math.min(n.value.length,n.cursorPos+1):"Home"===t.key?r=0:"End"===t.key&&(r=n.value.length),r!==n.cursorPos&&(n.cursorPos=r,f.selectionStart=r,f.selectionEnd=r,n.dirty=!0,P())},w=()=>{if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null};function x(){if(null===o||!s.valid(o))return;const t=s.get(o,jn);if(t.readOnly)return;let n=f.value;if(t.maxLength>0&&n.length>t.maxLength&&(n=n.substring(0,t.maxLength),f.value=n),n!==t.value){t.value=n;e.getResource(In).emit(o,"change")}t.cursorPos=f.selectionStart??n.length,t.dirty=!0,P()}function b(e){if(o===e)return;S();const t=s.get(e,jn);t.readOnly||(o=e,t.focused=!0,t.dirty=!0,f.value=t.value,f.selectionStart=t.cursorPos,f.selectionEnd=t.cursorPos,f.focus(),P())}function S(){if(null!==o&&s.valid(o)&&s.has(o,jn)){const e=s.get(o,jn);e.focused=!1,e.dirty=!0}o=null,f.blur()}function P(){c=!0,l=0}function C(e,o,a,l){(r.width<a||r.height<l)&&(r.width=Xn(Math.max(r.width,a)),r.height=Xn(Math.max(r.height,l))),i.clearRect(0,0,r.width,r.height);const h=o.backgroundColor;i.fillStyle=`rgba(${Math.round(255*h.r)}, ${Math.round(255*h.g)}, ${Math.round(255*h.b)}, ${h.a})`,i.fillRect(0,0,a,l),i.save(),i.beginPath(),i.rect(o.padding,0,a-2*o.padding,l),i.clip(),i.font=`${o.fontSize}px ${o.fontFamily}`,i.textBaseline="top",i.textAlign="left";const u=0===o.value.length,d=u?o.placeholder:o.password?"●".repeat(o.value.length):o.value,f=u?o.placeholderColor:o.color;i.fillStyle=`rgba(${Math.round(255*f.r)}, ${Math.round(255*f.g)}, ${Math.round(255*f.b)}, ${f.a})`;const p=Math.ceil(1.2*o.fontSize),_=o.padding;if(o.multiline){const e=Vn(i,d,a-2*_);let t=_;for(const s of e)i.fillText(s,_,t),t+=p}else{const e=(l-o.fontSize)/2;i.fillText(d,_,e)}if(o.focused&&c){const e=o.password?"●".repeat(o.cursorPos):o.value.substring(0,o.cursorPos);let t,s,n;if(o.multiline){const e=Vn(i,o.value.substring(0,o.cursorPos),a-2*_),r=e.length>0?e[e.length-1]:"";t=_+i.measureText(r).width,s=_+(e.length-1)*p,n=p}else t=_+i.measureText(e).width,s=(l-o.fontSize)/2,n=o.fontSize;i.fillStyle=`rgba(${Math.round(255*o.color.r)}, ${Math.round(255*o.color.g)}, ${Math.round(255*o.color.b)}, ${o.color.a})`,i.fillRect(t,s,2,n)}i.restore();const m=i.getImageData(0,0,a,l),g=new Uint8Array(m.data.buffer),y=t.getResourceManager(),w=t._malloc(g.length);t.HEAPU8.set(g,w);const x=n.get(e);void 0!==x&&y.releaseTexture(x);const v=y.createTexture(a,l,w,g.length,1,!0);n.set(e,v),t._free(w);const b=s.get(e,Y);b.texture=v,b.size.x=a,b.size.y=l,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,Y,b)}f.addEventListener("input",p),f.addEventListener("compositionstart",_),f.addEventListener("compositionend",m),f.addEventListener("keydown",g),f.addEventListener("blur",w),this.cleanupListeners_=()=>{f.removeEventListener("input",p),f.removeEventListener("compositionstart",_),f.removeEventListener("compositionend",m),f.removeEventListener("keydown",g),f.removeEventListener("blur",w),f.remove()},e.addSystemToSchedule(Se.PreUpdate,Ce([ue(In)],e=>{const t=s.getEntitiesWithComponents([jn,Tn]);for(const e of t){if(!s.has(e,En))continue;if(s.get(e,En).justPressed)return void b(e)}if(null!==o){const e=s.getEntitiesWithComponents([Tn]);for(const t of e){if(s.has(t,jn))continue;if(!s.has(t,En))continue;if(s.get(t,En).justPressed)return void S()}}},{name:"TextInputFocusSystem"})),e.addSystemToSchedule(Se.PreUpdate,Ce([],()=>{const e="undefined"!=typeof performance?performance.now():Date.now(),r=0===h?0:(e-h)/1e3;if(h=e,null!==o&&(l+=r,l>=.5&&(l-=.5,c=!c,null!==o&&s.valid(o)&&s.has(o,jn)))){s.get(o,jn).dirty=!0}const i=t.getResourceManager();for(const[e,t]of n)s.valid(e)&&s.has(e,jn)||(i.releaseTexture(t),n.delete(e));const a=s.getEntitiesWithComponents([jn,hn]);for(const e of a){const t=s.get(e,jn);if(!t.dirty)continue;const n=s.get(e,hn),r=Math.ceil(n.size.x),i=Math.ceil(n.size.y);r<=0||i<=0||(s.has(e,Y)||s.insert(e,Y,{texture:v,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}),C(e,t,r,i),t.dirty=!1)}},{name:"TextInputRenderSystem"}))}}function Vn(e,t,s){if(!t)return[""];if(s<=0)return t.split("\n");const n=t.split("\n"),r=[];for(const t of n){if(!t){r.push("");continue}let n="";for(const i of t){const t=n+i;e.measureText(t).width>s&&n?(r.push(n),n=i):n=t}n&&r.push(n)}return r.length>0?r:[""]}function Xn(e){let t=1;for(;t<e;)t*=2;return t}const Yn=new Nn;async function qn(e,t,s){const n=e.getResource(Ws);await n.switchTo(t,{transition:s.type,duration:s.duration,color:s.color})}async function Gn(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 Jn=he({collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]},"PhysicsEvents"),Kn=he(null,"PhysicsAPI");function Qn(e){return Math.atan2(2*(e.w*e.z+e.x*e.y),1-2*(e.y*e.y+e.z*e.z))}function Zn(e){const t=.5*e;return{w:Math.cos(t),x:0,y:0,z:Math.sin(t)}}class er{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(Jn,{collisionEnters:[],collisionExits:[],sensorEnters:[],sensorExits:[]});const t=new Set,s=new Map,n=Gn(this.wasmUrl_,this.factory_).then(n=>{n._physics_init(this.config_.gravity.x,this.config_.gravity.y,this.config_.fixedTimestep,this.config_.subStepCount);const r=function(e){const t=e.world.getEntitiesWithComponents([G]);for(const s of t){const t=e.world.get(s,G);if(t&&t.pixelsPerUnit)return t.pixelsPerUnit}return 100}(e),i=1/r,o=e.world;e.addSystemToSchedule(Se.PostUpdate,Ce([ue(_e)],a=>{const c=o.getEntitiesWithComponents([re,V,X]),l=new Set;for(const r of c){l.add(r);const a=o.get(r,re),c=o.get(r,X);if(t.has(r)){const e=s.get(r);!e||e.bodyType===a.bodyType&&e.gravityScale===a.gravityScale&&e.linearDamping===a.linearDamping&&e.angularDamping===a.angularDamping&&e.fixedRotation===a.fixedRotation&&e.bullet===a.bullet||(n._physics_updateBodyProperties(r,a.bodyType,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),e.bodyType=a.bodyType,e.gravityScale=a.gravityScale,e.linearDamping=a.linearDamping,e.angularDamping=a.angularDamping,e.fixedRotation=a.fixedRotation,e.bullet=a.bullet)}else{if(!a.enabled)continue;const o=Qn(c.rotation);n._physics_createBody(r,a.bodyType,c.position.x*i,c.position.y*i,o,a.gravityScale,a.linearDamping,a.angularDamping,a.fixedRotation?1:0,a.bullet?1:0),tr(e,n,r),t.add(r),s.set(r,{bodyType:a.bodyType,gravityScale:a.gravityScale,linearDamping:a.linearDamping,angularDamping:a.angularDamping,fixedRotation:a.fixedRotation,bullet:a.bullet})}if(a.bodyType===ce.Kinematic){const e=Qn(c.rotation);n._physics_setBodyTransform(r,c.position.x*i,c.position.y*i,e)}}for(const e of t)l.has(e)||(n._physics_destroyBody(e),t.delete(e),s.delete(e));n._physics_step(a.delta),function(e,t,s){const n=t._physics_getDynamicBodyCount();if(0===n)return;const r=t._physics_getDynamicBodyTransforms(),i=r>>2;for(let r=0;r<n;r++){const n=i+4*r,o=t.HEAPU32[n],a=t.HEAPF32[n+1]*s,c=t.HEAPF32[n+2]*s,l=t.HEAPF32[n+3];if(!e.world.valid(o))continue;const h=e.world.get(o,V);if(!h)continue;let u=a,d=c,f=l;if(e.world.has(o,K)){const t=e.world.get(o,K);if(t&&e.world.valid(t.entity)&&e.world.has(t.entity,X)){const s=e.world.get(t.entity,X),n=Qn(s.rotation),r=a-s.position.x,i=c-s.position.y,o=Math.cos(-n),h=Math.sin(-n);u=(r*o-i*h)/(0!==s.scale.x?s.scale.x:1),d=(r*h+i*o)/(0!==s.scale.y?s.scale.y:1),f=l-n}}h.position.x=u,h.position.y=d;const p=Zn(f);h.rotation.w=p.w,h.rotation.x=p.x,h.rotation.y=p.y,h.rotation.z=p.z,e.world.insert(o,V,h)}}(e,n,r),function(e,t,s){t._physics_collectEvents();const n=[],r=t._physics_getCollisionEnterCount();if(r>0){const e=t._physics_getCollisionEnterBuffer()>>2;for(let i=0;i<r;i++){const r=e+6*i;n.push({entityA:t.HEAPU32[r],entityB:t.HEAPU32[r+1],normalX:t.HEAPF32[r+2],normalY:t.HEAPF32[r+3],contactX:t.HEAPF32[r+4]*s,contactY:t.HEAPF32[r+5]*s})}}const i=[],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;i.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=[],h=t._physics_getSensorExitCount();if(h>0){const e=t._physics_getSensorExitBuffer()>>2;for(let s=0;s<h;s++){const n=e+2*s;l.push({sensorEntity:t.HEAPU32[n],visitorEntity:t.HEAPU32[n+1]})}}e.insertResource(Jn,{collisionEnters:n,collisionExits:i,sensorEnters:a,sensorExits:l})}(e,n,r)},{name:"PhysicsSystem"})),e.physicsModule=n,e.insertResource(Kn,sr._fromModule(n)),e.setFixedTimestep(this.config_.fixedTimestep)});n.catch(()=>{}),e.physicsInitPromise=n}}function tr(e,t,s){const n=e.world;if(n.has(s,ie)){const e=n.get(s,ie);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,oe)){const e=n.get(s,oe);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,ae)){const e=n.get(s,ae);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 sr{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(sr.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)}}function nr(e,t,s=!0){const n=e.getResourceManager(),r=e._malloc(t.pixels.length);e.HEAPU8.set(t.pixels,r);const i=n.createTexture(t.width,t.height,r,t.pixels.length,1,s);return e._free(r),i}function rr(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 ir(e,t,s,n){const r=e.scale.x*t*(s?-1:1),i=e.scale.y*t*(n?-1:1),o=e.scale.z,a=e.rotation.x,c=e.rotation.y,l=e.rotation.z,h=e.rotation.w,u=a+a,d=c+c,f=l+l,p=a*u,_=a*d,m=a*f,g=c*d,y=c*f,w=l*f,x=h*u,v=h*d,b=h*f;return new Float32Array([(1-(g+w))*r,(_+b)*r,(m-v)*r,0,(_-b)*i,(1-(p+w))*i,(y+x)*i,0,(m+v)*o,(y-x)*o,(1-(p+g))*o,0,e.position.x,e.position.y,e.position.z,1])}async function or(e,t,s,n,r,i,o,a,c){const l=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components)if("Sprite"===t.type&&t.data.texture&&"string"==typeof t.data.texture){const r=t.data.texture;if(void 0!==n[r])continue;try{n[r]=nr(e,await s.loadPixels(r))}catch{n[r]=0}}return n}(t,s,n);!function(e,t,s){if(!t.textureMetadata)return;const n=e.getResourceManager();for(const e in t.textureMetadata){const r=s[e];if(r&&r>0){const s=t.textureMetadata[e];if(s?.sliceBorder){const e=s.sliceBorder;n.setTextureMetadata(r,e.left,e.right,e.top,e.bottom)}}}}(t,s,l);let h={},u=null;if(r&&(u=function(e){const t=e.cwrap.bind(e);return{loadSkeleton:t("spine_loadSkeleton","number",["number","number","string","number","number"]),getLastError:t("spine_getLastError","string",[]),unloadSkeleton:t("spine_unloadSkeleton",null,["number"]),getAtlasPageCount:t("spine_getAtlasPageCount","number",["number"]),getAtlasPageTextureName:t("spine_getAtlasPageTextureName","string",["number","number"]),setAtlasPageTexture:t("spine_setAtlasPageTexture",null,["number","number","number","number","number"]),createInstance:t("spine_createInstance","number",["number"]),destroyInstance:t("spine_destroyInstance",null,["number"]),playAnimation:t("spine_playAnimation","number",["number","string","number","number"]),addAnimation:t("spine_addAnimation","number",["number","string","number","number","number"]),setSkin:t("spine_setSkin",null,["number","string"]),update:t("spine_update",null,["number","number"]),getAnimations:t("spine_getAnimations","string",["number"]),getSkins:t("spine_getSkins","string",["number"]),getBonePosition:t("spine_getBonePosition","number",["number","string","number","number"]),getBoneRotation:t("spine_getBoneRotation","number",["number","string"]),getBounds:t("spine_getBounds",null,["number","number","number","number","number"]),getMeshBatchCount:t("spine_getMeshBatchCount","number",["number"]),getMeshBatchVertexCount:t("spine_getMeshBatchVertexCount","number",["number","number"]),getMeshBatchIndexCount:t("spine_getMeshBatchIndexCount","number",["number","number"]),getMeshBatchData:t("spine_getMeshBatchData",null,["number","number","number","number","number","number"])}}(r),h=await async function(e,t,s,n,r){const i={};for(const o of n.entities)for(const n of o.components){if("SpineAnimation"!==n.type||!n.data)continue;const o=n.data.skeletonPath,a=n.data.atlasPath;if(!o||!a)continue;const c=r.resolvePath(o),l=r.resolvePath(a);try{const n=await r.readText(a),h="binary"===Pt(c)?.contentType;let u,d;if(h){const e=await r.readBinary(o);d=e.length,u=t._malloc(d),t.HEAPU8.set(e,u)}else{const e=await r.readText(o),s=(new TextEncoder).encode(e);d=s.length,u=t._malloc(d+1),t.HEAPU8.set(s,u),t.HEAPU8[u+d]=0}const f=s.loadSkeleton(u,d,n,n.length,h);if(t._free(u),f<0)continue;i[o]=f;const p=rr(n),_=l.substring(0,l.lastIndexOf("/"));for(let t=0;t<p.length;t++){const n=_+"/"+p[t];try{const i=r.loadPixelsRaw?await r.loadPixelsRaw(n):await r.loadPixels(n),o=nr(e,i,!1),a=e.getResourceManager().getTextureGLId(o);s.setAtlasPageTexture(f,t,a,i.width,i.height)}catch{}}}catch{}}return i}(t,r,u,s,n)),i){new er("",{gravity:o?.gravity??{x:0,y:-9.81},fixedTimestep:o?.fixedTimestep??1/60,subStepCount:o?.subStepCount??4},()=>Promise.resolve(i)).build(e)}const d=await async function(e,t,s){const n={};for(const r of t.entities)for(const t of r.components){if("BitmapText"!==t.type||!t.data.font||"string"!=typeof t.data.font)continue;const r=t.data.font;if(void 0===n[r])try{let t,i;const o=Pt(r);if("bitmap-font"===o?.editorType&&"json"===o.contentType){const e=JSON.parse(await s.readText(r)),o="label-atlas"===e.type?e.generatedFnt:e.fntFile;if(!o){n[r]=0;continue}const a=r.substring(0,r.lastIndexOf("/")),c=a?`${a}/${o}`:o;t=await s.readText(c),i=c.substring(0,c.lastIndexOf("/"))}else t=await s.readText(r),i=r.substring(0,r.lastIndexOf("/"));const a=t.match(/file="([^"]+)"/);if(!a){n[r]=0;continue}const c=i?`${i}/${a[1]}`:a[1],l=s.loadPixelsRaw?await s.loadPixelsRaw(c):await s.loadPixels(c),h=nr(e,l,!1),u=e.getResourceManager();n[r]=u.loadBitmapFont(t,h,l.width,l.height)}catch{n[r]=0}}return n}(t,s,n),f=await async function(e,t){const s={},n={};for(const r of e.entities)for(const e of r.components){if(!e.data||"string"!=typeof e.data.material||!e.data.material)continue;if("Sprite"!==e.type&&"SpineAnimation"!==e.type)continue;const r=e.data.material;if(void 0===s[r])try{const e=JSON.parse(await t.readText(r));if(!e.vertexSource||!e.fragmentSource){s[r]=0;continue}const i=e.vertexSource+e.fragmentSource;let o=n[i];o||(o=Ze.createShader(e.vertexSource,e.fragmentSource),n[i]=o),s[r]=Ze.createFromAsset(e,o)}catch{s[r]=0}}return s}(s,n);!function(e,t,s,n){const r={texture:t,material:n,font:s};for(const t of e.entities)for(const e of t.components){const t=ft(e.type);if(0===t.length)continue;const s=e.data;for(const e of t)"string"==typeof s[e.field]&&(s[e.field]=r[e.type][s[e.field]]||0)}}(s,l,d,f);const p=pt(e.world,s);if(c&&e.hasResource(Ws))for(const t of p.values())e.world.insert(t,se,{scene:c,persistent:!1});if(r&&u){const n=function(e,t,s,n){const r={};for(const i of t.entities)if(!1!==i.visible)for(const t of i.components){if("SpineAnimation"!==t.type||!t.data)continue;const o=s[t.data.skeletonPath];if(void 0===o)continue;const a=e.createInstance(o);if(a<0)continue;const c=n.get(i.id);void 0!==c&&(r[c]=a),t.data.animation&&e.playAnimation(a,t.data.animation,!1!==t.data.loop,0),t.data.skin&&e.setSkin(a,t.data.skin)}return r}(u,s,h,p);!function(e,t,s,n,r){let i=0;e.setSpineRenderer((o,a)=>{let c=a-i;i=a,(c<=0||c>.5)&&(c=1/60);const l=e.world;for(const e in r){const i=Number(e),o=r[e],a=l.has(i,ee)?l.get(i,ee):null,h=!1!==a?.playing,u=a?.timeScale??1;h&&n.update(o,c*u);let d=0;if(l.has(i,X)){const e=ir(l.get(i,X),a?.skeletonScale??1,a?.flipX??!1,a?.flipY??!1);d=t._malloc(64),t.HEAPF32.set(e,d>>2)}const f=n.getMeshBatchCount(o);for(let e=0;e<f;e++){const r=n.getMeshBatchVertexCount(o,e),i=n.getMeshBatchIndexCount(o,e);if(!r||!i)continue;const a=8*r*4,c=2*i,l=s._malloc(a),h=s._malloc(c),u=s._malloc(4),f=s._malloc(4);n.getMeshBatchData(o,e,l,h,u,f);const p=s.HEAPU32[u>>2],_=s.HEAPU32[f>>2],m=new Float32Array(s.HEAPF32.buffer,l,8*r),g=new Uint16Array(s.HEAPU8.buffer,h,i),y=t._malloc(a),w=t._malloc(c);t.HEAPF32.set(m,y>>2),new Uint16Array(t.HEAPU8.buffer,w,i).set(g),t.renderer_submitTriangles(y,r,w,i,p,_,d),t._free(y),t._free(w),s._free(l),s._free(h),s._free(u),s._free(f)}d&&t._free(d)}})}(e,t,r,u,n)}if(a){const t=e.getResource(Ut);t&&t.setAddressableManifest(a)}}function ar(e,t,s){return{name:e,data:t,async setup(){await or(s.app,s.module,t,s.provider,s.spineModule,s.physicsModule,s.physicsConfig,s.manifest,e)}}}class cr{constructor(e){this.textCache_=new Map,this.binaryCache_=new Map,this.baseUrl_=e.endsWith("/")?e:e+"/"}async prefetch(e){const t=new Set,s=new Set,n=new Set;for(const r of e.entities)for(const e of r.components)if(e.data){if("SpineAnimation"===e.type){const n=e.data.skeletonPath,r=e.data.atlasPath;n&&("binary"===Pt(n)?.contentType?s.add(n):t.add(n)),r&&t.add(r)}"BitmapText"===e.type&&"string"==typeof e.data.font&&e.data.font&&(n.add(e.data.font),t.add(e.data.font)),"string"==typeof e.data.material&&e.data.material&&t.add(e.data.material)}const r=[];for(const e of t)r.push(fetch(this.resolveUrl(e)).then(e=>e.text()).then(t=>{this.textCache_.set(e,t)}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch text "${e}":`,t)}));for(const e of s)r.push(fetch(this.resolveUrl(e)).then(e=>e.arrayBuffer()).then(t=>{this.binaryCache_.set(e,new Uint8Array(t))}).catch(t=>{console.warn(`[WebAssetProvider] Failed to prefetch binary "${e}":`,t)}));await Promise.all(r);const i=[];for(const e of n){const t=Pt(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)||i.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{}}i.length>0&&await Promise.all(i)}readText(e){const t=this.textCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}readBinary(e){const t=this.binaryCache_.get(e);if(void 0!==t)return t;throw new Error("Asset not prefetched: "+e)}async loadPixels(e){const t=this.resolveUrl(e),s=await fetch(t),n=await s.blob(),r=await createImageBitmap(n),i=new OffscreenCanvas(r.width,r.height).getContext("2d");i.drawImage(r,0,0);const o=i.getImageData(0,0,r.width,r.height);return r.close(),{width:o.width,height:o.height,pixels:new Uint8Array(o.data.buffer)}}resolvePath(e){return e}resolveUrl(e){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("/")?e:this.baseUrl_+e}}const lr="__preview__";class hr{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(Ws);t.register({name:lr,setup:async()=>{await this.loadRuntimeData(),this.ensureCamera()}}),t.setInitial(lr),this.loadPromise_=t.load(lr).then(()=>{}),this.setupHotReload()}async waitForReady(){this.loadPromise_&&await this.loadPromise_}async loadRuntimeData(){if(!this.app_)return;const e=await o(this.sceneUrl_);if(!e.ok)throw new Error(`Failed to fetch scene: ${e.status}`);const t=await e.json(),s=new cr(this.baseUrl_);await s.prefetch(t);let n=null;const r=this.app_.spineInitPromise;if(r){n=(await r).controller.raw}await or(this.app_,this.app_.wasmModule,t,s,n,null,void 0,null,lr)}ensureCamera(){if(!this.app_)return;const e=this.app_.world;let t=!1;const s=e.getEntitiesWithComponents([q]);for(const n of s){if(e.get(n,q).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([G]);for(const r of n){const n=e.get(r,G);if(n.designResolution){const e=n.pixelsPerUnit||100;t=n.designResolution.y/2/e,s=n.designResolution.x/n.designResolution.y;break}}const r=this.app_.getResource(Ws).getScene(lr),i=r?r.spawn():e.spawn(),o={position:{x:0,y:0,z:10},rotation:{x:0,y:0,z:0,w:1},scale:{x:1,y:1,z:1}};e.insert(i,V,o);const a={isActive:!0,projectionType:W.Orthographic,fov:60,orthoSize:t,nearPlane:.1,farPlane:1e3,aspectRatio:s,priority:0,showFrustum:!1,viewportX:0,viewportY:0,viewportW:1,viewportH:1,clearFlags:j.ColorAndDepth};e.insert(i,q,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(Ws);await e.switchTo(lr),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 ur={create(e){const t=(e.depth??!0?1:0)|("linear"===e.filter?2:0),s=Fs.createRenderTarget(e.width,e.height,t);return{_handle:s,textureId:Fs.getTargetTexture(s),width:e.width,height:e.height}},release(e){Fs.releaseRenderTarget(e._handle)},resize:(e,t,s)=>(Fs.releaseRenderTarget(e._handle),ur.create({width:t,height:s,depth:!0})),begin(e,t){Fs.begin(t,e._handle)},end(){Fs.end()},getDepthTexture:e=>Fs.getTargetDepthTexture(e._handle)};let dr=!1;function fr(e){dr=e}function pr(){return dr}function _r(){return!dr}var mr;!function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warn=2]="Warn",e[e.Error=3]="Error"}(mr||(mr={}));class gr{handle(e){const t=`[${new Date(e.timestamp).toISOString().substring(11,23)}] [${mr[e.level].toUpperCase().padEnd(5)}] [${e.category}]`,s=void 0!==e.data?`${e.message} ${JSON.stringify(e.data)}`:e.message;switch(e.level){case mr.Debug:console.debug(t,s);break;case mr.Info:console.log(t,s);break;case mr.Warn:console.warn(t,s);break;case mr.Error:console.error(t,s)}}}class yr{constructor(){this.handlers_=[],this.minLevel_=mr.Info,this.addHandler(new gr)}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(mr.Debug,e,t,s)}info(e,t,s){this.log(mr.Info,e,t,s)}warn(e,t,s){this.log(mr.Warn,e,t,s)}error(e,t,s){this.log(mr.Error,e,t,s)}log(e,t,s,n){if(e<this.minLevel_)return;const r={timestamp:Date.now(),level:e,category:t,message:s,data:n};for(const e of this.handlers_)try{e.handle(r)}catch(e){console.error("[Logger] Handler threw error:",e)}}}const wr=new yr;function xr(){return wr}function vr(e){wr.setMinLevel(e)}function br(e,t,s){wr.debug(e,t,s)}function Sr(e,t,s){wr.info(e,t,s)}function Pr(e,t,s){wr.warn(e,t,s)}function Cr(e,t,s){wr.error(e,t,s)}const Tr=[_n,Cn,Un,Wn,Yn];function Er(e,t){return function(e,t){const s=Xs.new(),n=new e.Registry;s.connectCpp(n,e),t?.glContextHandle?e.initRendererWithContext(t.glContextHandle):e.initRenderer(),es(e),Je(e),gs(e),bs(e),As(e),ks(e);const r=new Ds;s.setPipeline(r);let i=d();const o=t?.getViewportSize??(()=>({width:window.innerWidth*(window.devicePixelRatio||1),height:window.innerHeight*(window.devicePixelRatio||1)}));function a(t,r,i){i||(i=Js(e,n,t,r));const o=s.getResource(je);if(i.length>0){const e=i[0],s=e.viewportRect;o.viewProjection.set(e.viewProjection),o.vpX=Math.round(s.x*t),o.vpY=Math.round((1-s.y-s.h)*r),o.vpW=Math.round(s.w*t),o.vpH=Math.round(s.h*r),o.screenW=t,o.screenH=r,o.worldLeft=e.cameraX-e.halfW,o.worldRight=e.cameraX+e.halfW,o.worldBottom=e.cameraY-e.halfH,o.worldTop=e.cameraY+e.halfH,o.valid=!0}else o.valid=!1}s.insertResource(je,{viewProjection:new Float32Array(16),vpX:0,vpY:0,vpW:0,vpH:0,screenW:0,screenH:0,worldLeft:0,worldBottom:0,worldRight:0,worldTop:0,valid:!1});const c={_id:Symbol("UICameraSyncSystem"),_name:"UICameraSyncSystem",_params:[],_fn:()=>{const{width:e,height:t}=o();a(e,t)}},l={_id:Symbol("RenderSystem"),_name:"RenderSystem",_params:[],_fn:()=>{const{width:t,height:c}=o();if(0===t||0===c)return;const l=e.registry_getCanvasEntity(n);if(l>=0){const e=n.getCanvas(l).backgroundColor;Fs.setClearColor(e.x,e.y,e.z,e.w)}const h=(d()-i)/1e3;let u;if(Fs.resize(t,c),Cs.isInitialized()&&Cs.getPassCount()>0&&!Cs.isBypassed()&&Cs.resize(t,c),s.hasResource(Ws)){const e=s.getResource(Ws).getActiveScenes();e.length>0&&(u=new Set(e))}r.setActiveScenes(u??null);const f=Js(e,n,t,c,s.world,u);if(a(t,c,f),0===f.length)r.render({registry:{_cpp:n},viewProjection:qs,width:t,height:c,elapsed:h});else{for(const e of f){const s=e.viewportRect,i=Math.round(s.x*t),o=Math.round((1-s.y-s.h)*c),a=Math.round(s.w*t),l=Math.round(s.h*c);r.renderCamera({registry:{_cpp:n},viewProjection:e.viewProjection,viewportPixels:{x:i,y:o,w:a,h:l},clearFlags:e.clearFlags,elapsed:h})}Fs.setViewport(0,0,t,c)}}};if(s.addSystemToSchedule(Se.First,c),s.addSystemToSchedule(Se.Last,l),s.addPlugin(zt),s.addPlugin(qt),s.addPlugin(ke),s.addPlugin(Vs),t?.plugins)for(const e of t.plugins)s.addPlugin(e);return s}(e,{plugins:Tr,...t})}e=f;export{Xs as App,Dt as AssetPlugin,Lt as AssetRefCounter,Bt as AssetServer,Ut as Assets,ct as AsyncCache,Z as BitmapText,Ne as BlendMode,ce as BodyType,ie as BoxCollider,Rn as Button,Mn as ButtonState,q as Camera,G as Canvas,ae as CapsuleCollider,Q as Children,oe as CircleCollider,j as ClearFlags,xe as Commands,be as CommandsInstance,_ as DEFAULT_DESIGN_HEIGHT,p as DEFAULT_DESIGN_WIDTH,m as DEFAULT_PIXELS_PER_UNIT,g as DEFAULT_TEXT_CANVAS_SIZE,ds as DataType,rs as Draw,ve as EntityCommands,Us as GLDebug,xs as Geometry,x as INVALID_ENTITY,b as INVALID_FONT,v as INVALID_TEXTURE,Fe as Input,$e as InputPlugin,Ie as InputState,Tn as Interactable,V as LocalTransform,mr as LogLevel,yr as Logger,Ze as Material,lt as MaterialLoader,me as Mut,te as Name,K as Parent,sr as Physics,Jn as PhysicsEvents,er as PhysicsPlugin,Cs as PostProcess,Vt as PrefabServer,Xt as Prefabs,Yt as PrefabsPlugin,hr as PreviewPlugin,W as ProjectionType,ye as Query,we as QueryInstance,Ds as RenderPipeline,Es as RenderStage,ur as RenderTexture,Fs as Renderer,ue as Res,de as ResMut,re as RigidBody,y as RuntimeConfig,N as ScaleMode,Ws as SceneManager,Hs as SceneManagerState,se as SceneOwner,Se as Schedule,Fn as ScreenSpace,at as ShaderSources,ee as SpineAnimation,Y as Sprite,Ae as SystemRunner,ln as Text,on as TextAlign,jn as TextInput,Nn as TextInputPlugin,cn as TextOverflow,pn as TextPlugin,un as TextRenderer,an as TextVerticalAlign,_e as Time,je as UICameraInfo,An as UIEventQueue,In as UIEvents,En as UIInteraction,Hn as UIInteractionPlugin,Bn as UILayoutPlugin,mn as UIMask,Pn as UIMaskPlugin,hn as UIRect,J as Velocity,cr as WebAssetProvider,We as World,X as WorldTransform,Me as addStartupSystem,Ee as addSystem,Re as addSystemToSchedule,w as applyRuntimeConfig,zt as assetPlugin,us as clearDrawCallbacks,B as clearUserComponents,T as color,$n as computeUIRectLayout,Sn as createMaskProcessor,ar as createRuntimeSceneConfig,Er as createWebApp,br as debug,F as defineComponent,he as defineResource,Ce as defineSystem,$ as defineTag,Cr as error,yt as findEntityByName,Ys as flushPendingSystems,Tt as getAddressableType,Et as getAddressableTypeByEditorType,Rt as getAllAssetExtensions,$t as getAssetMimeType,Pt as getAssetTypeEntry,O as getComponent,dt as getComponentAssetFields,ne as getComponentDefaults,It as getCustomExtensions,Ct as getEditorType,xr as getLogger,t as getPlatform,n as getPlatformType,k as getUserComponent,Ft as getWeChatPackOptions,Sr as info,es as initDrawAPI,ks as initGLDebugAPI,gs as initGeometryAPI,Je as initMaterialAPI,bs as initPostProcessAPI,As as initRendererAPI,ke as inputPlugin,Ht as instantiatePrefab,gn as intersectRects,wn as invertMatrix4,D as isBuiltinComponent,kt as isCustomExtension,pr as isEditor,Mt as isKnownAssetExtension,s as isPlatformInitialized,_r as isRuntime,Ve as isTextureRef,r as isWeChat,i as isWeb,mt as loadComponent,Gn as loadPhysicsModule,or as loadRuntimeScene,pt as loadSceneData,_t as loadSceneWithAssets,At as looksLikeAssetPath,o as platformFetch,l as platformFileExists,h as platformInstantiateWasm,a as platformReadFile,c as platformReadTextFile,vn as pointInWorldRect,qt as prefabsPlugin,E as quat,L as registerComponent,ut as registerComponentAssetFields,ls as registerDrawCallback,Ot as registerEmbeddedAssets,ot as registerMaterialCallback,Vs as sceneManagerPlugin,xn as screenToWorld,fr as setEditorMode,vr as setLogLevel,Le as setWasmErrorHandler,ts as shutdownDrawAPI,Bs as shutdownGLDebugAPI,ys as shutdownGeometryAPI,Ke as shutdownMaterialAPI,Ss as shutdownPostProcessAPI,Is as shutdownRendererAPI,Yn as textInputPlugin,_n as textPlugin,qn as transitionTo,Wn as uiInteractionPlugin,Un as uiLayoutPlugin,Cn as uiMaskPlugin,Tr as uiPlugins,hs as unregisterDrawCallback,gt as updateCameraAspectRatio,S as vec2,P as vec3,C as vec4,Pr as warn,yn as worldRectToScreen,js 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 c84a8842a..39a846bd7 100644
--- a/desktop/public/sdk/esm/physics/index.d.ts
+++ b/desktop/public/sdk/esm/physics/index.d.ts
@@ -493,6 +493,7 @@ declare class World {
private removeScript;
private getStorage;
resetQueryPool(): void;
+ getComponentTypes(entity: Entity): string[];
getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
@@ -698,6 +699,9 @@ declare class App {
private error_handler_;
private system_error_handler_;
private frame_paused_;
+ private user_paused_;
+ private step_pending_;
+ private play_speed_;
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
@@ -725,6 +729,11 @@ declare class App {
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;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
diff --git a/desktop/public/sdk/esm/spine/index.d.ts b/desktop/public/sdk/esm/spine/index.d.ts
index 60e794452..37bca8466 100644
--- a/desktop/public/sdk/esm/spine/index.d.ts
+++ b/desktop/public/sdk/esm/spine/index.d.ts
@@ -448,6 +448,7 @@ declare class World {
private removeScript;
private getStorage;
resetQueryPool(): void;
+ getComponentTypes(entity: Entity): string[];
getEntitiesWithComponents(components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]): Entity[];
}
@@ -773,6 +774,9 @@ declare class App {
private error_handler_;
private system_error_handler_;
private frame_paused_;
+ private user_paused_;
+ private step_pending_;
+ private play_speed_;
private constructor();
static new(): App;
addPlugin(plugin: Plugin): this;
@@ -800,6 +804,11 @@ declare class App {
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;
insertResource<T>(resource: ResourceDef<T>, value: T): this;
getResource<T>(resource: ResourceDef<T>): T;
hasResource<T>(resource: ResourceDef<T>): boolean;
diff --git a/desktop/src-tauri/src/preview_template.html b/desktop/src-tauri/src/preview_template.html
index 811fb8fe4..f585942cf 100644
--- a/desktop/src-tauri/src/preview_template.html
+++ b/desktop/src-tauri/src/preview_template.html
@@ -133,12 +133,15 @@
break;
}
}
+ if (requestId !== undefined) {
+ window.parent.postMessage({ type, requestId, data: response }, '*');
+ }
} catch (e) {
- response = { error: e.message || String(e) };
- }
-
- if (requestId !== undefined) {
- window.parent.postMessage({ type, requestId, data: response }, '*');
+ if (requestId !== undefined) {
+ try {
+ window.parent.postMessage({ type, requestId, data: { error: e.message || String(e) } }, '*');
+ } catch {}
+ }
}
});
@@ -146,7 +149,9 @@
if (!gameApp) return [];
const world = gameApp.world;
const sdk = window.__esSdk;
- const entities = world.getAllEntities();
+ const rawEntities = world.getAllEntities();
+ const entities = [];
+ for (let i = 0; i < rawEntities.length; i++) entities.push(Number(rawEntities[i]));
return entities.map(entityId => {
const name = getEntityName(world, entityId);
const componentTypes = getComponentTypes(world, entityId);
@@ -182,7 +187,7 @@
const nameDef = sdk.getComponent('Name');
if (nameDef) {
const nameData = world.tryGet(entityId, nameDef);
- if (nameData && nameData.value) return nameData.value;
+ if (nameData && nameData.value) return String(nameData.value);
}
} catch {}
}
@@ -192,7 +197,8 @@
function getComponentTypes(world, entityId) {
try {
if (world.getComponentTypes) {
- return world.getComponentTypes(entityId);
+ const types = world.getComponentTypes(entityId);
+ return types.map(t => String(t));
}
} catch {}
return [];
@@ -202,7 +208,7 @@
if (!sdk) return null;
try {
const parent = world.tryGet(entityId, sdk.Parent);
- if (parent && parent.entity !== undefined && parent.entity !== 0) return parent.entity;
+ if (parent && parent.entity !== undefined && parent.entity !== 0) return Number(parent.entity);
} catch {}
return null;
}
@@ -211,7 +217,12 @@
if (!sdk) return [];
try {
const children = world.tryGet(entityId, sdk.Children);
- if (children && Array.isArray(children.entities)) return children.entities;
+ if (children && children.entities) {
+ const arr = children.entities;
+ const result = [];
+ for (let i = 0; i < arr.length; i++) result.push(Number(arr[i]));
+ return result;
+ }
} catch {}
return [];
}
@@ -232,6 +243,15 @@
return String(val);
}
+ function serializeBuiltinComponent(data, compDef) {
+ if (!compDef || !compDef._default) return serializeValue(data);
+ const out = {};
+ for (const key of Object.keys(compDef._default)) {
+ try { out[key] = serializeValue(data[key]); } catch {}
+ }
+ return out;
+ }
+
function getComponentData(world, entityId, typeName) {
const sdk = window.__esSdk;
if (!sdk) return {};
@@ -240,7 +260,7 @@
if (!compDef) return {};
const data = world.tryGet(entityId, compDef);
if (!data) return {};
- return serializeValue(data);
+ return compDef._builtin ? serializeBuiltinComponent(data, compDef) : serializeValue(data);
} catch { return {}; }
}
@@ -256,7 +276,7 @@
if (!current) return;
if (compDef._builtin) {
- const snapshot = serializeValue(current);
+ const snapshot = serializeBuiltinComponent(current, compDef);
snapshot[property] = value;
world.insert(entityId, compDef, snapshot);
} else {
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 8946cb1f9..beae0d331 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -92,6 +92,7 @@ export class InspectorPanel {
}),
pms.onSelectionChange((entityId) => {
if (!this.playMode_) return;
+ if (entityId === this.runtimeEntityId_) return;
this.runtimeEntityId_ = entityId;
if (entityId !== null) {
this.renderRuntimeEntity(entityId);
@@ -383,7 +384,13 @@ export class InspectorPanel {
return;
}
const fresh = await pms.querySelectedEntity();
- if (fresh && this.runtimeEntityId_ === entityId) {
+ if (!fresh) {
+ this.stopRuntimeRefresh();
+ this.contentContainer_.innerHTML = '<div class="es-inspector-empty">Entity despawned</div>';
+ this.updateFooter('Runtime mode');
+ return;
+ }
+ if (this.runtimeEntityId_ === entityId) {
updateRuntimeEntityValues(this.contentContainer_, fresh);
}
}, 500);
diff --git a/editor/src/panels/game-view/GameInstanceManager.ts b/editor/src/panels/game-view/GameInstanceManager.ts
index 7ada566b0..26f3f6518 100644
--- a/editor/src/panels/game-view/GameInstanceManager.ts
+++ b/editor/src/panels/game-view/GameInstanceManager.ts
@@ -1,6 +1,6 @@
import { getEditorInstance } from '../../context/EditorContext';
-export type GameState = 'stopped' | 'playing';
+export type GameState = 'stopped' | 'playing' | 'paused';
export interface GameInstanceCallbacks {
onStateChange(state: GameState): void;
@@ -42,6 +42,18 @@ export class GameInstanceManager {
}
}
+ pause(): void {
+ if (this.state_ === 'playing') {
+ this.setState('paused');
+ }
+ }
+
+ resume(): void {
+ if (this.state_ === 'paused') {
+ this.setState('playing');
+ }
+ }
+
async stop(): Promise<void> {
this.setState('stopped');
}
diff --git a/editor/src/panels/game-view/GameViewToolbar.ts b/editor/src/panels/game-view/GameViewToolbar.ts
index bddc77dbc..1155b1948 100644
--- a/editor/src/panels/game-view/GameViewToolbar.ts
+++ b/editor/src/panels/game-view/GameViewToolbar.ts
@@ -18,6 +18,10 @@ const RESOLUTION_PRESETS: ResolutionPreset[] = [
export interface GameViewToolbarCallbacks {
onPlay(): void;
onStop(): void;
+ onPause(): void;
+ onResume(): void;
+ onStepFrame(): void;
+ onSpeedChange(speed: number): void;
onResolutionChange(preset: ResolutionPreset): void;
}
@@ -25,7 +29,11 @@ export class GameViewToolbar {
private container_: HTMLElement;
private callbacks_: GameViewToolbarCallbacks;
private playBtn_: HTMLButtonElement | null = null;
+ private pauseBtn_: HTMLButtonElement | null = null;
+ private resumeBtn_: HTMLButtonElement | null = null;
+ private stepBtn_: HTMLButtonElement | null = null;
private stopBtn_: HTMLButtonElement | null = null;
+ private speedSelect_: HTMLSelectElement | null = null;
private fpsDisplay_: HTMLSpanElement | null = null;
private resolutionSelect_: HTMLSelectElement | null = null;
private customSizeEl_: HTMLElement | null = null;
@@ -47,9 +55,20 @@ export class GameViewToolbar {
<div class="es-gameview-toolbar">
<div class="es-gameview-controls">
<button class="es-btn es-btn-icon es-gameview-play" title="Play">${icons.play(14)}</button>
+ <button class="es-btn es-btn-icon es-gameview-pause" title="Pause" disabled>${icons.pause(14)}</button>
+ <button class="es-btn es-btn-icon es-gameview-resume" title="Resume" style="display:none">${icons.play(14)}</button>
+ <button class="es-btn es-btn-icon es-gameview-step" title="Step Frame" disabled>${icons.stepForward(14)}</button>
<button class="es-btn es-btn-icon es-gameview-stop" title="Stop" disabled>${icons.stop(14)}</button>
</div>
<div class="es-toolbar-divider"></div>
+ <select class="es-gameview-speed" title="Play Speed">
+ <option value="0.25">0.25x</option>
+ <option value="0.5">0.5x</option>
+ <option value="1" selected>1x</option>
+ <option value="2">2x</option>
+ <option value="4">4x</option>
+ </select>
+ <div class="es-toolbar-divider"></div>
<select class="es-gameview-resolution">${options}<option value="custom">Custom</option></select>
<div class="es-gameview-custom-size" style="display:none">
<input type="number" class="es-gameview-custom-w" placeholder="W" min="1" max="7680" />
@@ -63,7 +82,11 @@ export class GameViewToolbar {
setup(): void {
this.playBtn_ = this.container_.querySelector('.es-gameview-play');
+ this.pauseBtn_ = this.container_.querySelector('.es-gameview-pause');
+ this.resumeBtn_ = this.container_.querySelector('.es-gameview-resume');
+ this.stepBtn_ = this.container_.querySelector('.es-gameview-step');
this.stopBtn_ = this.container_.querySelector('.es-gameview-stop');
+ this.speedSelect_ = this.container_.querySelector('.es-gameview-speed');
this.fpsDisplay_ = this.container_.querySelector('.es-gameview-fps');
this.resolutionSelect_ = this.container_.querySelector('.es-gameview-resolution');
this.customSizeEl_ = this.container_.querySelector('.es-gameview-custom-size');
@@ -71,8 +94,16 @@ export class GameViewToolbar {
this.customHeightInput_ = this.container_.querySelector('.es-gameview-custom-h');
this.playBtn_?.addEventListener('click', () => this.callbacks_.onPlay());
+ this.pauseBtn_?.addEventListener('click', () => this.callbacks_.onPause());
+ this.resumeBtn_?.addEventListener('click', () => this.callbacks_.onResume());
+ this.stepBtn_?.addEventListener('click', () => this.callbacks_.onStepFrame());
this.stopBtn_?.addEventListener('click', () => this.callbacks_.onStop());
+ this.speedSelect_?.addEventListener('change', () => {
+ const speed = parseFloat(this.speedSelect_!.value);
+ this.callbacks_.onSpeedChange(speed);
+ });
+
this.resolutionSelect_?.addEventListener('change', () => {
const val = this.resolutionSelect_!.value;
if (val === 'custom') {
@@ -100,10 +131,17 @@ export class GameViewToolbar {
updateState(state: GameState): void {
if (!this.playBtn_) return;
- const playing = state === 'playing';
const stopped = state === 'stopped';
-
- this.playBtn_.disabled = playing;
+ const playing = state === 'playing';
+ const paused = state === 'paused';
+
+ this.playBtn_.disabled = playing || paused;
+ this.playBtn_.style.display = paused ? 'none' : '';
+ this.pauseBtn_!.disabled = !playing;
+ this.pauseBtn_!.style.display = paused ? 'none' : '';
+ this.resumeBtn_!.style.display = paused ? '' : 'none';
+ this.resumeBtn_!.disabled = !paused;
+ this.stepBtn_!.disabled = !paused;
this.stopBtn_!.disabled = stopped;
this.playBtn_.classList.toggle('es-active', playing);
@@ -120,7 +158,11 @@ export class GameViewToolbar {
dispose(): void {
this.playBtn_ = null;
+ this.pauseBtn_ = null;
+ this.resumeBtn_ = null;
+ this.stepBtn_ = null;
this.stopBtn_ = null;
+ this.speedSelect_ = null;
this.fpsDisplay_ = null;
this.resolutionSelect_ = null;
this.customSizeEl_ = null;
diff --git a/editor/src/panels/hierarchy/HierarchyDragDrop.ts b/editor/src/panels/hierarchy/HierarchyDragDrop.ts
index 48b56ff75..100eec9f9 100644
--- a/editor/src/panels/hierarchy/HierarchyDragDrop.ts
+++ b/editor/src/panels/hierarchy/HierarchyDragDrop.ts
@@ -6,6 +6,8 @@ export function setupDragAndDrop(
createEntityFromAsset: (asset: { type: string; path: string; name: string }, parent: Entity | null) => Promise<void>,
): void {
state.treeContainer.addEventListener('dragstart', (e) => {
+ if (state.playMode) { e.preventDefault(); return; }
+
const target = e.target as HTMLElement;
const row = target.closest('.es-hierarchy-row') as HTMLElement;
const item = row?.parentElement as HTMLElement;
@@ -31,6 +33,8 @@ export function setupDragAndDrop(
});
state.treeContainer.addEventListener('dragover', (e) => {
+ if (state.playMode) { e.preventDefault(); return; }
+
const types = e.dataTransfer?.types ?? [];
const hasAssetData = Array.from(types).includes('application/esengine-asset');
const hasEntityData = Array.from(types).includes('application/esengine-entity');
@@ -86,6 +90,8 @@ export function setupDragAndDrop(
});
state.treeContainer.addEventListener('drop', (e) => {
+ if (state.playMode) { e.preventDefault(); return; }
+
e.preventDefault();
const assetDataStr = e.dataTransfer?.getData('application/esengine-asset');
diff --git a/editor/src/panels/hierarchy/HierarchyKeyboard.ts b/editor/src/panels/hierarchy/HierarchyKeyboard.ts
index bc93e7983..fc3350db2 100644
--- a/editor/src/panels/hierarchy/HierarchyKeyboard.ts
+++ b/editor/src/panels/hierarchy/HierarchyKeyboard.ts
@@ -3,6 +3,8 @@ import type { HierarchyState } from './HierarchyTypes';
export function setupKeyboard(state: HierarchyState, scrollToEntity: (id: number) => void): void {
state.treeContainer.addEventListener('keydown', (e) => {
+ if (state.playMode) return;
+
if (state.renamingEntityId !== null) {
return;
}
diff --git a/editor/src/panels/hierarchy/HierarchyPanel.ts b/editor/src/panels/hierarchy/HierarchyPanel.ts
index 4e5e901b6..d80bd879f 100644
--- a/editor/src/panels/hierarchy/HierarchyPanel.ts
+++ b/editor/src/panels/hierarchy/HierarchyPanel.ts
@@ -44,6 +44,7 @@ export class HierarchyPanel implements HierarchyState {
playMode: boolean = false;
private playModeCleanups_: (() => void)[] = [];
private toolbar_: HTMLElement | null = null;
+ private editorExpandedIds_: Set<number> | null = null;
constructor(container: HTMLElement, store: EditorStore) {
this.container_ = container;
@@ -104,9 +105,15 @@ export class HierarchyPanel implements HierarchyState {
if (this.playMode) {
this.container_.classList.add('es-play-mode');
this.setToolbarDisabled(true);
+ this.editorExpandedIds_ = new Set(this.expandedIds);
+ this.expandedIds = new Set();
} else {
this.container_.classList.remove('es-play-mode');
this.setToolbarDisabled(false);
+ if (this.editorExpandedIds_) {
+ this.expandedIds = this.editorExpandedIds_;
+ this.editorExpandedIds_ = null;
+ }
}
this.render();
}),
@@ -515,10 +522,19 @@ export class HierarchyPanel implements HierarchyState {
private setToolbarDisabled(disabled: boolean): void {
if (!this.toolbar_) return;
- const buttons = this.toolbar_.querySelectorAll('[data-action="add"], [data-action="duplicate"]');
+ const buttons = this.toolbar_.querySelectorAll('[data-action="add"], [data-action="duplicate"], [data-action="expand-all"], [data-action="collapse-all"]');
for (const btn of buttons) {
(btn as HTMLButtonElement).disabled = disabled;
}
+ if (this.searchInput) {
+ this.searchInput.disabled = disabled;
+ if (disabled) {
+ this.searchInput.value = '';
+ this.searchFilter = '';
+ this.searchResults = [];
+ this.selectedResultIndex = -1;
+ }
+ }
}
private onScroll(): void {
diff --git a/editor/src/panels/inspector/RuntimeEntityRenderer.ts b/editor/src/panels/inspector/RuntimeEntityRenderer.ts
index b060c19db..d78e9d4c5 100644
--- a/editor/src/panels/inspector/RuntimeEntityRenderer.ts
+++ b/editor/src/panels/inspector/RuntimeEntityRenderer.ts
@@ -10,11 +10,22 @@ export function renderRuntimeEntity(
const header = document.createElement('div');
header.className = 'es-inspector-entity-header';
- header.innerHTML = `
- <span class="es-entity-icon">${icons.box(16)}</span>
- <span class="es-entity-name">${data.name || 'Entity ' + data.entityId}</span>
- <span class="es-entity-id">#${data.entityId}</span>
- `;
+
+ const iconSpan = document.createElement('span');
+ iconSpan.className = 'es-entity-icon';
+ iconSpan.innerHTML = icons.box(16);
+
+ const nameSpan = document.createElement('span');
+ nameSpan.className = 'es-entity-name';
+ nameSpan.textContent = data.name || 'Entity ' + data.entityId;
+
+ const idSpan = document.createElement('span');
+ idSpan.className = 'es-entity-id';
+ idSpan.textContent = '#' + data.entityId;
+
+ header.appendChild(iconSpan);
+ header.appendChild(nameSpan);
+ header.appendChild(idSpan);
container.appendChild(header);
for (const comp of data.components) {
@@ -23,10 +34,17 @@ export function renderRuntimeEntity(
const compHeader = document.createElement('div');
compHeader.className = 'es-component-header es-collapsible-header';
- compHeader.innerHTML = `
- <span class="es-collapse-icon">${icons.chevronDown(12)}</span>
- <span class="es-component-title">${comp.type}</span>
- `;
+
+ const collapseIcon = document.createElement('span');
+ collapseIcon.className = 'es-collapse-icon';
+ collapseIcon.innerHTML = icons.chevronDown(12);
+
+ const titleSpan = document.createElement('span');
+ titleSpan.className = 'es-component-title';
+ titleSpan.textContent = comp.type;
+
+ compHeader.appendChild(collapseIcon);
+ compHeader.appendChild(titleSpan);
compHeader.addEventListener('click', () => section.classList.toggle('es-expanded'));
section.appendChild(compHeader);
@@ -61,10 +79,22 @@ export function updateRuntimeEntityValues(
): void {
for (const comp of data.components) {
for (const [key, value] of Object.entries(comp.data)) {
- const input = container.querySelector(
+ const el = container.querySelector(
`[data-rt-comp="${comp.type}"][data-rt-prop="${key}"]`
- ) as HTMLInputElement | null;
- if (!input) continue;
+ ) as HTMLElement | null;
+ if (!el) continue;
+
+ if (el.getAttribute('data-rt-kind') === 'object' && value && typeof value === 'object') {
+ const obj = value as Record<string, number>;
+ for (const [subKey, subVal] of Object.entries(obj)) {
+ const inp = el.querySelector(`[data-rt-key="${subKey}"]`) as HTMLInputElement | null;
+ if (!inp || document.activeElement === inp) continue;
+ inp.value = String(Math.round(subVal * 1000) / 1000);
+ }
+ continue;
+ }
+
+ const input = el as HTMLInputElement;
if (document.activeElement === input) continue;
if (input.type === 'checkbox') {
@@ -121,9 +151,14 @@ function createRuntimePropertyEditor(
container.appendChild(input);
} else if (value && typeof value === 'object' && !Array.isArray(value)) {
const obj = value as Record<string, number>;
+ const vecWrapper = document.createElement('div');
+ vecWrapper.className = 'es-runtime-vec-wrapper';
+ vecWrapper.setAttribute('data-rt-comp', componentType);
+ vecWrapper.setAttribute('data-rt-prop', property);
+ vecWrapper.setAttribute('data-rt-kind', 'object');
for (const k of Object.keys(obj)) {
- const wrapper = document.createElement('span');
- wrapper.className = 'es-runtime-vec-field';
+ const field = document.createElement('span');
+ field.className = 'es-runtime-vec-field';
const lbl = document.createElement('span');
lbl.className = 'es-runtime-vec-label';
lbl.textContent = k;
@@ -132,14 +167,16 @@ function createRuntimePropertyEditor(
inp.className = 'es-input es-runtime-vec-input';
inp.value = String(Math.round(obj[k] * 1000) / 1000);
inp.step = 'any';
+ inp.dataset.rtKey = k;
inp.addEventListener('change', () => {
const newObj = { ...obj, [k]: parseFloat(inp.value) };
bridge?.setEntityProperty(entityId, componentType, property, newObj);
});
- wrapper.appendChild(lbl);
- wrapper.appendChild(inp);
- container.appendChild(wrapper);
+ field.appendChild(lbl);
+ field.appendChild(inp);
+ vecWrapper.appendChild(field);
}
+ container.appendChild(vecWrapper);
} else {
const span = document.createElement('span');
span.className = 'es-runtime-readonly';
diff --git a/editor/src/services/PlayModeService.ts b/editor/src/services/PlayModeService.ts
index 495bdb9e5..8637a23ed 100644
--- a/editor/src/services/PlayModeService.ts
+++ b/editor/src/services/PlayModeService.ts
@@ -11,8 +11,9 @@ class PlayModeService {
private bridge_: GameViewBridge | null = null;
private selectedEntityId_: number | null = null;
private cachedEntities_: RuntimeEntityData[] = [];
- private pollTimer_: ReturnType<typeof setInterval> | null = null;
- private detailTimer_: ReturnType<typeof setInterval> | null = null;
+ private pollTimer_: ReturnType<typeof setTimeout> | null = null;
+ private isRefreshing_ = false;
+ private consecutiveFailures_ = 0;
private stateListeners_ = new Set<StateChangeCallback>();
private entityListListeners_ = new Set<EntityListCallback>();
private selectionListeners_ = new Set<SelectionCallback>();
@@ -23,6 +24,7 @@ class PlayModeService {
get selectedEntityId(): number | null { return this.selectedEntityId_; }
enter(bridge: GameViewBridge): void {
+ if (this.state_ === 'playing') this.exit();
this.bridge_ = bridge;
this.state_ = 'playing';
this.cachedEntities_ = [];
@@ -33,7 +35,6 @@ class PlayModeService {
exit(): void {
this.stopPolling();
- this.stopDetailPolling();
this.bridge_ = null;
this.state_ = 'stopped';
this.cachedEntities_ = [];
@@ -45,11 +46,6 @@ class PlayModeService {
selectEntity(id: number | null): void {
this.selectedEntityId_ = id;
this.emitSelectionChange();
- if (id !== null) {
- this.startDetailPolling();
- } else {
- this.stopDetailPolling();
- }
}
onStateChange(cb: StateChangeCallback): () => void {
@@ -68,47 +64,55 @@ class PlayModeService {
}
async refreshEntityList(): Promise<void> {
- if (!this.bridge_?.isReady) return;
+ if (this.isRefreshing_ || !this.bridge_?.isReady) return;
+ this.isRefreshing_ = true;
try {
this.cachedEntities_ = await this.bridge_.queryEntityList();
+ this.consecutiveFailures_ = 0;
this.emitEntityListUpdate();
- } catch {}
+ } catch (e) {
+ this.consecutiveFailures_++;
+ if (this.consecutiveFailures_ <= 3) {
+ console.warn('[PlayModeService] refresh failed:', e);
+ }
+ } finally {
+ this.isRefreshing_ = false;
+ }
}
async querySelectedEntity(): Promise<RuntimeEntityData | null> {
if (this.selectedEntityId_ === null || !this.bridge_?.isReady) return null;
try {
return await this.bridge_.queryEntity(this.selectedEntityId_);
- } catch { return null; }
+ } catch (e) {
+ console.warn('[PlayModeService] querySelectedEntity failed:', e);
+ return null;
+ }
}
private startPolling(): void {
this.stopPolling();
+ this.consecutiveFailures_ = 0;
this.refreshEntityList();
- this.pollTimer_ = setInterval(() => this.refreshEntityList(), 1000);
+ this.schedulePoll();
+ }
+
+ private schedulePoll(): void {
+ if (this.state_ !== 'playing') return;
+ const delay = this.consecutiveFailures_ > 2 ? 5000 : 1000;
+ this.pollTimer_ = setTimeout(async () => {
+ await this.refreshEntityList();
+ this.schedulePoll();
+ }, delay);
}
private stopPolling(): void {
if (this.pollTimer_) {
- clearInterval(this.pollTimer_);
+ clearTimeout(this.pollTimer_);
this.pollTimer_ = null;
}
}
- private startDetailPolling(): void {
- this.stopDetailPolling();
- this.detailTimer_ = setInterval(() => {
- this.emitSelectionChange();
- }, 500);
- }
-
- private stopDetailPolling(): void {
- if (this.detailTimer_) {
- clearInterval(this.detailTimer_);
- this.detailTimer_ = null;
- }
- }
-
private emitStateChange(): void {
for (const cb of this.stateListeners_) cb(this.state_);
}
diff --git a/editor/src/styles/base.css b/editor/src/styles/base.css
index 593526454..99d2b758a 100644
--- a/editor/src/styles/base.css
+++ b/editor/src/styles/base.css
@@ -25,6 +25,7 @@
--es-accent-gold: #d19a66;
--es-prefab: #4fc1ff;
--es-drag: #61afef;
+ --es-play-mode: #4a9eff;
--es-selection-bg: rgba(209, 154, 102, 0.2);
--es-radius-sm: 3px;
--es-radius-md: 4px;
diff --git a/editor/src/styles/game-view.css b/editor/src/styles/game-view.css
index 618a52e1a..ac872e986 100644
--- a/editor/src/styles/game-view.css
+++ b/editor/src/styles/game-view.css
@@ -138,41 +138,6 @@
border-color: var(--es-accent);
}
-/* Runtime property editors (used by InspectorPanel in play mode) */
-.es-runtime-input {
- width: 100%;
- height: 20px;
- padding: 1px 4px;
- font-size: 11px;
-}
-
-.es-runtime-vec-field {
- display: inline-flex;
- align-items: center;
- gap: 2px;
- margin-right: 4px;
-}
-
-.es-runtime-vec-label {
- font-size: 10px;
- color: var(--es-text-secondary);
- text-transform: uppercase;
- min-width: 8px;
-}
-
-.es-runtime-vec-input {
- width: 52px;
- height: 20px;
- padding: 1px 3px;
- font-size: 11px;
-}
-
-.es-runtime-readonly {
- font-size: 11px;
- color: var(--es-text-secondary);
- word-break: break-all;
-}
-
/* Viewport layout */
.es-gameview-canvas-area {
flex: 1;
diff --git a/editor/src/styles/hierarchy.css b/editor/src/styles/hierarchy.css
index 098c7c1cc..f889cb546 100644
--- a/editor/src/styles/hierarchy.css
+++ b/editor/src/styles/hierarchy.css
@@ -298,14 +298,14 @@
/* Play mode indicator */
.es-hierarchy-panel.es-play-mode {
- border-top: 2px solid #4a9eff;
+ border-top: 2px solid var(--es-play-mode);
}
.es-hierarchy-panel.es-play-mode .es-hierarchy-toolbar::after {
content: 'RUNTIME';
font-size: 9px;
font-weight: 600;
- color: #4a9eff;
+ color: var(--es-play-mode);
padding: 1px 5px;
border-radius: 2px;
background: rgba(74, 158, 255, 0.12);
@@ -314,11 +314,11 @@
.es-hierarchy-panel.es-play-mode .es-hierarchy-item.es-selected > .es-hierarchy-row {
background: rgba(74, 158, 255, 0.3);
- border-left-color: #4a9eff;
+ border-left-color: var(--es-play-mode);
}
.es-hierarchy-panel.es-play-mode .es-hierarchy-item.es-selected > .es-hierarchy-row .es-hierarchy-name {
- color: #4a9eff;
+ color: var(--es-play-mode);
}
.es-hierarchy-footer {
diff --git a/editor/src/styles/inspector.css b/editor/src/styles/inspector.css
index 9d59cad6f..1c0784967 100644
--- a/editor/src/styles/inspector.css
+++ b/editor/src/styles/inspector.css
@@ -1147,16 +1147,51 @@
align-items: flex-start;
}
+/* Runtime property editors */
+.es-runtime-input {
+ width: 100%;
+ height: 20px;
+ padding: 1px 4px;
+ font-size: 11px;
+}
+
+.es-runtime-vec-field {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ margin-right: 4px;
+}
+
+.es-runtime-vec-label {
+ font-size: 10px;
+ color: var(--es-text-secondary);
+ text-transform: uppercase;
+ min-width: 8px;
+}
+
+.es-runtime-vec-input {
+ width: 52px;
+ height: 20px;
+ padding: 1px 3px;
+ font-size: 11px;
+}
+
+.es-runtime-readonly {
+ font-size: 11px;
+ color: var(--es-text-secondary);
+ word-break: break-all;
+}
+
/* Play mode indicator */
.es-inspector-panel.es-play-mode {
- border-top: 2px solid #4a9eff;
+ border-top: 2px solid var(--es-play-mode);
}
.es-inspector-panel.es-play-mode .es-inspector-toolbar::after {
content: 'RUNTIME';
font-size: 9px;
font-weight: 600;
- color: #4a9eff;
+ color: var(--es-play-mode);
padding: 1px 5px;
border-radius: 2px;
background: rgba(74, 158, 255, 0.12);
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index dd12a79e2..64e274832 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -76,6 +76,9 @@ export class App {
private error_handler_: ((error: unknown, systemName: string) => void) | null = null;
private system_error_handler_: ((error: Error, systemName?: string) => 'continue' | 'pause') | null = null;
private frame_paused_ = false;
+ private user_paused_ = false;
+ private step_pending_ = false;
+ private play_speed_ = 1.0;
private constructor() {
this.world_ = new World();
@@ -234,6 +237,26 @@ export class App {
return this;
}
+ setPaused(paused: boolean): void {
+ this.user_paused_ = paused;
+ }
+
+ isPaused(): boolean {
+ return this.user_paused_;
+ }
+
+ stepFrame(): void {
+ this.step_pending_ = true;
+ }
+
+ setPlaySpeed(speed: number): void {
+ this.play_speed_ = Math.max(0.1, Math.min(4.0, speed));
+ }
+
+ getPlaySpeed(): number {
+ return this.play_speed_;
+ }
+
// =========================================================================
// Resource Access
// =========================================================================
@@ -294,32 +317,41 @@ export class App {
const deltaMs = currentTime - this.lastTime_;
this.lastTime_ = currentTime;
- const delta = Math.min(deltaMs / 1000, this.maxDeltaTime_);
+ const rawDelta = Math.min(deltaMs / 1000, this.maxDeltaTime_);
+ const delta = rawDelta * this.play_speed_;
this.updateTime(delta);
this.world_.resetQueryPool();
this.frame_paused_ = false;
- this.runSchedule(Schedule.First);
+ if (this.user_paused_ && !this.step_pending_) {
+ this.runSchedule(Schedule.Last);
+ } else {
+ this.runSchedule(Schedule.First);
+
+ this.fixedAccumulator_ += delta;
+ let fixedSteps = 0;
+ while (this.fixedAccumulator_ >= this.fixedTimestep_ && fixedSteps < this.maxFixedSteps_) {
+ this.fixedAccumulator_ -= this.fixedTimestep_;
+ this.runSchedule(Schedule.FixedPreUpdate);
+ this.runSchedule(Schedule.FixedUpdate);
+ this.runSchedule(Schedule.FixedPostUpdate);
+ fixedSteps++;
+ }
+ if (fixedSteps >= this.maxFixedSteps_) {
+ this.fixedAccumulator_ = 0;
+ }
+
+ this.runSchedule(Schedule.PreUpdate);
+ this.runSchedule(Schedule.Update);
+ this.runSchedule(Schedule.PostUpdate);
+ this.runSchedule(Schedule.Last);
- this.fixedAccumulator_ += delta;
- let fixedSteps = 0;
- while (this.fixedAccumulator_ >= this.fixedTimestep_ && fixedSteps < this.maxFixedSteps_) {
- this.fixedAccumulator_ -= this.fixedTimestep_;
- this.runSchedule(Schedule.FixedPreUpdate);
- this.runSchedule(Schedule.FixedUpdate);
- this.runSchedule(Schedule.FixedPostUpdate);
- fixedSteps++;
- }
- if (fixedSteps >= this.maxFixedSteps_) {
- this.fixedAccumulator_ = 0;
+ if (this.step_pending_) {
+ this.step_pending_ = false;
+ }
}
- this.runSchedule(Schedule.PreUpdate);
- this.runSchedule(Schedule.Update);
- this.runSchedule(Schedule.PostUpdate);
- this.runSchedule(Schedule.Last);
-
requestAnimationFrame(this.mainLoop);
};
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 8e78f43c3..2996c01ec 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -129,6 +129,10 @@ export function registerComponent(name: string, def: AnyComponentDef): void {
componentRegistry.set(name, def);
}
+export function getAllRegisteredComponents(): Map<string, AnyComponentDef> {
+ return componentRegistry;
+}
+
export function getComponent(name: string): AnyComponentDef | undefined {
return componentRegistry.get(name) ?? getUserComponent(name);
}
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 53295b208..691e9dd78 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -4,7 +4,7 @@
*/
import { Entity } from './types';
-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponent } from './component';
+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents } from './component';
import type { CppRegistry } from './wasm';
import { validateComponentData, formatValidationErrors } from './validation';
import { handleWasmError } from './wasmError';
@@ -407,16 +407,8 @@ export class World {
try { if (methods.has(entity)) types.push(name); } catch {}
}
if (this.cppRegistry_) {
- const knownBuiltins = [
- 'LocalTransform', 'GlobalTransform', 'Sprite', 'Camera', 'Text',
- 'Velocity', 'Parent', 'Children', 'BitmapText', 'SpineAnimation',
- 'Canvas', 'UIRect', 'Interaction', 'Mask', 'LayoutGroup', 'LayoutElement',
- 'TextInput', 'RigidBody', 'BoxCollider', 'CircleCollider', 'CapsuleCollider',
- ];
- for (const name of knownBuiltins) {
- if (types.includes(name)) continue;
- const comp = getComponent(name);
- if (comp && isBuiltinComponent(comp)) {
+ for (const [name, comp] of getAllRegisteredComponents()) {
+ if (isBuiltinComponent(comp) && !types.includes(name)) {
try {
const m = this.getBuiltinMethods(comp._cppName);
if (m.has(entity)) types.push(name);
@@ -426,11 +418,15 @@ export class World {
}
const ids = this.entityComponents_.get(entity);
if (ids) {
- for (const id of ids) {
- for (const [, storage] of this.tsStorage_) {
- if (storage.has(entity) && storage === this.tsStorage_.get(id)) {
- for (const [name, def] of this.findScriptName(id)) {
- if (!types.includes(name)) types.push(name);
+ const registry = typeof window !== 'undefined'
+ ? (window as any).__esengine_componentRegistry as Map<string, any> | undefined
+ : undefined;
+ if (registry) {
+ for (const id of ids) {
+ for (const [name, def] of registry) {
+ if (def._id === id) {
+ types.push(name);
+ break;
}
}
}
@@ -439,20 +435,6 @@ export class World {
return types;
}
- private findScriptName(id: symbol): [string, ComponentDef<any>][] {
- const results: [string, ComponentDef<any>][] = [];
- if (typeof window !== 'undefined' && (window as any).__esengine_componentRegistry) {
- const registry = (window as any).__esengine_componentRegistry as Map<string, ComponentDef<any>>;
- for (const [name, def] of registry) {
- if (def._id === id) {
- results.push([name, def]);
- break;
- }
- }
- }
- return results;
- }
-
getEntitiesWithComponents(
components: AnyComponentDef[],
withFilters: AnyComponentDef[] = [],